@h-ai/ai 1.0.0-beta.35 → 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,15 +1,14 @@
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-PELGM4XN.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-PELGM4XN.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
4
  import { aiM } from './chunk-CLCPQTW2.js';
5
- import { HaiAIError } from './chunk-JD6YODU6.js';
6
- export { HaiAIError } from './chunk-JD6YODU6.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';
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';
11
+ import { core } from '@h-ai/core';
13
12
  import { datapipe } from '@h-ai/datapipe';
14
13
  import { JsonRpcTransportFactory, ClientFactory } from '@a2a-js/sdk/client';
15
14
  import { Buffer } from 'buffer';
@@ -42,11 +41,9 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
42
41
  import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
43
42
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
44
43
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
45
- export { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
46
- export { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';
47
- 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';
48
46
  import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
49
- export { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
50
47
  import { reldb } from '@h-ai/reldb';
51
48
  import { vecdb, HaiVecdbError } from '@h-ai/vecdb';
52
49
  import { tools } from '@h-ai/tools';
@@ -705,10 +702,10 @@ async function executeRemoteAgentCall(remoteUrl, message, options) {
705
702
  } else {
706
703
  result = {};
707
704
  }
708
- return ok(result);
705
+ return core.ok(result);
709
706
  } catch (error) {
710
707
  const errorName = error instanceof Error ? error.name : "UnknownError";
711
- return err(HaiAIError.A2A_REMOTE_CALL_FAILED, aiM("ai_a2aRemoteCallFailed", {
708
+ return core.err(HaiAIError.A2A_REMOTE_CALL_FAILED, aiM("ai_a2aRemoteCallFailed", {
712
709
  params: { url: safeLabel, error: errorName }
713
710
  }));
714
711
  }
@@ -735,10 +732,10 @@ function createA2AOperations(options, deps) {
735
732
  close: () => requestHandler.close(),
736
733
  registerExecutor() {
737
734
  logger2.warn("A2A executor already registered, ignoring duplicate registerExecutor call");
738
- return ok(void 0);
735
+ return core.ok(void 0);
739
736
  },
740
737
  getAgentCard() {
741
- return ok(buildAgentCardDocument(agentCardConfig));
738
+ return core.ok(buildAgentCardDocument(agentCardConfig));
742
739
  },
743
740
  async handleRequest(requestBody, context) {
744
741
  const agentId = typeof context?.agentId === "string" ? context.agentId : void 0;
@@ -775,9 +772,9 @@ function createA2AOperations(options, deps) {
775
772
  },
776
773
  { offset: filter.offset ?? 0, limit: filter.limit ?? 50 }
777
774
  );
778
- return ok(page);
775
+ return core.ok(page);
779
776
  } catch {
780
- return err(HaiAIError.A2A_LIST_MESSAGES_FAILED, aiM("ai_a2aListMessagesFailed"));
777
+ return core.err(HaiAIError.A2A_LIST_MESSAGES_FAILED, aiM("ai_a2aListMessagesFailed"));
781
778
  }
782
779
  },
783
780
  async callRemoteAgent(remoteUrl, message, options2) {
@@ -793,14 +790,14 @@ function createA2ALazyProxy(deps) {
793
790
  }
794
791
  const a2aConfig = deps.getA2AConfig();
795
792
  if (!a2aConfig) {
796
- return err(HaiAIError.A2A_NOT_CONFIGURED, aiM("ai_a2aNotConfigured"));
793
+ return core.err(HaiAIError.A2A_NOT_CONFIGURED, aiM("ai_a2aNotConfigured"));
797
794
  }
798
795
  if (deps.getA2AImpl()) {
799
- return err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_a2aExecutorAlreadyRegistered"));
796
+ return core.err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_a2aExecutorAlreadyRegistered"));
800
797
  }
801
798
  const stores = deps.getStores();
802
799
  if (!stores) {
803
- return err(HaiAIError.STORE_FAILED, aiM("ai_internalError", {
800
+ return core.err(HaiAIError.STORE_FAILED, aiM("ai_internalError", {
804
801
  params: { error: "StoreProvider not available" }
805
802
  }));
806
803
  }
@@ -811,7 +808,7 @@ function createA2ALazyProxy(deps) {
811
808
  );
812
809
  deps.setA2AImpl(impl);
813
810
  logger2.info("A2A executor registered", { agentName: a2aConfig.agentCard.name });
814
- return ok(void 0);
811
+ return core.ok(void 0);
815
812
  },
816
813
  getAgentCard() {
817
814
  const impl = deps.getA2AImpl();
@@ -819,10 +816,10 @@ function createA2ALazyProxy(deps) {
819
816
  return impl.getAgentCard();
820
817
  const a2aConfig = deps.getA2AConfig();
821
818
  if (a2aConfig)
822
- return ok(buildAgentCardDocument({ ...a2aConfig.agentCard, security: a2aConfig.security }));
819
+ return core.ok(buildAgentCardDocument({ ...a2aConfig.agentCard, security: a2aConfig.security }));
823
820
  if (!deps.isInitialized())
824
821
  return deps.notInitializedResult();
825
- return err(HaiAIError.A2A_NOT_CONFIGURED, aiM("ai_a2aNotConfigured"));
822
+ return core.err(HaiAIError.A2A_NOT_CONFIGURED, aiM("ai_a2aNotConfigured"));
826
823
  },
827
824
  async handleRequest(requestBody, context) {
828
825
  const impl = deps.getA2AImpl();
@@ -847,7 +844,7 @@ function createA2ALazyProxy(deps) {
847
844
  return impl.listMessages(filter);
848
845
  if (!deps.isInitialized())
849
846
  return deps.notInitializedResult();
850
- return err(HaiAIError.A2A_NOT_CONFIGURED, aiM("ai_a2aNotConfigured"));
847
+ return core.err(HaiAIError.A2A_NOT_CONFIGURED, aiM("ai_a2aNotConfigured"));
851
848
  },
852
849
  async callRemoteAgent(remoteUrl, message, options) {
853
850
  const impl = deps.getA2AImpl();
@@ -899,7 +896,7 @@ var mappings = {
899
896
  function acpError(error) {
900
897
  const failure = error instanceof ACPFailure ? error : new ACPFailure(error instanceof ZodError ? "invalid" : "failed");
901
898
  const [code, message] = mappings[failure.kind];
902
- return err(HaiAIError[code], aiM(message), failure.details);
899
+ return core.err(HaiAIError[code], aiM(message), failure.details);
903
900
  }
904
901
 
905
902
  // src/acp/ai-acp-adapters.ts
@@ -1239,11 +1236,11 @@ function createResourceRegistry(store, schema, configured, isOpen) {
1239
1236
  }
1240
1237
  async function protect(operation) {
1241
1238
  if (!isOpen())
1242
- return err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
1239
+ return core.err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
1243
1240
  try {
1244
- return ok(await operation());
1241
+ return core.ok(await operation());
1245
1242
  } catch {
1246
- return err(
1243
+ return core.err(
1247
1244
  HaiAIError.RESOURCE_OPERATION_FAILED,
1248
1245
  aiM("ai_resourceOperationFailed")
1249
1246
  );
@@ -1251,34 +1248,34 @@ function createResourceRegistry(store, schema, configured, isOpen) {
1251
1248
  }
1252
1249
  async function write(input, update, expectedVersion) {
1253
1250
  if (!isOpen())
1254
- return err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
1251
+ return core.err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
1255
1252
  const parsed = schema.safeParse(input);
1256
1253
  if (!parsed.success || !parsed.data.id)
1257
- return err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
1254
+ return core.err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
1258
1255
  const value = parsed.data;
1259
1256
  if (config.has(value.id))
1260
- return err(HaiAIError.RESOURCE_READ_ONLY, aiM("ai_resourceReadOnly"));
1257
+ return core.err(HaiAIError.RESOURCE_READ_ONLY, aiM("ai_resourceReadOnly"));
1261
1258
  try {
1262
1259
  const previous = await store.readVersioned(value.id);
1263
1260
  const exists = previous && !previous.data.__deleted;
1264
1261
  if (update && !exists)
1265
- return err(HaiAIError.RESOURCE_NOT_FOUND, aiM("ai_resourceNotFound"));
1262
+ return core.err(HaiAIError.RESOURCE_NOT_FOUND, aiM("ai_resourceNotFound"));
1266
1263
  if (!update && exists || expectedVersion !== void 0 && expectedVersion !== previous?.version) {
1267
- return err(HaiAIError.RESOURCE_CONFLICT, aiM("ai_resourceConflict"));
1264
+ return core.err(HaiAIError.RESOURCE_CONFLICT, aiM("ai_resourceConflict"));
1268
1265
  }
1269
1266
  const version = await store.compareAndSwap(value.id, {
1270
1267
  expectedVersion: previous?.version,
1271
1268
  data: value
1272
1269
  });
1273
1270
  if (!version)
1274
- return err(HaiAIError.RESOURCE_CONFLICT, aiM("ai_resourceConflict"));
1275
- return ok({
1271
+ return core.err(HaiAIError.RESOURCE_CONFLICT, aiM("ai_resourceConflict"));
1272
+ return core.ok({
1276
1273
  value: structuredClone(value),
1277
1274
  source: "database",
1278
1275
  version
1279
1276
  });
1280
1277
  } catch {
1281
- return err(
1278
+ return core.err(
1282
1279
  HaiAIError.RESOURCE_OPERATION_FAILED,
1283
1280
  aiM("ai_resourceOperationFailed")
1284
1281
  );
@@ -1290,31 +1287,31 @@ function createResourceRegistry(store, schema, configured, isOpen) {
1290
1287
  const result = await protect(() => read(id3));
1291
1288
  if (!result.success)
1292
1289
  return result;
1293
- 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"));
1294
1291
  },
1295
1292
  register: (input) => write(input, false),
1296
1293
  update: (input, version) => write(input, true, version),
1297
1294
  remove: async (id3, expectedVersion) => {
1298
1295
  if (!isOpen())
1299
- return err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
1296
+ return core.err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
1300
1297
  if (config.has(id3))
1301
- return err(HaiAIError.RESOURCE_READ_ONLY, aiM("ai_resourceReadOnly"));
1298
+ return core.err(HaiAIError.RESOURCE_READ_ONLY, aiM("ai_resourceReadOnly"));
1302
1299
  try {
1303
1300
  const previous = await store.readVersioned(id3);
1304
1301
  if (!previous || previous.data.__deleted)
1305
- return err(HaiAIError.RESOURCE_NOT_FOUND, aiM("ai_resourceNotFound"));
1302
+ return core.err(HaiAIError.RESOURCE_NOT_FOUND, aiM("ai_resourceNotFound"));
1306
1303
  if (expectedVersion !== void 0 && expectedVersion !== previous.version) {
1307
- return err(HaiAIError.RESOURCE_CONFLICT, aiM("ai_resourceConflict"));
1304
+ return core.err(HaiAIError.RESOURCE_CONFLICT, aiM("ai_resourceConflict"));
1308
1305
  }
1309
1306
  if (!await store.compareAndSwap(id3, {
1310
1307
  expectedVersion: previous.version,
1311
1308
  data: { ...previous.data, __deleted: true }
1312
1309
  })) {
1313
- return err(HaiAIError.RESOURCE_CONFLICT, aiM("ai_resourceConflict"));
1310
+ return core.err(HaiAIError.RESOURCE_CONFLICT, aiM("ai_resourceConflict"));
1314
1311
  }
1315
- return ok(void 0);
1312
+ return core.ok(void 0);
1316
1313
  } catch {
1317
- return err(
1314
+ return core.err(
1318
1315
  HaiAIError.RESOURCE_OPERATION_FAILED,
1319
1316
  aiM("ai_resourceOperationFailed")
1320
1317
  );
@@ -3846,7 +3843,7 @@ function createACPPlatform(deps) {
3846
3843
  }
3847
3844
  async function protectedCall(operation) {
3848
3845
  try {
3849
- return ok(await operation());
3846
+ return core.ok(await operation());
3850
3847
  } catch (error) {
3851
3848
  return acpError(error);
3852
3849
  }
@@ -4713,7 +4710,7 @@ function createACPOperations(provider, config, extensions = {}, modelConfig = as
4713
4710
  const task = (async () => {
4714
4711
  try {
4715
4712
  ensure();
4716
- return ok(await operation());
4713
+ return core.ok(await operation());
4717
4714
  } catch (error) {
4718
4715
  return acpError(error);
4719
4716
  }
@@ -5481,11 +5478,11 @@ function createACPOperations(provider, config, extensions = {}, modelConfig = as
5481
5478
  },
5482
5479
  workspaces: {
5483
5480
  /** 从受信仓库的一次提交读取有界普通文件快照。 */
5484
- readGitSnapshot: (input, signal) => protectResult(async () => ok(await readGitSnapshot(input, signal))),
5481
+ readGitSnapshot: (input, signal) => protectResult(async () => core.ok(await readGitSnapshot(input, signal))),
5485
5482
  /** 比较快照并生成可下载的补丁。 */
5486
- 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))),
5487
5484
  /** 应用重新验权后,向独立任务分支提交并普通推送。 */
5488
- publishSnapshot: (input, signal) => protectResult(async () => ok(await publishSnapshot(input, signal))),
5485
+ publishSnapshot: (input, signal) => protectResult(async () => core.ok(await publishSnapshot(input, signal))),
5489
5486
  /**
5490
5487
  * 新增数据库工作区并归一化存储位置;拒绝目录重叠或同一 volume 重复登记。
5491
5488
  * @param input - 工作区存储位置、显式 Git 主分支和环境变量引用。
@@ -6414,7 +6411,7 @@ function createDoubaoAudioProvider() {
6414
6411
  if (event.type === "transcript" && event.final)
6415
6412
  finalText = event.text;
6416
6413
  }
6417
- return ok({ text: finalText });
6414
+ return core.ok({ text: finalText });
6418
6415
  } catch (error) {
6419
6416
  logger5.debug("Doubao transcribe failed", {
6420
6417
  error: errorMessage(error)
@@ -6508,7 +6505,7 @@ function createDoubaoAudioProvider() {
6508
6505
  signal: request2.signal
6509
6506
  }))
6510
6507
  chunks.push(audio);
6511
- return ok({
6508
+ return core.ok({
6512
6509
  data: concatChunks(chunks),
6513
6510
  format: out.format,
6514
6511
  sampleRate: out.sampleRate,
@@ -6631,7 +6628,7 @@ function createIndexTtsAudioProvider() {
6631
6628
  async function synthesize(request2) {
6632
6629
  const { model, text, language: language2, speakerReference, styleReference, styleStrength, speed, targetDurationMs, durationToleranceMs, format, sampleRate, signal } = request2;
6633
6630
  if (!speakerReference) {
6634
- return err(HaiAIError.AUDIO_INVALID_REQUEST, aiM("ai_audioInvalidRequest", {
6631
+ return core.err(HaiAIError.AUDIO_INVALID_REQUEST, aiM("ai_audioInvalidRequest", {
6635
6632
  params: { reason: "speaker_reference is required" }
6636
6633
  }));
6637
6634
  }
@@ -6675,12 +6672,12 @@ function createIndexTtsAudioProvider() {
6675
6672
  dispatcher
6676
6673
  });
6677
6674
  if (!response.ok) {
6678
- return err(HaiAIError.AUDIO_UPSTREAM_ERROR, aiM("ai_audioUpstreamError", {
6675
+ return core.err(HaiAIError.AUDIO_UPSTREAM_ERROR, aiM("ai_audioUpstreamError", {
6679
6676
  params: { error: await describeHttpError(response) }
6680
6677
  }));
6681
6678
  }
6682
6679
  const data = new Uint8Array(await response.arrayBuffer());
6683
- return ok(buildSynthesisResult(data, out, response.headers));
6680
+ return core.ok(buildSynthesisResult(data, out, response.headers));
6684
6681
  } finally {
6685
6682
  await dispatcher.close();
6686
6683
  }
@@ -6983,7 +6980,7 @@ function createMimoAudioProvider() {
6983
6980
  const { model, audio, language: language2, signal } = request2;
6984
6981
  const mime = MIMO_ASR_MIME[audio.format];
6985
6982
  if (!mime) {
6986
- return err(HaiAIError.AUDIO_UNSUPPORTED_INPUT, aiM("ai_audioUnsupportedInput", {
6983
+ return core.err(HaiAIError.AUDIO_UNSUPPORTED_INPUT, aiM("ai_audioUnsupportedInput", {
6987
6984
  params: { provider: "mimo", reason: `format ${audio.format} (only wav/mp3)` }
6988
6985
  }));
6989
6986
  }
@@ -7005,13 +7002,13 @@ function createMimoAudioProvider() {
7005
7002
  asr_options: { language: language2 ?? "auto" }
7006
7003
  }, requestSignal);
7007
7004
  if (!response.ok) {
7008
- return err(HaiAIError.AUDIO_UPSTREAM_ERROR, aiM("ai_audioUpstreamError", {
7005
+ return core.err(HaiAIError.AUDIO_UPSTREAM_ERROR, aiM("ai_audioUpstreamError", {
7009
7006
  params: { error: await describeHttpError(response) }
7010
7007
  }));
7011
7008
  }
7012
7009
  const body = await response.json();
7013
7010
  const text = body.choices?.[0]?.message?.content ?? "";
7014
- return ok({ text });
7011
+ return core.ok({ text });
7015
7012
  } catch (error) {
7016
7013
  logger7.debug("MiMo transcribe failed", {
7017
7014
  error: errorMessage(error)
@@ -7079,18 +7076,18 @@ function createMimoAudioProvider() {
7079
7076
  }
7080
7077
  }, requestSignal);
7081
7078
  if (!response.ok) {
7082
- return err(HaiAIError.AUDIO_UPSTREAM_ERROR, aiM("ai_audioUpstreamError", {
7079
+ return core.err(HaiAIError.AUDIO_UPSTREAM_ERROR, aiM("ai_audioUpstreamError", {
7083
7080
  params: { error: await describeHttpError(response) }
7084
7081
  }));
7085
7082
  }
7086
7083
  const body = await response.json();
7087
7084
  const base64 = body.choices?.[0]?.message?.audio?.data;
7088
7085
  if (!base64) {
7089
- return err(HaiAIError.AUDIO_UPSTREAM_ERROR, aiM("ai_audioUpstreamError", {
7086
+ return core.err(HaiAIError.AUDIO_UPSTREAM_ERROR, aiM("ai_audioUpstreamError", {
7090
7087
  params: { error: "missing audio data" }
7091
7088
  }));
7092
7089
  }
7093
- return ok({
7090
+ return core.ok({
7094
7091
  data: fromBase64(base64),
7095
7092
  format: out.format,
7096
7093
  sampleRate: out.sampleRate,
@@ -7203,7 +7200,7 @@ function createOpenAIAudioProvider() {
7203
7200
  async function transcribe(request2) {
7204
7201
  const { model, audio, language: language2, contextHints, signal } = request2;
7205
7202
  if (!model.apiKey) {
7206
- return err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_audioMissingApiKey", {
7203
+ return core.err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_audioMissingApiKey", {
7207
7204
  params: { provider: "openai" }
7208
7205
  }));
7209
7206
  }
@@ -7218,7 +7215,7 @@ function createOpenAIAudioProvider() {
7218
7215
  prompt: contextHints.join(", ")
7219
7216
  } : {}
7220
7217
  }, { signal });
7221
- return ok({ text: result.text });
7218
+ return core.ok({ text: result.text });
7222
7219
  } catch (error) {
7223
7220
  logger8.debug("OpenAI transcribe failed", {
7224
7221
  error: errorMessage(error)
@@ -7265,7 +7262,7 @@ function createOpenAIAudioProvider() {
7265
7262
  async function synthesize(request2) {
7266
7263
  const { model, text, voice, instruction, format, sampleRate, signal } = request2;
7267
7264
  if (!model.apiKey) {
7268
- return err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_audioMissingApiKey", {
7265
+ return core.err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_audioMissingApiKey", {
7269
7266
  params: { provider: "openai" }
7270
7267
  }));
7271
7268
  }
@@ -7280,7 +7277,7 @@ function createOpenAIAudioProvider() {
7280
7277
  ...instruction ? { instructions: instruction } : {}
7281
7278
  }, { signal });
7282
7279
  const data = new Uint8Array(await response.arrayBuffer());
7283
- return ok({
7280
+ return core.ok({
7284
7281
  data,
7285
7282
  format: out.format,
7286
7283
  sampleRate: out.sampleRate,
@@ -7393,7 +7390,7 @@ function createQwenAudioProvider() {
7393
7390
  finalText = finalText ? `${finalText}${event.text}` : event.text;
7394
7391
  }
7395
7392
  }
7396
- return ok({ text: finalText });
7393
+ return core.ok({ text: finalText });
7397
7394
  } catch (error) {
7398
7395
  logger9.debug("Qwen transcribe failed", {
7399
7396
  error: errorMessage(error)
@@ -7497,7 +7494,7 @@ function createQwenAudioProvider() {
7497
7494
  signal: request2.signal
7498
7495
  }))
7499
7496
  chunks.push(audio);
7500
- return ok({
7497
+ return core.ok({
7501
7498
  data: concatChunks(chunks),
7502
7499
  format: out.format,
7503
7500
  sampleRate: out.sampleRate,
@@ -7640,12 +7637,12 @@ function createWhisperAudioProvider() {
7640
7637
  signal: combineSignal(signal, model.timeout)
7641
7638
  });
7642
7639
  if (!response.ok) {
7643
- return err(HaiAIError.AUDIO_UPSTREAM_ERROR, aiM("ai_audioUpstreamError", {
7640
+ return core.err(HaiAIError.AUDIO_UPSTREAM_ERROR, aiM("ai_audioUpstreamError", {
7644
7641
  params: { error: await describeHttpError(response) }
7645
7642
  }));
7646
7643
  }
7647
7644
  const body = await response.json();
7648
- return ok(mapWhisperResponse(body));
7645
+ return core.ok(mapWhisperResponse(body));
7649
7646
  } catch (error) {
7650
7647
  logger10.debug("Whisper transcribe failed", {
7651
7648
  error: errorMessage(error)
@@ -7732,7 +7729,7 @@ function createAudioOperations(config) {
7732
7729
  }
7733
7730
  async function transcribe(request2) {
7734
7731
  if (!request2.audio?.data?.length) {
7735
- return err(HaiAIError.AUDIO_INVALID_REQUEST, aiM("ai_audioInvalidRequest", {
7732
+ return core.err(HaiAIError.AUDIO_INVALID_REQUEST, aiM("ai_audioInvalidRequest", {
7736
7733
  params: { reason: "empty audio" }
7737
7734
  }));
7738
7735
  }
@@ -7745,7 +7742,7 @@ function createAudioOperations(config) {
7745
7742
  const provider = getProvider(resolved.data.provider);
7746
7743
  const transcription = provider.transcription;
7747
7744
  if (!transcription) {
7748
- return err(HaiAIError.AUDIO_UNSUPPORTED_INPUT, aiM("ai_audioUnsupportedInput", {
7745
+ return core.err(HaiAIError.AUDIO_UNSUPPORTED_INPUT, aiM("ai_audioUnsupportedInput", {
7749
7746
  params: { provider: resolved.data.provider, reason: "transcription" }
7750
7747
  }));
7751
7748
  }
@@ -7832,7 +7829,7 @@ function createAudioOperations(config) {
7832
7829
  }
7833
7830
  async function synthesize(request2) {
7834
7831
  if (!request2.text) {
7835
- return err(HaiAIError.AUDIO_INVALID_REQUEST, aiM("ai_audioInvalidRequest", {
7832
+ return core.err(HaiAIError.AUDIO_INVALID_REQUEST, aiM("ai_audioInvalidRequest", {
7836
7833
  params: { reason: "empty text" }
7837
7834
  }));
7838
7835
  }
@@ -7848,7 +7845,7 @@ function createAudioOperations(config) {
7848
7845
  const provider = getProvider(resolved.data.provider);
7849
7846
  const synthesis = provider.synthesis;
7850
7847
  if (!synthesis) {
7851
- return err(HaiAIError.AUDIO_UNSUPPORTED_INPUT, aiM("ai_audioUnsupportedInput", {
7848
+ return core.err(HaiAIError.AUDIO_UNSUPPORTED_INPUT, aiM("ai_audioUnsupportedInput", {
7852
7849
  params: { provider: resolved.data.provider, reason: "synthesis" }
7853
7850
  }));
7854
7851
  }
@@ -7975,7 +7972,7 @@ function createAudioOperations(config) {
7975
7972
  if (!resolved.success)
7976
7973
  return resolved;
7977
7974
  const capabilities = getProvider(resolved.data.provider).getCapabilities(resolved.data);
7978
- return ok(request2.operation === "transcribe" ? { transcribe: capabilities.transcribe } : { synthesize: capabilities.synthesize });
7975
+ return core.ok(request2.operation === "transcribe" ? { transcribe: capabilities.transcribe } : { synthesize: capabilities.synthesize });
7979
7976
  }
7980
7977
  return {
7981
7978
  transcribe,
@@ -8130,7 +8127,7 @@ var CONVERSATION_SUMMARY_PREFIX = "[Conversation Summary]";
8130
8127
  var CONVERSATION_SUMMARY_NAME = "hai_internal_conversation_summary_v1";
8131
8128
  function completeCompression(result, maxTokens) {
8132
8129
  if (result.compressedTokens > maxTokens) {
8133
- return err(
8130
+ return core.err(
8134
8131
  HaiAIError.CONTEXT_BUDGET_EXCEEDED,
8135
8132
  aiM("ai_contextBudgetExceeded", {
8136
8133
  params: {
@@ -8140,7 +8137,7 @@ function completeCompression(result, maxTokens) {
8140
8137
  })
8141
8138
  );
8142
8139
  }
8143
- return ok(result);
8140
+ return core.ok(result);
8144
8141
  }
8145
8142
  function isGeneratedConversationSummary(message) {
8146
8143
  return message.role === "system" && message.name === CONVERSATION_SUMMARY_NAME;
@@ -8276,7 +8273,7 @@ function createCompressOperations(config, token, summary, modelMaxTokens) {
8276
8273
  try {
8277
8274
  const originalTokens = token.estimateMessages(messages);
8278
8275
  if (originalTokens <= maxTokens) {
8279
- return ok({
8276
+ return core.ok({
8280
8277
  messages: [...messages],
8281
8278
  originalTokens,
8282
8279
  compressedTokens: originalTokens,
@@ -8390,7 +8387,7 @@ ${summaryText}`
8390
8387
  }, maxTokens);
8391
8388
  } catch (error) {
8392
8389
  logger12.error("Context compression failed", { error });
8393
- return err(HaiAIError.CONTEXT_COMPRESS_FAILED, aiM("ai_contextCompressFailed", {
8390
+ return core.err(HaiAIError.CONTEXT_COMPRESS_FAILED, aiM("ai_contextCompressFailed", {
8394
8391
  params: {
8395
8392
  error: String(error)
8396
8393
  }
@@ -8475,7 +8472,7 @@ var logger13 = core.logger.child({ module: "ai", scope: "context" });
8475
8472
  var GENERATION_LEASE_MS = 3e4;
8476
8473
  function contextFailure(error) {
8477
8474
  const code = error instanceof ContextStateError ? error.definition : HaiAIError.STORE_FAILED;
8478
- return err(code, aiM("ai_sessionFailed", {
8475
+ return core.err(code, aiM("ai_sessionFailed", {
8479
8476
  params: {
8480
8477
  error: String(error)
8481
8478
  }
@@ -8652,7 +8649,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
8652
8649
  });
8653
8650
  if (!generation) {
8654
8651
  if (concurrency === "reject")
8655
- return err(HaiAIError.CONTEXT_BUSY, aiM("ai_contextBusy"));
8652
+ return core.err(HaiAIError.CONTEXT_BUSY, aiM("ai_contextBusy"));
8656
8653
  await waitForContext(caller);
8657
8654
  continue;
8658
8655
  }
@@ -8683,7 +8680,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
8683
8680
  signal.addEventListener("abort", onAbort2, { once: true });
8684
8681
  if (signal.aborted)
8685
8682
  onAbort2();
8686
- return ok({ generation, signal, release });
8683
+ return core.ok({ generation, signal, release });
8687
8684
  }
8688
8685
  } catch (error) {
8689
8686
  return contextFailure(error);
@@ -8733,7 +8730,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
8733
8730
  await append(candidate, message);
8734
8731
  return { value: void 0 };
8735
8732
  });
8736
- return ok(void 0);
8733
+ return core.ok(void 0);
8737
8734
  } catch (error) {
8738
8735
  return contextFailure(error);
8739
8736
  }
@@ -8741,22 +8738,22 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
8741
8738
  async reload() {
8742
8739
  try {
8743
8740
  await access.read();
8744
- return ok(void 0);
8741
+ return core.ok(void 0);
8745
8742
  } catch (error) {
8746
8743
  return contextFailure(error);
8747
8744
  }
8748
8745
  },
8749
8746
  getMessages() {
8750
- return ok(structuredClone(state.messages));
8747
+ return core.ok(structuredClone(state.messages));
8751
8748
  },
8752
8749
  getTokenUsage() {
8753
- return ok({
8750
+ return core.ok({
8754
8751
  current: tokenOps.estimateMessages(state.messages),
8755
8752
  budget: managerMaxTokens
8756
8753
  });
8757
8754
  },
8758
8755
  getSummaries() {
8759
- return ok(structuredClone(state.summaries));
8756
+ return core.ok(structuredClone(state.summaries));
8760
8757
  },
8761
8758
  async save() {
8762
8759
  const flushed = await manager.flush();
@@ -8765,7 +8762,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
8765
8762
  try {
8766
8763
  await access.mutate(() => ({ value: void 0 }));
8767
8764
  await touchSession(scope);
8768
- return ok(void 0);
8765
+ return core.ok(void 0);
8769
8766
  } catch (error) {
8770
8767
  return contextFailure(error);
8771
8768
  }
@@ -8793,13 +8790,13 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
8793
8790
  producer.stop();
8794
8791
  }
8795
8792
  }
8796
- return ok(void 0);
8793
+ return core.ok(void 0);
8797
8794
  } catch (error) {
8798
8795
  return contextFailure(error);
8799
8796
  }
8800
8797
  },
8801
8798
  getTurns() {
8802
- return ok(structuredClone(state.turns));
8799
+ return core.ok(structuredClone(state.turns));
8803
8800
  },
8804
8801
  async markTurnSpeaking(turnId) {
8805
8802
  try {
@@ -8818,7 +8815,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
8818
8815
  notAfter: active.phase === "generating" ? active.expiresAt : void 0
8819
8816
  };
8820
8817
  });
8821
- return ok(void 0);
8818
+ return core.ok(void 0);
8822
8819
  } catch (error) {
8823
8820
  return contextFailure(error);
8824
8821
  }
@@ -8831,7 +8828,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
8831
8828
  },
8832
8829
  async consolidate(consolidateOpts) {
8833
8830
  if (!deps?.summary || !deps?.memory) {
8834
- return err(HaiAIError.MEMORY_PROMOTE_FAILED, aiM("ai_memoryPromoteFailed", {
8831
+ return core.err(HaiAIError.MEMORY_PROMOTE_FAILED, aiM("ai_memoryPromoteFailed", {
8835
8832
  params: { error: "summary/memory deps unavailable" }
8836
8833
  }));
8837
8834
  }
@@ -8849,7 +8846,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
8849
8846
  return summaryResult;
8850
8847
  const summaryText = summaryResult.data;
8851
8848
  if (!summaryText.trim()) {
8852
- return ok({ summary: summaryText, memories: [] });
8849
+ return core.ok({ summary: summaryText, memories: [] });
8853
8850
  }
8854
8851
  const durableScope = consolidateOpts?.scope ?? options.memory?.scope;
8855
8852
  const extracted = await deps.memory.extract(
@@ -8866,10 +8863,10 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
8866
8863
  );
8867
8864
  if (!extracted.success)
8868
8865
  return extracted;
8869
- return ok({ summary: summaryText, memories: extracted.data });
8866
+ return core.ok({ summary: summaryText, memories: extracted.data });
8870
8867
  } catch (error) {
8871
8868
  logger13.error("Context consolidate failed", { error });
8872
- return err(HaiAIError.MEMORY_PROMOTE_FAILED, aiM("ai_memoryPromoteFailed", {
8869
+ return core.err(HaiAIError.MEMORY_PROMOTE_FAILED, aiM("ai_memoryPromoteFailed", {
8873
8870
  params: {
8874
8871
  error: String(error)
8875
8872
  }
@@ -8885,9 +8882,9 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
8885
8882
  await Promise.allSettled([...pendingMemoryTasks]);
8886
8883
  const failed = failedMemoryTasks;
8887
8884
  failedMemoryTasks = 0;
8888
- return failed > 0 ? err(HaiAIError.MEMORY_EXTRACT_FAILED, aiM("ai_contextMemoryTasksFailed", {
8885
+ return failed > 0 ? core.err(HaiAIError.MEMORY_EXTRACT_FAILED, aiM("ai_contextMemoryTasksFailed", {
8889
8886
  params: { count: failed }
8890
- })) : ok(void 0);
8887
+ })) : core.ok(void 0);
8891
8888
  })().finally(() => {
8892
8889
  memoryFlush = void 0;
8893
8890
  });
@@ -8896,7 +8893,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
8896
8893
  // ─── chat/chatStream 编排 ───
8897
8894
  async chat(message, chatOpts) {
8898
8895
  if (!deps?.llm) {
8899
- return err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
8896
+ return core.err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
8900
8897
  }
8901
8898
  const acq = await acquireGeneration(message, chatOpts?.signal, false);
8902
8899
  if (!acq.success)
@@ -8929,7 +8926,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
8929
8926
  if (ragResult.success) {
8930
8927
  const reply = ragResult.data.answer;
8931
8928
  turnId = await finalizeAssistantReply(generation, reply);
8932
- return ok({
8929
+ return core.ok({
8933
8930
  reply,
8934
8931
  model: ragResult.data.model,
8935
8932
  turnId,
@@ -8953,7 +8950,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
8953
8950
  if (reasonResult.success) {
8954
8951
  const reply = reasonResult.data.answer;
8955
8952
  turnId = await finalizeAssistantReply(generation, reply);
8956
- return ok({
8953
+ return core.ok({
8957
8954
  reply,
8958
8955
  model: chatOpts?.model ?? options.model ?? "",
8959
8956
  turnId,
@@ -9009,7 +9006,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
9009
9006
  }
9010
9007
  const reply = typeof assistantMessage.content === "string" ? assistantMessage.content : "";
9011
9008
  turnId = await finalizeAssistantReply(generation, reply);
9012
- return ok({
9009
+ return core.ok({
9013
9010
  reply,
9014
9011
  model: lastModel,
9015
9012
  turnId,
@@ -9019,7 +9016,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
9019
9016
  const lastAssistantMsg = messages.filter((m) => m.role === "assistant").pop();
9020
9017
  const fallbackReply = lastAssistantMsg && "content" in lastAssistantMsg && typeof lastAssistantMsg.content === "string" ? lastAssistantMsg.content : "";
9021
9018
  turnId = await finalizeAssistantReply(generation, fallbackReply);
9022
- return ok({
9019
+ return core.ok({
9023
9020
  reply: fallbackReply,
9024
9021
  model: lastModel,
9025
9022
  turnId,
@@ -9275,7 +9272,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
9275
9272
  producers.get(turnId)?.stop();
9276
9273
  if (extracted?.reply)
9277
9274
  enqueueMemoryExtract(extracted.user, extracted.reply);
9278
- return ok(void 0);
9275
+ return core.ok(void 0);
9279
9276
  } catch (error) {
9280
9277
  return contextFailure(error);
9281
9278
  }
@@ -9298,8 +9295,8 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
9298
9295
  createManager(options) {
9299
9296
  try {
9300
9297
  if (!validScope(options?.scope))
9301
- return err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_contextScopeRequired"));
9302
- return ok(buildManager(options));
9298
+ return core.err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_contextScopeRequired"));
9299
+ return core.ok(buildManager(options));
9303
9300
  } catch (error) {
9304
9301
  return contextFailure(error);
9305
9302
  }
@@ -9307,18 +9304,18 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
9307
9304
  async restoreManager(scope, options) {
9308
9305
  try {
9309
9306
  if (!validScope(scope))
9310
- return err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_contextScopeRequired"));
9307
+ return core.err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_contextScopeRequired"));
9311
9308
  const persisted = await contextStore.readVersioned(sessionStoreKey(scope));
9312
9309
  if (persisted?.data.deleted)
9313
9310
  throw new ContextStateError(HaiAIError.SESSION_FAILED, "Context has been deleted");
9314
- return ok(buildManager({ ...options, scope }, persisted?.data));
9311
+ return core.ok(buildManager({ ...options, scope }, persisted?.data));
9315
9312
  } catch (error) {
9316
9313
  return contextFailure(error);
9317
9314
  }
9318
9315
  },
9319
9316
  async listSessions(objectId) {
9320
9317
  if (!sessionStore)
9321
- return ok([]);
9318
+ return core.ok([]);
9322
9319
  try {
9323
9320
  const sessions = await sessionStore.query({
9324
9321
  objectId,
@@ -9326,14 +9323,14 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
9326
9323
  });
9327
9324
  const contexts = await contextStore.query({ objectId });
9328
9325
  const deleted = new Set(contexts.filter((item2) => item2.deleted).map((item2) => sessionStoreKey(item2.scope)));
9329
- return ok(sessions.filter((item2) => !item2.deleted && !deleted.has(sessionStoreKey(item2))));
9326
+ return core.ok(sessions.filter((item2) => !item2.deleted && !deleted.has(sessionStoreKey(item2))));
9330
9327
  } catch (error) {
9331
9328
  return contextFailure(error);
9332
9329
  }
9333
9330
  },
9334
9331
  async renameSession(scope, title) {
9335
9332
  if (!sessionStore)
9336
- return ok(void 0);
9333
+ return core.ok(void 0);
9337
9334
  try {
9338
9335
  const context = await contextStore.readVersioned(sessionStoreKey(scope));
9339
9336
  if (context?.data.deleted)
@@ -9343,7 +9340,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
9343
9340
  throw new ContextStateError(HaiAIError.SESSION_FAILED, "Session not found");
9344
9341
  return { ...existing, title, updatedAt: now };
9345
9342
  });
9346
- return ok(void 0);
9343
+ return core.ok(void 0);
9347
9344
  } catch (error) {
9348
9345
  return contextFailure(error);
9349
9346
  }
@@ -9378,7 +9375,7 @@ function createContextOperations(compressConfig, tokenOps, compressOps, contextS
9378
9375
  deleted: true
9379
9376
  }));
9380
9377
  }
9381
- return ok(void 0);
9378
+ return core.ok(void 0);
9382
9379
  } catch (error) {
9383
9380
  return contextFailure(error);
9384
9381
  }
@@ -9413,7 +9410,7 @@ function createEmbeddingOperations(config, loadModels = () => config.llm) {
9413
9410
  params.dimensions = request2.dimensions ?? embeddingConfig.dimensions;
9414
9411
  }
9415
9412
  const response = await client2.embeddings.create(params);
9416
- return ok({
9413
+ return core.ok({
9417
9414
  model: response.model,
9418
9415
  data: response.data.map((item2) => ({
9419
9416
  index: item2.index,
@@ -9426,7 +9423,7 @@ function createEmbeddingOperations(config, loadModels = () => config.llm) {
9426
9423
  });
9427
9424
  } catch (error) {
9428
9425
  logger14.error("Embedding API call failed", { error });
9429
- return err(HaiAIError.EMBEDDING_API_ERROR, aiM("ai_internalError", {
9426
+ return core.err(HaiAIError.EMBEDDING_API_ERROR, aiM("ai_internalError", {
9430
9427
  params: {
9431
9428
  error: String(error)
9432
9429
  }
@@ -9465,7 +9462,7 @@ function createEmbeddingOperations(config, loadModels = () => config.llm) {
9465
9462
  });
9466
9463
  }
9467
9464
  }
9468
- return ok({
9465
+ return core.ok({
9469
9466
  model: resultModel,
9470
9467
  data: allData,
9471
9468
  usage: { prompt_tokens: totalPromptTokens, total_tokens: totalTokens }
@@ -9481,18 +9478,18 @@ function createEmbeddingOperations(config, loadModels = () => config.llm) {
9481
9478
  return result;
9482
9479
  const first = result.data.data.find((item2) => item2.index === 0);
9483
9480
  if (!first) {
9484
- return err(HaiAIError.EMBEDDING_API_ERROR, aiM("ai_internalError", {
9481
+ return core.err(HaiAIError.EMBEDDING_API_ERROR, aiM("ai_internalError", {
9485
9482
  params: { error: "Embedding result is empty" }
9486
9483
  }));
9487
9484
  }
9488
- return ok(first.embedding);
9485
+ return core.ok(first.embedding);
9489
9486
  },
9490
9487
  async embedBatch(texts) {
9491
9488
  const result = await embedRequest({ input: texts });
9492
9489
  if (!result.success)
9493
9490
  return result;
9494
9491
  const sorted = [...result.data.data].sort((a, b) => a.index - b.index);
9495
- return ok(sorted.map((item2) => item2.embedding));
9492
+ return core.ok(sorted.map((item2) => item2.embedding));
9496
9493
  }
9497
9494
  };
9498
9495
  }
@@ -9505,7 +9502,7 @@ var activeLocalParsers = 0;
9505
9502
  async function parseInWorker(job) {
9506
9503
  const result = await filePool.run(job);
9507
9504
  if (!result.success) {
9508
- return err(HaiAIError.FILE_PARSE_FAILED, aiM("ai_fileParseFailed", {
9505
+ return core.err(HaiAIError.FILE_PARSE_FAILED, aiM("ai_fileParseFailed", {
9509
9506
  params: { error: result.error.message }
9510
9507
  }), result.error);
9511
9508
  }
@@ -9623,10 +9620,10 @@ async function parseBoundedLocalFile(request2) {
9623
9620
  maxExpandedBytes,
9624
9621
  timeoutMs
9625
9622
  ].some((limit) => !Number.isSafeInteger(limit) || limit < 1) || !inputBytes || inputBytes > maxInputBytes2) {
9626
- return err(HaiAIError.FILE_INVALID_CONTENT, aiM("ai_fileLocalInvalid"));
9623
+ return core.err(HaiAIError.FILE_INVALID_CONTENT, aiM("ai_fileLocalInvalid"));
9627
9624
  }
9628
9625
  if (signal?.aborted)
9629
- return err(HaiAIError.FILE_LOCAL_CANCELLED, aiM("ai_fileLocalCancelled"));
9626
+ return core.err(HaiAIError.FILE_LOCAL_CANCELLED, aiM("ai_fileLocalCancelled"));
9630
9627
  const mimeType = detectMimeType(content, filename, options.mimeType);
9631
9628
  const parameters = {
9632
9629
  format: outputFormat,
@@ -9649,12 +9646,12 @@ async function parseBoundedLocalFile(request2) {
9649
9646
  } else if (typeof payload !== "string" && mimeType === "application/vnd.openxmlformats-officedocument.wordprocessingml.document") {
9650
9647
  job = { ...parameters, type: "docx", content: payload };
9651
9648
  } else {
9652
- return err(HaiAIError.FILE_UNSUPPORTED_FORMAT, aiM("ai_fileUnsupportedFormat", {
9649
+ return core.err(HaiAIError.FILE_UNSUPPORTED_FORMAT, aiM("ai_fileUnsupportedFormat", {
9653
9650
  params: { mimeType }
9654
9651
  }));
9655
9652
  }
9656
9653
  if (activeLocalParsers >= 3)
9657
- return err(HaiAIError.FILE_LOCAL_BUSY, aiM("ai_fileLocalBusy"));
9654
+ return core.err(HaiAIError.FILE_LOCAL_BUSY, aiM("ai_fileLocalBusy"));
9658
9655
  activeLocalParsers++;
9659
9656
  let worker;
9660
9657
  const deadline = AbortSignal.timeout(timeoutMs);
@@ -9681,15 +9678,15 @@ async function parseBoundedLocalFile(request2) {
9681
9678
  }
9682
9679
  });
9683
9680
  if (signal?.aborted)
9684
- return err(HaiAIError.FILE_LOCAL_CANCELLED, aiM("ai_fileLocalCancelled"));
9681
+ return core.err(HaiAIError.FILE_LOCAL_CANCELLED, aiM("ai_fileLocalCancelled"));
9685
9682
  if (deadline.aborted)
9686
- return err(HaiAIError.FILE_LOCAL_TIMEOUT, aiM("ai_fileLocalTimeout"));
9683
+ return core.err(HaiAIError.FILE_LOCAL_TIMEOUT, aiM("ai_fileLocalTimeout"));
9687
9684
  if (!parsed)
9688
- return err(HaiAIError.FILE_PARSE_FAILED, aiM("ai_fileLocalFailed"));
9685
+ return core.err(HaiAIError.FILE_PARSE_FAILED, aiM("ai_fileLocalFailed"));
9689
9686
  if (!parsed.success)
9690
9687
  return parsed;
9691
9688
  const { text, pageCount, truncated } = parsed.data;
9692
- return ok({
9689
+ return core.ok({
9693
9690
  text,
9694
9691
  method: job.type,
9695
9692
  ...pageCount !== void 0 && { pageCount },
@@ -9701,7 +9698,7 @@ async function parseBoundedLocalFile(request2) {
9701
9698
  }
9702
9699
  });
9703
9700
  } catch {
9704
- return err(HaiAIError.FILE_PARSE_FAILED, aiM("ai_fileLocalFailed"));
9701
+ return core.err(HaiAIError.FILE_PARSE_FAILED, aiM("ai_fileLocalFailed"));
9705
9702
  } finally {
9706
9703
  try {
9707
9704
  await worker?.terminate();
@@ -9736,11 +9733,11 @@ async function parseImageWithOcr(content, mimeType, llmOps, model, outputFormat
9736
9733
  ]
9737
9734
  });
9738
9735
  if (!result.success) {
9739
- return err(HaiAIError.FILE_OCR_FAILED, aiM("ai_fileOcrFailed", {
9736
+ return core.err(HaiAIError.FILE_OCR_FAILED, aiM("ai_fileOcrFailed", {
9740
9737
  params: { error: result.error.message }
9741
9738
  }), result.error);
9742
9739
  }
9743
- return ok(result.data.choices[0]?.message?.content ?? "");
9740
+ return core.ok(result.data.choices[0]?.message?.content ?? "");
9744
9741
  }
9745
9742
  function createFileOperations(config, llmOps) {
9746
9743
  async function runOcr(content, mimeType, filename, model, outputFormat, systemPrompt) {
@@ -9761,7 +9758,7 @@ function createFileOperations(config, llmOps) {
9761
9758
  );
9762
9759
  if (!ocrResult.success)
9763
9760
  return ocrResult;
9764
- return ok({
9761
+ return core.ok({
9765
9762
  text: ocrResult.data,
9766
9763
  method: "ocr",
9767
9764
  metadata: { filename, mimeType, charCount: ocrResult.data.length }
@@ -9782,7 +9779,7 @@ function createFileOperations(config, llmOps) {
9782
9779
  });
9783
9780
  if (options.useOcr) {
9784
9781
  if (!Buffer.isBuffer(content)) {
9785
- return err(HaiAIError.FILE_INVALID_CONTENT, aiM("ai_fileInvalidContent", {
9782
+ return core.err(HaiAIError.FILE_INVALID_CONTENT, aiM("ai_fileInvalidContent", {
9786
9783
  params: { reason: "OCR requires Buffer content" }
9787
9784
  }));
9788
9785
  }
@@ -9790,7 +9787,7 @@ function createFileOperations(config, llmOps) {
9790
9787
  }
9791
9788
  if (TEXT_MIME_TYPES.has(mimeType)) {
9792
9789
  const text = parseTextContent(content);
9793
- return ok({
9790
+ return core.ok({
9794
9791
  text,
9795
9792
  method: "text",
9796
9793
  metadata: { filename, mimeType, charCount: text.length }
@@ -9813,7 +9810,7 @@ function createFileOperations(config, llmOps) {
9813
9810
  } else {
9814
9811
  text = parseHtmlFile(parseTextContent(content), outputFormat);
9815
9812
  }
9816
- return ok({
9813
+ return core.ok({
9817
9814
  text,
9818
9815
  method: "html",
9819
9816
  metadata: { filename, mimeType, charCount: text.length }
@@ -9822,7 +9819,7 @@ function createFileOperations(config, llmOps) {
9822
9819
  const isPdf = mimeType === "application/pdf";
9823
9820
  if (isPdf || mimeType === "application/vnd.openxmlformats-officedocument.wordprocessingml.document" || mimeType === "application/msword" || mimeType === "application/zip") {
9824
9821
  if (!Buffer.isBuffer(content)) {
9825
- return err(HaiAIError.FILE_INVALID_CONTENT, aiM("ai_fileInvalidContent", {
9822
+ return core.err(HaiAIError.FILE_INVALID_CONTENT, aiM("ai_fileInvalidContent", {
9826
9823
  params: {
9827
9824
  reason: isPdf ? "PDF parsing requires Buffer content" : "DOCX parsing requires Buffer content"
9828
9825
  }
@@ -9839,7 +9836,7 @@ function createFileOperations(config, llmOps) {
9839
9836
  return result;
9840
9837
  if (result.data.success) {
9841
9838
  const { text, pageCount } = result.data.data;
9842
- return ok({
9839
+ return core.ok({
9843
9840
  text,
9844
9841
  method: isPdf ? "pdf" : "docx",
9845
9842
  ...isPdf ? { pageCount } : {},
@@ -9851,13 +9848,13 @@ function createFileOperations(config, llmOps) {
9851
9848
  }
9852
9849
  if (IMAGE_MIME_TYPES.has(mimeType)) {
9853
9850
  if (!Buffer.isBuffer(content)) {
9854
- return err(HaiAIError.FILE_INVALID_CONTENT, aiM("ai_fileInvalidContent", {
9851
+ return core.err(HaiAIError.FILE_INVALID_CONTENT, aiM("ai_fileInvalidContent", {
9855
9852
  params: { reason: "Image OCR requires Buffer content" }
9856
9853
  }));
9857
9854
  }
9858
9855
  return runOcr(content, mimeType, filename, options.model, outputFormat, options.systemPrompt);
9859
9856
  }
9860
- return err(HaiAIError.FILE_UNSUPPORTED_FORMAT, aiM("ai_fileUnsupportedFormat", {
9857
+ return core.err(HaiAIError.FILE_UNSUPPORTED_FORMAT, aiM("ai_fileUnsupportedFormat", {
9861
9858
  params: { mimeType }
9862
9859
  }));
9863
9860
  }
@@ -9867,7 +9864,7 @@ function createFileOperations(config, llmOps) {
9867
9864
  return await doParse(request2);
9868
9865
  } catch (error) {
9869
9866
  logger15.error("File parse failed unexpectedly", { filename: request2.filename, error });
9870
- return err(HaiAIError.FILE_PARSE_FAILED, aiM("ai_fileParseFailed", {
9867
+ return core.err(HaiAIError.FILE_PARSE_FAILED, aiM("ai_fileParseFailed", {
9871
9868
  params: {
9872
9869
  error: String(error)
9873
9870
  }
@@ -9878,7 +9875,7 @@ function createFileOperations(config, llmOps) {
9878
9875
  const result = await this.parse({ content, filename });
9879
9876
  if (!result.success)
9880
9877
  return result;
9881
- return ok(result.data.text);
9878
+ return core.ok(result.data.text);
9882
9879
  }
9883
9880
  };
9884
9881
  }
@@ -9982,12 +9979,12 @@ async function readImageBody(response, maxBytes, signal) {
9982
9979
  }
9983
9980
  function validateImageOutput(image, maxBytes) {
9984
9981
  if (image.data.byteLength > maxBytes)
9985
- return err(HaiAIError.IMAGE_TOO_LARGE, aiM("ai_imageTooLarge"));
9982
+ return core.err(HaiAIError.IMAGE_TOO_LARGE, aiM("ai_imageTooLarge"));
9986
9983
  const bytes = image.data;
9987
9984
  const mime = image.mimeType.toLowerCase() === "image/jpg" ? "image/jpeg" : image.mimeType.toLowerCase();
9988
9985
  const prefix = (value) => value.every((byte, index) => bytes[index] === byte);
9989
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";
9990
- return valid ? ok({ ...image, mimeType: mime }) : imageProtocolError();
9987
+ return valid ? core.ok({ ...image, mimeType: mime }) : imageProtocolError();
9991
9988
  }
9992
9989
  function imageFromBase64(data, mimeType, options) {
9993
9990
  if (Buffer.byteLength(data, "base64") > options.maxImageBytes)
@@ -10016,11 +10013,11 @@ async function readJson(response, request2) {
10016
10013
  if (!response.ok)
10017
10014
  return imageUpstreamError(response, request2.signal);
10018
10015
  try {
10019
- 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))));
10020
10017
  } catch (error) {
10021
10018
  if (error instanceof RangeError || request2.signal?.aborted)
10022
10019
  return imageProviderFailure(error);
10023
- return err(HaiAIError.IMAGE_PROTOCOL_ERROR, aiM("ai_imageProtocolError"), error);
10020
+ return core.err(HaiAIError.IMAGE_PROTOCOL_ERROR, aiM("ai_imageProtocolError"), error);
10024
10021
  }
10025
10022
  }
10026
10023
  async function downloadImage(url, request2) {
@@ -10048,7 +10045,7 @@ async function downloadImage(url, request2) {
10048
10045
  }
10049
10046
  async function downloadImages(urls, request2) {
10050
10047
  if (urls.length > request2.maxImages)
10051
- return err(HaiAIError.IMAGE_TOO_LARGE, aiM("ai_imageTooLarge"));
10048
+ return core.err(HaiAIError.IMAGE_TOO_LARGE, aiM("ai_imageTooLarge"));
10052
10049
  const images = [];
10053
10050
  for (const url of urls) {
10054
10051
  const downloaded = await downloadImage(url, request2);
@@ -10056,7 +10053,7 @@ async function downloadImages(urls, request2) {
10056
10053
  return downloaded;
10057
10054
  images.push(downloaded.data);
10058
10055
  }
10059
- return ok(images);
10056
+ return core.ok(images);
10060
10057
  }
10061
10058
  async function readImageResponse(response, request2) {
10062
10059
  if (!response.ok)
@@ -10083,18 +10080,18 @@ function imageProviderFailure(error) {
10083
10080
  let cause = error;
10084
10081
  for (let depth = 0; depth < 4 && cause instanceof Error; depth++, cause = cause.cause) {
10085
10082
  if (cause instanceof ImageDownloadBlockedError)
10086
- return err(HaiAIError.IMAGE_DOWNLOAD_BLOCKED, aiM("ai_imageDownloadBlocked"));
10083
+ return core.err(HaiAIError.IMAGE_DOWNLOAD_BLOCKED, aiM("ai_imageDownloadBlocked"));
10087
10084
  }
10088
10085
  if (error instanceof RangeError)
10089
- return err(HaiAIError.IMAGE_TOO_LARGE, aiM("ai_imageTooLarge"));
10086
+ return core.err(HaiAIError.IMAGE_TOO_LARGE, aiM("ai_imageTooLarge"));
10090
10087
  if (error instanceof DOMException && error.name === "TimeoutError")
10091
- return err(HaiAIError.IMAGE_TIMEOUT, aiM("ai_imageTimeout"));
10088
+ return core.err(HaiAIError.IMAGE_TIMEOUT, aiM("ai_imageTimeout"));
10092
10089
  if (error instanceof DOMException && error.name === "AbortError")
10093
- return err(HaiAIError.IMAGE_CANCELLED, aiM("ai_imageCancelled"), error);
10094
- 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);
10095
10092
  }
10096
10093
  function imageProtocolError() {
10097
- return err(HaiAIError.IMAGE_PROTOCOL_ERROR, aiM("ai_imageProtocolError"));
10094
+ return core.err(HaiAIError.IMAGE_PROTOCOL_ERROR, aiM("ai_imageProtocolError"));
10098
10095
  }
10099
10096
  async function imageUpstreamError(response, signal) {
10100
10097
  const details = {
@@ -10118,7 +10115,7 @@ async function imageUpstreamError(response, signal) {
10118
10115
  const message = response.status === 401 ? aiM("ai_imageAuthenticationFailed") : response.status === 402 ? aiM("ai_imagePaymentRequired") : response.status === 403 ? aiM("ai_imageAccessDenied") : aiM("ai_imageUpstreamError", {
10119
10116
  params: { status: response.status }
10120
10117
  });
10121
- return err(HaiAIError.IMAGE_UPSTREAM_ERROR, message, details);
10118
+ return core.err(HaiAIError.IMAGE_UPSTREAM_ERROR, message, details);
10122
10119
  }
10123
10120
 
10124
10121
  // src/image/providers/ai-image-provider-google.ts
@@ -10435,15 +10432,15 @@ function createImageOperations(config) {
10435
10432
  return {
10436
10433
  async generate(request2) {
10437
10434
  if (!request2.prompt?.trim())
10438
- return err(HaiAIError.IMAGE_INVALID_REQUEST, aiM("ai_imageInvalidRequest"));
10435
+ return core.err(HaiAIError.IMAGE_INVALID_REQUEST, aiM("ai_imageInvalidRequest"));
10439
10436
  if (request2.size && (!Number.isInteger(request2.size.width) || !Number.isInteger(request2.size.height) || request2.size.width <= 0 || request2.size.height <= 0))
10440
- return err(HaiAIError.IMAGE_INVALID_REQUEST, aiM("ai_imageInvalidSize"));
10437
+ return core.err(HaiAIError.IMAGE_INVALID_REQUEST, aiM("ai_imageInvalidSize"));
10441
10438
  if (request2.referenceImages?.some((image) => image.data.byteLength === 0 || !image.mimeType.toLowerCase().startsWith("image/")))
10442
- return err(HaiAIError.IMAGE_INVALID_REQUEST, aiM("ai_imageInvalidReferenceImage"));
10439
+ return core.err(HaiAIError.IMAGE_INVALID_REQUEST, aiM("ai_imageInvalidReferenceImage"));
10443
10440
  if ((request2.referenceImages?.length ?? 0) > imageConfig.maxImages || request2.referenceImages?.some((image) => image.data.byteLength > imageConfig.maxImageBytes))
10444
- return err(HaiAIError.IMAGE_TOO_LARGE, aiM("ai_imageTooLarge"));
10441
+ return core.err(HaiAIError.IMAGE_TOO_LARGE, aiM("ai_imageTooLarge"));
10445
10442
  if (request2.signal?.aborted)
10446
- return err(HaiAIError.IMAGE_CANCELLED, aiM("ai_imageCancelled"));
10443
+ return core.err(HaiAIError.IMAGE_CANCELLED, aiM("ai_imageCancelled"));
10447
10444
  const resolved = resolveImageModel(imageConfig, request2.model);
10448
10445
  if (!resolved.success) {
10449
10446
  logger16.warn("Image model resolution failed", {
@@ -10482,9 +10479,9 @@ function createImageOperations(config) {
10482
10479
  clearTimeout(timer);
10483
10480
  }
10484
10481
  if (request2.signal?.aborted)
10485
- return err(HaiAIError.IMAGE_CANCELLED, aiM("ai_imageCancelled"));
10482
+ return core.err(HaiAIError.IMAGE_CANCELLED, aiM("ai_imageCancelled"));
10486
10483
  if (deadline.signal.aborted)
10487
- return err(HaiAIError.IMAGE_TIMEOUT, aiM("ai_imageTimeout"));
10484
+ return core.err(HaiAIError.IMAGE_TIMEOUT, aiM("ai_imageTimeout"));
10488
10485
  if (!generated.success) {
10489
10486
  logger16.warn("Image generation failed", {
10490
10487
  ...logContext,
@@ -10496,7 +10493,7 @@ function createImageOperations(config) {
10496
10493
  return generated;
10497
10494
  }
10498
10495
  if (generated.data.length > imageConfig.maxImages)
10499
- return err(HaiAIError.IMAGE_TOO_LARGE, aiM("ai_imageTooLarge"));
10496
+ return core.err(HaiAIError.IMAGE_TOO_LARGE, aiM("ai_imageTooLarge"));
10500
10497
  const images = [];
10501
10498
  for (const image of generated.data) {
10502
10499
  const validated = validateImageOutput(image, imageConfig.maxImageBytes);
@@ -10564,7 +10561,7 @@ Rules:
10564
10561
  }
10565
10562
  async function extractEntities(llm, text, model, entityTypes, systemPrompt) {
10566
10563
  if (!text.trim()) {
10567
- return ok([]);
10564
+ return core.ok([]);
10568
10565
  }
10569
10566
  const resolvedTypes = entityTypes ?? DEFAULT_ENTITY_TYPES;
10570
10567
  const resolvedPrompt = systemPrompt ?? buildEntityExtractionPrompt(resolvedTypes);
@@ -10580,7 +10577,7 @@ async function extractEntities(llm, text, model, entityTypes, systemPrompt) {
10580
10577
  });
10581
10578
  if (!chatResult.success) {
10582
10579
  logger17.warn("Entity extraction LLM call failed", { error: chatResult.error });
10583
- return err(HaiAIError.KNOWLEDGE_ENTITY_EXTRACT_FAILED, aiM("ai_knowledgeEntityExtractFailed", {
10580
+ return core.err(HaiAIError.KNOWLEDGE_ENTITY_EXTRACT_FAILED, aiM("ai_knowledgeEntityExtractFailed", {
10584
10581
  params: {
10585
10582
  error: String(chatResult.error.message)
10586
10583
  }
@@ -10590,10 +10587,10 @@ async function extractEntities(llm, text, model, entityTypes, systemPrompt) {
10590
10587
  const validTypes = new Set(resolvedTypes);
10591
10588
  const entities = parseEntityResponse(content, validTypes);
10592
10589
  logger17.trace("Entity extraction completed", { textLength: text.length, entityCount: entities.length });
10593
- return ok(entities);
10590
+ return core.ok(entities);
10594
10591
  } catch (error) {
10595
10592
  logger17.error("Entity extraction failed", { error });
10596
- return err(HaiAIError.KNOWLEDGE_ENTITY_EXTRACT_FAILED, aiM("ai_knowledgeEntityExtractFailed", {
10593
+ return core.err(HaiAIError.KNOWLEDGE_ENTITY_EXTRACT_FAILED, aiM("ai_knowledgeEntityExtractFailed", {
10597
10594
  params: {
10598
10595
  error: String(error)
10599
10596
  }
@@ -10680,7 +10677,7 @@ async function extractEntitiesBatch(llm, chunks, model, entityTypes, systemPromp
10680
10677
  });
10681
10678
  }
10682
10679
  }
10683
- return ok(Array.from(entityMap.values()));
10680
+ return core.ok(Array.from(entityMap.values()));
10684
10681
  }
10685
10682
 
10686
10683
  // src/knowledge/ai-knowledge-functions.ts
@@ -10712,7 +10709,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
10712
10709
  */
10713
10710
  async setup(options) {
10714
10711
  if (!store) {
10715
- return err(HaiAIError.KNOWLEDGE_SETUP_FAILED, aiM("ai_knowledgeSetupFailed", {
10712
+ return core.err(HaiAIError.KNOWLEDGE_SETUP_FAILED, aiM("ai_knowledgeSetupFailed", {
10716
10713
  params: { error: "KnowledgeStore not available. Provider may not support knowledge operations." }
10717
10714
  }));
10718
10715
  }
@@ -10724,10 +10721,10 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
10724
10721
  await store.registerCollection(collection, dimension);
10725
10722
  await store.repair(collection);
10726
10723
  logger18.debug("Knowledge base setup completed", { collection });
10727
- return ok(void 0);
10724
+ return core.ok(void 0);
10728
10725
  } catch (error) {
10729
10726
  logger18.error("Knowledge base setup failed", { error });
10730
- return err(HaiAIError.KNOWLEDGE_SETUP_FAILED, aiM("ai_knowledgeSetupFailed", {
10727
+ return core.err(HaiAIError.KNOWLEDGE_SETUP_FAILED, aiM("ai_knowledgeSetupFailed", {
10731
10728
  params: {
10732
10729
  error: String(error)
10733
10730
  }
@@ -10771,10 +10768,10 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
10771
10768
  logger18.trace("Ingesting document", { documentId: input.documentId, collection, contentLength: input.content.length });
10772
10769
  try {
10773
10770
  if (!await isCollectionReady(collection))
10774
- return err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
10771
+ return core.err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
10775
10772
  const chunkResult = await datapipe2.pipeline().clean(cleanOptions).chunk(chunkOptions).run(input.content);
10776
10773
  if (!chunkResult.success) {
10777
- return err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
10774
+ return core.err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
10778
10775
  params: { error: chunkResult.error.message }
10779
10776
  }), chunkResult.error);
10780
10777
  }
@@ -10782,7 +10779,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
10782
10779
  const texts = chunks.map((c) => c.content);
10783
10780
  const embedResult = await embedding.embedBatch(texts);
10784
10781
  if (!embedResult.success) {
10785
- return err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
10782
+ return core.err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
10786
10783
  params: { error: "Embedding failed" }
10787
10784
  }), embedResult.error);
10788
10785
  }
@@ -10834,7 +10831,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
10834
10831
  });
10835
10832
  }
10836
10833
  } else {
10837
- return err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
10834
+ return core.err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
10838
10835
  params: { error: entityResult.error.message }
10839
10836
  }), entityResult.error);
10840
10837
  }
@@ -10858,7 +10855,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
10858
10855
  entityCount: extractedEntities.length,
10859
10856
  duration
10860
10857
  });
10861
- return ok({
10858
+ return core.ok({
10862
10859
  documentId: input.documentId,
10863
10860
  revision,
10864
10861
  cleanupPending: published.cleanupPending,
@@ -10868,7 +10865,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
10868
10865
  });
10869
10866
  } catch (error) {
10870
10867
  logger18.error("Document ingestion failed", { documentId: input.documentId, error });
10871
- return err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
10868
+ return core.err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
10872
10869
  params: {
10873
10870
  error: String(error)
10874
10871
  }
@@ -10898,10 +10895,10 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
10898
10895
  });
10899
10896
  try {
10900
10897
  if (!await isCollectionReady(collection))
10901
- return err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
10898
+ return core.err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
10902
10899
  const embedResult = await embedding.embedText(query);
10903
10900
  if (!embedResult.success) {
10904
- return err(HaiAIError.KNOWLEDGE_RETRIEVE_FAILED, aiM("ai_knowledgeRetrieveFailed", {
10901
+ return core.err(HaiAIError.KNOWLEDGE_RETRIEVE_FAILED, aiM("ai_knowledgeRetrieveFailed", {
10905
10902
  params: { error: "Query embedding failed" }
10906
10903
  }), embedResult.error);
10907
10904
  }
@@ -10977,7 +10974,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
10977
10974
  }
10978
10975
  const duration = Date.now() - startTime;
10979
10976
  logger18.trace("Knowledge retrieval completed", { resultCount: items.length, duration });
10980
- return ok({
10977
+ return core.ok({
10981
10978
  items,
10982
10979
  citations: Array.from(citationMap.values()),
10983
10980
  query,
@@ -10985,7 +10982,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
10985
10982
  });
10986
10983
  } catch (error) {
10987
10984
  logger18.error("Knowledge retrieval failed", { error });
10988
- return err(HaiAIError.KNOWLEDGE_RETRIEVE_FAILED, aiM("ai_knowledgeRetrieveFailed", {
10985
+ return core.err(HaiAIError.KNOWLEDGE_RETRIEVE_FAILED, aiM("ai_knowledgeRetrieveFailed", {
10989
10986
  params: {
10990
10987
  error: String(error)
10991
10988
  }
@@ -11005,7 +11002,7 @@ function createKnowledgeOperations(config, llm, embedding, datapipe2, store) {
11005
11002
  async ask(query, options) {
11006
11003
  const retrieveResult = await this.retrieve(query, options);
11007
11004
  if (!retrieveResult.success) {
11008
- return err(HaiAIError.RAG_FAILED, aiM("ai_ragFailed", {
11005
+ return core.err(HaiAIError.RAG_FAILED, aiM("ai_ragFailed", {
11009
11006
  params: { error: retrieveResult.error.message }
11010
11007
  }), retrieveResult.error);
11011
11008
  }
@@ -11034,7 +11031,7 @@ ${contextText}
11034
11031
  temperature: options?.temperature
11035
11032
  });
11036
11033
  if (!chatResult.success) {
11037
- return err(HaiAIError.RAG_FAILED, aiM("ai_ragFailed", {
11034
+ return core.err(HaiAIError.RAG_FAILED, aiM("ai_ragFailed", {
11038
11035
  params: { error: chatResult.error.message }
11039
11036
  }), chatResult.error);
11040
11037
  }
@@ -11044,7 +11041,7 @@ ${contextText}
11044
11041
  contextCount: items.length,
11045
11042
  model: chatResult.data.model
11046
11043
  });
11047
- return ok({
11044
+ return core.ok({
11048
11045
  answer,
11049
11046
  context: items,
11050
11047
  citations,
@@ -11061,16 +11058,16 @@ ${contextText}
11061
11058
  async findByEntity(entityName, options) {
11062
11059
  const collection = options?.collection ?? config.collection;
11063
11060
  if (!store) {
11064
- return err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
11061
+ return core.err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
11065
11062
  }
11066
11063
  try {
11067
11064
  if (!await isCollectionReady(collection))
11068
- return err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
11065
+ return core.err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
11069
11066
  const results = await store.findByEntityName(entityName, {
11070
11067
  collection,
11071
11068
  type: options?.type
11072
11069
  });
11073
- return ok(results.map((item2) => ({
11070
+ return core.ok(results.map((item2) => ({
11074
11071
  entity: {
11075
11072
  id: item2.entity.id,
11076
11073
  name: item2.entity.name,
@@ -11087,7 +11084,7 @@ ${contextText}
11087
11084
  }))
11088
11085
  })));
11089
11086
  } catch (error) {
11090
- return err(HaiAIError.KNOWLEDGE_RETRIEVE_FAILED, aiM("ai_knowledgeRetrieveFailed", {
11087
+ return core.err(HaiAIError.KNOWLEDGE_RETRIEVE_FAILED, aiM("ai_knowledgeRetrieveFailed", {
11091
11088
  params: {
11092
11089
  error: String(error)
11093
11090
  }
@@ -11097,7 +11094,7 @@ ${contextText}
11097
11094
  // ─── listEntities ───
11098
11095
  async listEntities(options) {
11099
11096
  if (!store) {
11100
- return err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
11097
+ return core.err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
11101
11098
  }
11102
11099
  try {
11103
11100
  const rows = await store.listEntities({
@@ -11106,7 +11103,7 @@ ${contextText}
11106
11103
  keyword: options?.keyword,
11107
11104
  limit: options?.limit
11108
11105
  });
11109
- return ok(rows.map((row) => ({
11106
+ return core.ok(rows.map((row) => ({
11110
11107
  id: row.id,
11111
11108
  name: row.name,
11112
11109
  type: row.type,
@@ -11116,7 +11113,7 @@ ${contextText}
11116
11113
  updatedAt: row.updatedAt ?? void 0
11117
11114
  })));
11118
11115
  } catch (error) {
11119
- return err(HaiAIError.KNOWLEDGE_RETRIEVE_FAILED, aiM("ai_knowledgeRetrieveFailed", {
11116
+ return core.err(HaiAIError.KNOWLEDGE_RETRIEVE_FAILED, aiM("ai_knowledgeRetrieveFailed", {
11120
11117
  params: {
11121
11118
  error: String(error)
11122
11119
  }
@@ -11127,11 +11124,11 @@ ${contextText}
11127
11124
  async listDocuments(options) {
11128
11125
  const collection = options?.collection ?? config.collection;
11129
11126
  if (!store) {
11130
- return err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
11127
+ return core.err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
11131
11128
  }
11132
11129
  try {
11133
11130
  if (!await isCollectionReady(collection))
11134
- return err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
11131
+ return core.err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
11135
11132
  const docs = await store.listDocuments(collection, {
11136
11133
  offset: options?.offset,
11137
11134
  limit: options?.limit
@@ -11145,9 +11142,9 @@ ${contextText}
11145
11142
  entityCount: d.entityCount,
11146
11143
  createdAt: d.createdAt
11147
11144
  }));
11148
- return ok(result);
11145
+ return core.ok(result);
11149
11146
  } catch (error) {
11150
- return err(HaiAIError.KNOWLEDGE_RETRIEVE_FAILED, aiM("ai_knowledgeRetrieveFailed", {
11147
+ return core.err(HaiAIError.KNOWLEDGE_RETRIEVE_FAILED, aiM("ai_knowledgeRetrieveFailed", {
11151
11148
  params: {
11152
11149
  error: String(error)
11153
11150
  }
@@ -11158,16 +11155,16 @@ ${contextText}
11158
11155
  async removeDocument(documentId, options) {
11159
11156
  const collection = options?.collection ?? config.collection;
11160
11157
  if (!store) {
11161
- return err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
11158
+ return core.err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
11162
11159
  }
11163
11160
  try {
11164
11161
  if (!await isCollectionReady(collection))
11165
- return err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
11162
+ return core.err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
11166
11163
  await store.removeDocument(documentId, collection);
11167
11164
  logger18.debug("Document removed", { documentId, collection });
11168
- return ok(void 0);
11165
+ return core.ok(void 0);
11169
11166
  } catch (error) {
11170
- return err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
11167
+ return core.err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
11171
11168
  params: {
11172
11169
  error: String(error)
11173
11170
  }
@@ -11179,16 +11176,16 @@ ${contextText}
11179
11176
  */
11180
11177
  async repair(options) {
11181
11178
  if (!store)
11182
- return err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
11179
+ return core.err(HaiAIError.KNOWLEDGE_NOT_SETUP, aiM("ai_knowledgeNotSetup"));
11183
11180
  if (!Number.isSafeInteger(options?.offset ?? 0) || (options?.offset ?? 0) < 0 || !Number.isSafeInteger(options?.limit ?? 100) || (options?.limit ?? 100) < 1 || (options?.limit ?? 100) > 1e3) {
11184
- return err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
11181
+ return core.err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
11185
11182
  params: { error: "Repair offset must be nonnegative and limit must be between 1 and 1000" }
11186
11183
  }));
11187
11184
  }
11188
11185
  try {
11189
- return ok(await store.repair(options?.collection ?? config.collection, options));
11186
+ return core.ok(await store.repair(options?.collection ?? config.collection, options));
11190
11187
  } catch (error) {
11191
- return err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
11188
+ return core.err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
11192
11189
  params: {
11193
11190
  error: String(error)
11194
11191
  }
@@ -11217,7 +11214,7 @@ ${contextText}
11217
11214
  chunkOptions: input.chunkOptions
11218
11215
  });
11219
11216
  } catch (error) {
11220
- return err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
11217
+ return core.err(HaiAIError.KNOWLEDGE_INGEST_FAILED, aiM("ai_knowledgeIngestFailed", {
11221
11218
  params: {
11222
11219
  error: String(error)
11223
11220
  }
@@ -11256,7 +11253,7 @@ ${contextText}
11256
11253
  });
11257
11254
  }
11258
11255
  }
11259
- return ok({
11256
+ return core.ok({
11260
11257
  successCount,
11261
11258
  failureCount,
11262
11259
  results,
@@ -11266,7 +11263,7 @@ ${contextText}
11266
11263
  // ─── deleteCollection ───
11267
11264
  async deleteCollection(collection) {
11268
11265
  if (!store) {
11269
- return err(HaiAIError.KNOWLEDGE_SETUP_FAILED, aiM("ai_knowledgeSetupFailed", {
11266
+ return core.err(HaiAIError.KNOWLEDGE_SETUP_FAILED, aiM("ai_knowledgeSetupFailed", {
11270
11267
  params: { error: "KnowledgeStore not available. Provider may not support knowledge operations." }
11271
11268
  }));
11272
11269
  }
@@ -11275,10 +11272,10 @@ ${contextText}
11275
11272
  try {
11276
11273
  await store.deleteCollection(col);
11277
11274
  logger18.debug("Knowledge collection deleted", { collection: col });
11278
- return ok(void 0);
11275
+ return core.ok(void 0);
11279
11276
  } catch (error) {
11280
11277
  logger18.error("Knowledge collection deletion failed", { collection: col, error });
11281
- return err(HaiAIError.KNOWLEDGE_SETUP_FAILED, aiM("ai_knowledgeSetupFailed", {
11278
+ return core.err(HaiAIError.KNOWLEDGE_SETUP_FAILED, aiM("ai_knowledgeSetupFailed", {
11282
11279
  params: {
11283
11280
  error: String(error)
11284
11281
  }
@@ -11481,12 +11478,12 @@ function projectToolProtocolSchema(schema) {
11481
11478
  var logger19 = core.logger.child({ module: "ai", scope: "tool-protocol" });
11482
11479
  function decodeCall(call) {
11483
11480
  if (call.type !== "function")
11484
- return err(HaiAIError.TOOL_PROTOCOL_ERROR, aiM("ai_toolInvalidCall"));
11481
+ return core.err(HaiAIError.TOOL_PROTOCOL_ERROR, aiM("ai_toolInvalidCall"));
11485
11482
  try {
11486
11483
  const input = JSON.parse(call.function.arguments);
11487
- return ok({ name: call.function.name, input });
11484
+ return core.ok({ name: call.function.name, input });
11488
11485
  } catch (cause) {
11489
- return err(HaiAIError.TOOL_PROTOCOL_ERROR, aiM("ai_toolInvalidJson"), cause);
11486
+ return core.err(HaiAIError.TOOL_PROTOCOL_ERROR, aiM("ai_toolInvalidJson"), cause);
11490
11487
  }
11491
11488
  }
11492
11489
  function encodeResult(call, output) {
@@ -11494,10 +11491,10 @@ function encodeResult(call, output) {
11494
11491
  const content = typeof output === "string" ? output : JSON.stringify(output === void 0 ? null : output);
11495
11492
  if (typeof content !== "string")
11496
11493
  throw new TypeError("Tool output is not JSON serializable");
11497
- return ok({ role: "tool", tool_call_id: call.id, content });
11494
+ return core.ok({ role: "tool", tool_call_id: call.id, content });
11498
11495
  } catch (cause) {
11499
11496
  logger19.error("Tool result encoding failed", { code: HaiAIError.TOOL_RESULT_ERROR.code });
11500
- return err(HaiAIError.TOOL_RESULT_ERROR, aiM("ai_toolInvalidResult"), cause);
11497
+ return core.err(HaiAIError.TOOL_RESULT_ERROR, aiM("ai_toolInvalidResult"), cause);
11501
11498
  }
11502
11499
  }
11503
11500
  function adaptToolRegistry(registry) {
@@ -11537,7 +11534,7 @@ function adaptToolRegistry(registry) {
11537
11534
  return encoded;
11538
11535
  messages.push(encoded.data);
11539
11536
  }
11540
- return ok(messages);
11537
+ return core.ok(messages);
11541
11538
  }
11542
11539
  };
11543
11540
  }
@@ -11705,13 +11702,13 @@ function createAnthropicProvider(deps) {
11705
11702
  const model = tempModel?.model ?? entry?.model ?? requestModel ?? config.llm.model ?? "claude-3-5-sonnet-latest";
11706
11703
  const apiKey = tempModel?.apiKey ?? entry?.apiKey ?? config.llm.apiKey ?? (process2.env.HAI_AI_LLM_APIKEY?.trim() || process2.env.ANTHROPIC_API_KEY);
11707
11704
  if (!apiKey) {
11708
- return err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_configError", {
11705
+ return core.err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_configError", {
11709
11706
  params: { error: "API Key is required for Anthropic" }
11710
11707
  }));
11711
11708
  }
11712
11709
  const globalBaseUrl = config.llm.protocol === "anthropic" ? config.llm.baseUrl ?? (process2.env.HAI_AI_LLM_BASEURL?.trim() || void 0) : void 0;
11713
11710
  const baseUrl = (tempModel?.baseUrl ?? entry?.baseUrl ?? globalBaseUrl ?? process2.env.ANTHROPIC_BASE_URL ?? DEFAULT_ANTHROPIC_BASE_URL).replace(/\/+$/, "");
11714
- return ok({
11711
+ return core.ok({
11715
11712
  apiKey,
11716
11713
  baseUrl,
11717
11714
  model,
@@ -11769,14 +11766,14 @@ function createAnthropicProvider(deps) {
11769
11766
  if (!res.ok) {
11770
11767
  const detail = await res.text().catch(() => res.statusText);
11771
11768
  const mapped = httpError(res.status, detail.slice(0, 500));
11772
- return err(mapped.def, mapped.message, { status: res.status });
11769
+ return core.err(mapped.def, mapped.message, { status: res.status });
11773
11770
  }
11774
11771
  const data = await res.json();
11775
- return ok(toChatResponse(data, resolved.model));
11772
+ return core.ok(toChatResponse(data, resolved.model));
11776
11773
  } catch (error) {
11777
11774
  if (error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError"))
11778
- return err(HaiAIError.TIMEOUT, aiM("ai_requestTimeout"), { message: error.message });
11779
- 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", {
11780
11777
  params: {
11781
11778
  error: error instanceof Error ? error.message : "Unknown error"
11782
11779
  }
@@ -11839,7 +11836,7 @@ function createAnthropicProvider(deps) {
11839
11836
  if ((entry.protocol ?? config.llm.protocol) === "anthropic")
11840
11837
  models.add(entry.model);
11841
11838
  }
11842
- return ok([...models]);
11839
+ return core.ok([...models]);
11843
11840
  }
11844
11841
  };
11845
11842
  }
@@ -12113,7 +12110,7 @@ function createOpenAIProvider(deps) {
12113
12110
  return resolvedResult;
12114
12111
  const { apiKey, baseUrl, timeout, model, protocol: api } = resolvedResult.data;
12115
12112
  const resolvedApi = api === "responses" ? "responses" : "chat";
12116
- return ok({
12113
+ return core.ok({
12117
12114
  client: getClient(apiKey ?? "", baseUrl ?? "https://api.openai.com/v1", timeout),
12118
12115
  model,
12119
12116
  protocol: resolvedApi
@@ -12122,14 +12119,14 @@ function createOpenAIProvider(deps) {
12122
12119
  function resolveTempClient(tempModel) {
12123
12120
  const apiKey = tempModel.apiKey ?? config.llm.apiKey ?? (process2.env.HAI_AI_LLM_APIKEY?.trim() || process2.env.OPENAI_API_KEY);
12124
12121
  if (!apiKey) {
12125
- return err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_configError", {
12122
+ return core.err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_configError", {
12126
12123
  params: { error: "API Key is required for temp model" }
12127
12124
  }));
12128
12125
  }
12129
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";
12130
12127
  const timeout = tempModel.timeout ?? config.llm.timeout ?? 6e4;
12131
12128
  const api = (tempModel.protocol ?? config.llm.protocol) === "responses" ? "responses" : "chat";
12132
- return ok({
12129
+ return core.ok({
12133
12130
  client: getTempClient(apiKey, baseUrl, timeout),
12134
12131
  model: tempModel.model,
12135
12132
  protocol: api,
@@ -12143,7 +12140,7 @@ function createOpenAIProvider(deps) {
12143
12140
  if (responseFormat?.type === "json_schema") {
12144
12141
  const { json_schema: jsonSchema } = responseFormat;
12145
12142
  if (!jsonSchema?.schema)
12146
- return err(HaiAIError.INVALID_REQUEST, aiM("ai_llmResponsesSchemaRequired"));
12143
+ return core.err(HaiAIError.INVALID_REQUEST, aiM("ai_llmResponsesSchemaRequired"));
12147
12144
  const { name, schema, description, strict } = jsonSchema;
12148
12145
  format = {
12149
12146
  type: "json_schema",
@@ -12158,7 +12155,7 @@ function createOpenAIProvider(deps) {
12158
12155
  const maxOutput = request2.max_tokens ?? resolved.maxTokens;
12159
12156
  const temperature = request2.temperature ?? resolved.temperature;
12160
12157
  const toolChoice = typeof request2.tool_choice === "string" ? request2.tool_choice : void 0;
12161
- return ok({
12158
+ return core.ok({
12162
12159
  model: resolved.model,
12163
12160
  input: toResponsesInput(request2.messages),
12164
12161
  ...format ? {
@@ -12188,7 +12185,7 @@ function createOpenAIProvider(deps) {
12188
12185
  if (!params2.success)
12189
12186
  return params2;
12190
12187
  const response2 = await client2.responses.create(params2.data, { signal });
12191
- return ok(responsesToChatResponse(response2, model));
12188
+ return core.ok(responsesToChatResponse(response2, model));
12192
12189
  }
12193
12190
  const openaiMessages = request2.messages.map(toOpenAIMessage);
12194
12191
  const params = {
@@ -12200,10 +12197,10 @@ function createOpenAIProvider(deps) {
12200
12197
  stream: false
12201
12198
  };
12202
12199
  const response = signal ? await client2.chat.completions.create(params, { signal }) : await client2.chat.completions.create(params);
12203
- return ok(response);
12200
+ return core.ok(response);
12204
12201
  } catch (error) {
12205
12202
  const mapped = toAIError(error);
12206
- return err(mapped.def, mapped.message, mapped.cause);
12203
+ return core.err(mapped.def, mapped.message, mapped.cause);
12207
12204
  }
12208
12205
  },
12209
12206
  async *chatStream(request2) {
@@ -12253,10 +12250,10 @@ function createOpenAIProvider(deps) {
12253
12250
  try {
12254
12251
  const response = await client2.models.list();
12255
12252
  const models = response.data.map((m) => m.id);
12256
- return ok(models);
12253
+ return core.ok(models);
12257
12254
  } catch (error) {
12258
12255
  const mapped = toAIError(error);
12259
- return err(mapped.def, mapped.message, mapped.cause);
12256
+ return core.err(mapped.def, mapped.message, mapped.cause);
12260
12257
  }
12261
12258
  }
12262
12259
  };
@@ -12348,7 +12345,7 @@ function createAILLMFunctions(config, deps) {
12348
12345
  try {
12349
12346
  result = await (await currentProvider()).chat(request2);
12350
12347
  } catch {
12351
- return err(
12348
+ return core.err(
12352
12349
  HaiAIError.RESOURCE_OPERATION_FAILED,
12353
12350
  aiM("ai_resourceOperationFailed")
12354
12351
  );
@@ -12494,7 +12491,7 @@ function createAILLMFunctions(config, deps) {
12494
12491
  }
12495
12492
  async function getHistory(scope, options) {
12496
12493
  if (!recordStore) {
12497
- return ok([]);
12494
+ return core.ok([]);
12498
12495
  }
12499
12496
  try {
12500
12497
  const records = await recordStore.query({
@@ -12503,9 +12500,9 @@ function createAILLMFunctions(config, deps) {
12503
12500
  orderBy: { field: "createdAt", direction: options?.order ?? "desc" },
12504
12501
  limit: options?.limit
12505
12502
  });
12506
- return ok(records);
12503
+ return core.ok(records);
12507
12504
  } catch (error) {
12508
- return err(
12505
+ return core.err(
12509
12506
  HaiAIError.LLM_HISTORY_FAILED,
12510
12507
  aiM("ai_llmHistoryFailed", {
12511
12508
  params: {
@@ -12518,16 +12515,16 @@ function createAILLMFunctions(config, deps) {
12518
12515
  }
12519
12516
  async function listSessions(objectId) {
12520
12517
  if (!sessionStore) {
12521
- return ok([]);
12518
+ return core.ok([]);
12522
12519
  }
12523
12520
  try {
12524
12521
  const sessions = await sessionStore.query({
12525
12522
  objectId,
12526
12523
  orderBy: { field: "updatedAt", direction: "desc" }
12527
12524
  });
12528
- return ok(sessions.filter((item2) => !item2.deleted));
12525
+ return core.ok(sessions.filter((item2) => !item2.deleted));
12529
12526
  } catch (error) {
12530
- return err(
12527
+ return core.err(
12531
12528
  HaiAIError.LLM_HISTORY_FAILED,
12532
12529
  aiM("ai_llmHistoryFailed", {
12533
12530
  params: {
@@ -12545,7 +12542,7 @@ function createAILLMFunctions(config, deps) {
12545
12542
  try {
12546
12543
  return await (await currentProvider()).listModels();
12547
12544
  } catch {
12548
- return err(
12545
+ return core.err(
12549
12546
  HaiAIError.RESOURCE_OPERATION_FAILED,
12550
12547
  aiM("ai_resourceOperationFailed")
12551
12548
  );
@@ -12571,7 +12568,7 @@ function createAILLMFunctions(config, deps) {
12571
12568
  });
12572
12569
  if (!result.success)
12573
12570
  return result;
12574
- return ok(result.data.choices[0]?.message?.content ?? "");
12571
+ return core.ok(result.data.choices[0]?.message?.content ?? "");
12575
12572
  },
12576
12573
  async *askStream(question, options) {
12577
12574
  const messages = [];
@@ -12603,7 +12600,7 @@ function createAILLMFunctions(config, deps) {
12603
12600
  try {
12604
12601
  jsonSchema = z.toJSONSchema(request2.schema);
12605
12602
  } catch {
12606
- return err(HaiAIError.INVALID_REQUEST, aiM("ai_generateObjectFailed", {
12603
+ return core.err(HaiAIError.INVALID_REQUEST, aiM("ai_generateObjectFailed", {
12607
12604
  params: { error: "schema cannot be represented as JSON Schema" }
12608
12605
  }));
12609
12606
  }
@@ -12677,7 +12674,7 @@ function createAILLMFunctions(config, deps) {
12677
12674
  }
12678
12675
  } catch {
12679
12676
  await clearPreview();
12680
- return err(HaiAIError.RESOURCE_OPERATION_FAILED, aiM("ai_resourceOperationFailed"));
12677
+ return core.err(HaiAIError.RESOURCE_OPERATION_FAILED, aiM("ai_resourceOperationFailed"));
12681
12678
  }
12682
12679
  if (request2.signal?.aborted || finishReason !== "stop") {
12683
12680
  await clearPreview();
@@ -12703,11 +12700,11 @@ function createAILLMFunctions(config, deps) {
12703
12700
  }
12704
12701
  const validated = request2.schema.safeParse(parsed);
12705
12702
  if (validated.success)
12706
- return ok(validated.data);
12703
+ return core.ok(validated.data);
12707
12704
  await clearPreview();
12708
12705
  lastError = validated.error.message;
12709
12706
  }
12710
- return err(
12707
+ return core.err(
12711
12708
  HaiAIError.INVALID_REQUEST,
12712
12709
  aiM("ai_generateObjectFailed", {
12713
12710
  params: { error: lastError || "unknown" }
@@ -12738,9 +12735,9 @@ function createAIMCPFunctions() {
12738
12735
  try {
12739
12736
  const validate = validator.getValidator(definition.inputSchema);
12740
12737
  tools4.set(definition.name, { definition, handler, validate });
12741
- return ok(void 0);
12738
+ return core.ok(void 0);
12742
12739
  } catch (error) {
12743
- return err(HaiAIError.MCP_TOOL_ERROR, aiM("ai_mcpInvalidToolSchema", {
12740
+ return core.err(HaiAIError.MCP_TOOL_ERROR, aiM("ai_mcpInvalidToolSchema", {
12744
12741
  params: { name: definition.name }
12745
12742
  }), error);
12746
12743
  }
@@ -12748,12 +12745,12 @@ function createAIMCPFunctions() {
12748
12745
  /** 注册 MCP 资源(同 URI 覆盖) */
12749
12746
  registerResource(resource, handler) {
12750
12747
  resources.set(resource.uri, { resource, handler });
12751
- return ok(void 0);
12748
+ return core.ok(void 0);
12752
12749
  },
12753
12750
  /** 注册 MCP 提示词模板(同名覆盖) */
12754
12751
  registerPrompt(prompt, handler) {
12755
12752
  prompts.set(prompt.name, { prompt, handler });
12756
- return ok(void 0);
12753
+ return core.ok(void 0);
12757
12754
  },
12758
12755
  /**
12759
12756
  * 调用已注册的 MCP 工具
@@ -12767,21 +12764,21 @@ function createAIMCPFunctions() {
12767
12764
  try {
12768
12765
  const registration = tools4.get(name);
12769
12766
  if (!registration) {
12770
- return err(HaiAIError.MCP_TOOL_ERROR, aiM("ai_mcpToolNotFound", {
12767
+ return core.err(HaiAIError.MCP_TOOL_ERROR, aiM("ai_mcpToolNotFound", {
12771
12768
  params: { name }
12772
12769
  }));
12773
12770
  }
12774
12771
  const validation = registration.validate(args);
12775
12772
  if (!validation.valid) {
12776
- return err(HaiAIError.MCP_TOOL_ERROR, aiM("ai_mcpInvalidToolInput", {
12773
+ return core.err(HaiAIError.MCP_TOOL_ERROR, aiM("ai_mcpInvalidToolInput", {
12777
12774
  params: { name }
12778
12775
  }));
12779
12776
  }
12780
12777
  const ctx = { ...context, requestId: context?.requestId ?? crypto.randomUUID() };
12781
12778
  const result = await registration.handler(args, ctx);
12782
- return ok(result);
12779
+ return core.ok(result);
12783
12780
  } catch (error) {
12784
- return err(
12781
+ return core.err(
12785
12782
  HaiAIError.MCP_TOOL_ERROR,
12786
12783
  aiM("ai_mcpToolFailed", {
12787
12784
  params: {
@@ -12803,7 +12800,7 @@ function createAIMCPFunctions() {
12803
12800
  try {
12804
12801
  const registration = resources.get(uri);
12805
12802
  if (!registration) {
12806
- return err(HaiAIError.MCP_RESOURCE_ERROR, aiM("ai_mcpResourceNotFound", {
12803
+ return core.err(HaiAIError.MCP_RESOURCE_ERROR, aiM("ai_mcpResourceNotFound", {
12807
12804
  params: { uri }
12808
12805
  }));
12809
12806
  }
@@ -12811,13 +12808,13 @@ function createAIMCPFunctions() {
12811
12808
  const text = TextResourceContentsSchema.safeParse(content);
12812
12809
  const blob = BlobResourceContentsSchema.safeParse(content);
12813
12810
  if (text.success === blob.success || text.success && Object.hasOwn(content, "blob") || blob.success && Object.hasOwn(content, "text")) {
12814
- return err(HaiAIError.MCP_RESOURCE_ERROR, aiM("ai_mcpInvalidResource", {
12811
+ return core.err(HaiAIError.MCP_RESOURCE_ERROR, aiM("ai_mcpInvalidResource", {
12815
12812
  params: { uri }
12816
12813
  }));
12817
12814
  }
12818
- return ok(content);
12815
+ return core.ok(content);
12819
12816
  } catch (error) {
12820
- return err(
12817
+ return core.err(
12821
12818
  HaiAIError.MCP_RESOURCE_ERROR,
12822
12819
  aiM("ai_mcpResourceFailed", {
12823
12820
  params: {
@@ -12842,31 +12839,31 @@ function createAIMCPFunctions() {
12842
12839
  try {
12843
12840
  const registration = prompts.get(name);
12844
12841
  if (!registration) {
12845
- return err(HaiAIError.MCP_PROTOCOL_ERROR, aiM("ai_mcpPromptNotFound", {
12842
+ return core.err(HaiAIError.MCP_PROTOCOL_ERROR, aiM("ai_mcpPromptNotFound", {
12846
12843
  params: { name }
12847
12844
  }));
12848
12845
  }
12849
12846
  for (const arg of registration.prompt.arguments || []) {
12850
12847
  if (arg.required && !Object.hasOwn(args, arg.name)) {
12851
- return err(HaiAIError.MCP_PROTOCOL_ERROR, aiM("ai_mcpPromptMissingArg", {
12848
+ return core.err(HaiAIError.MCP_PROTOCOL_ERROR, aiM("ai_mcpPromptMissingArg", {
12852
12849
  params: { name, arg: arg.name }
12853
12850
  }));
12854
12851
  }
12855
12852
  if (Object.hasOwn(args, arg.name) && typeof args[arg.name] !== "string") {
12856
- return err(HaiAIError.MCP_PROTOCOL_ERROR, aiM("ai_mcpInvalidPrompt", {
12853
+ return core.err(HaiAIError.MCP_PROTOCOL_ERROR, aiM("ai_mcpInvalidPrompt", {
12857
12854
  params: { name }
12858
12855
  }));
12859
12856
  }
12860
12857
  }
12861
12858
  const messages = await registration.handler(args);
12862
12859
  if (!Array.isArray(messages) || messages.some((message) => !PromptMessageSchema.safeParse(message).success)) {
12863
- return err(HaiAIError.MCP_PROTOCOL_ERROR, aiM("ai_mcpInvalidPrompt", {
12860
+ return core.err(HaiAIError.MCP_PROTOCOL_ERROR, aiM("ai_mcpInvalidPrompt", {
12864
12861
  params: { name }
12865
12862
  }));
12866
12863
  }
12867
- return ok(messages);
12864
+ return core.ok(messages);
12868
12865
  } catch (error) {
12869
- return err(
12866
+ return core.err(
12870
12867
  HaiAIError.MCP_PROTOCOL_ERROR,
12871
12868
  aiM("ai_mcpPromptFailed", {
12872
12869
  params: {
@@ -12906,7 +12903,7 @@ var digest = (token) => createHash("sha256").update(token).digest("hex");
12906
12903
  function createMCPServiceBroker(read, invoke, options, lifecycle, local) {
12907
12904
  const endpoint = URL.parse(options?.url);
12908
12905
  if (!endpoint || !["http:", "https:"].includes(endpoint.protocol) || endpoint.username || endpoint.password || endpoint.hash || endpoint.search || typeof options.authorize !== "function")
12909
- return err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
12906
+ return core.err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
12910
12907
  const grants = /* @__PURE__ */ new Map();
12911
12908
  let closed = false;
12912
12909
  function createGrant(input, validators, key) {
@@ -12944,13 +12941,13 @@ function createMCPServiceBroker(read, invoke, options, lifecycle, local) {
12944
12941
  const broker = {
12945
12942
  async bind(request2) {
12946
12943
  if (closed || lifecycle.aborted)
12947
- return err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
12944
+ return core.err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
12948
12945
  try {
12949
12946
  const parsed = bindingSchema.safeParse(request2);
12950
12947
  if (!parsed.success || new Set(parsed.data.tools.map((tool) => tool.id)).size !== parsed.data.tools.length)
12951
- return err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
12948
+ return core.err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
12952
12949
  if (Buffer.byteLength(JSON.stringify(parsed.data.tools)) > maxRequestBytes)
12953
- return err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
12950
+ return core.err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
12954
12951
  const input = {
12955
12952
  ...parsed.data,
12956
12953
  tools: structuredClone(parsed.data.tools)
@@ -12962,27 +12959,27 @@ function createMCPServiceBroker(read, invoke, options, lifecycle, local) {
12962
12959
  const catalog = await local.catalog(input.principal, input.taskId, input.signal);
12963
12960
  const actual = catalog.success ? catalog.data.find((item2) => item2.name === tool.tool) : void 0;
12964
12961
  if (!actual || actual.description !== tool.description || JSON.stringify(actual.inputSchema) !== JSON.stringify(tool.inputSchema))
12965
- return err(HaiAIError.MCP_TOOL_FORBIDDEN, aiM("ai_mcpServiceForbidden"));
12962
+ return core.err(HaiAIError.MCP_TOOL_FORBIDDEN, aiM("ai_mcpServiceForbidden"));
12966
12963
  } else {
12967
12964
  if (!services.has(tool.serviceId))
12968
12965
  services.set(tool.serviceId, await read(tool.serviceId));
12969
12966
  const service = services.get(tool.serviceId);
12970
12967
  if (!service || !["http", "job"].includes(service.transport) || !service.allowedTools?.includes(tool.tool))
12971
- return err(HaiAIError.MCP_TOOL_FORBIDDEN, aiM("ai_mcpServiceForbidden"));
12968
+ return core.err(HaiAIError.MCP_TOOL_FORBIDDEN, aiM("ai_mcpServiceForbidden"));
12972
12969
  }
12973
12970
  validators.set(tool.id, new AjvJsonSchemaValidator().getValidator(tool.inputSchema));
12974
12971
  }
12975
12972
  if (closed || lifecycle.aborted)
12976
- return err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
12973
+ return core.err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
12977
12974
  if (grants.size >= 1024)
12978
- return err(HaiAIError.RESOURCE_OPERATION_FAILED, aiM("ai_resourceOperationFailed"));
12975
+ return core.err(HaiAIError.RESOURCE_OPERATION_FAILED, aiM("ai_resourceOperationFailed"));
12979
12976
  const token = randomBytes(32).toString("base64url");
12980
12977
  const key = digest(token);
12981
12978
  const grant = createGrant(input, validators, key);
12982
12979
  if (!grant)
12983
- return err(HaiAIError.MCP_TOOL_CANCELLED, aiM("ai_mcpServiceCancelled"));
12980
+ return core.err(HaiAIError.MCP_TOOL_CANCELLED, aiM("ai_mcpServiceCancelled"));
12984
12981
  grants.set(key, grant);
12985
- return ok({
12982
+ return core.ok({
12986
12983
  servers: [
12987
12984
  {
12988
12985
  type: "http",
@@ -12997,7 +12994,7 @@ function createMCPServiceBroker(read, invoke, options, lifecycle, local) {
12997
12994
  signal: grant.signal
12998
12995
  });
12999
12996
  } catch {
13000
- return err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
12997
+ return core.err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
13001
12998
  }
13002
12999
  },
13003
13000
  async handleRequest(request2, response) {
@@ -13104,7 +13101,7 @@ function createMCPServiceBroker(read, invoke, options, lifecycle, local) {
13104
13101
  grants.clear();
13105
13102
  }
13106
13103
  };
13107
- return ok(broker);
13104
+ return core.ok(broker);
13108
13105
  }
13109
13106
  var kind = "ai-mcp-job";
13110
13107
  var fileName = /^[a-z0-9][\w.-]{0,127}$/i;
@@ -13366,10 +13363,10 @@ function createMCPServiceOperations(read, runner, files, configuredServices = []
13366
13363
  throw new Error("Managed MCP warm pools require a runner and file access policy");
13367
13364
  const jobs = runner && files ? createMCPJobs(read, runner, files, warmServices) : void 0;
13368
13365
  const operations2 = {
13369
- 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),
13370
13367
  async invoke(request2, authorization) {
13371
13368
  if (lifecycle.signal.aborted)
13372
- return err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
13369
+ return core.err(HaiAIError.NOT_INITIALIZED, aiM("ai_notInitialized"));
13373
13370
  let connected = false;
13374
13371
  let timeout;
13375
13372
  let transport;
@@ -13379,17 +13376,17 @@ function createMCPServiceOperations(read, runner, files, configuredServices = []
13379
13376
  const parsed = requestSchema.safeParse(request2);
13380
13377
  const principal2 = principalSchema.safeParse(authorization?.principal);
13381
13378
  if (!parsed.success || !principal2.success || Buffer.byteLength(JSON.stringify(parsed.data)) > maxInputBytes)
13382
- return err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
13379
+ return core.err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
13383
13380
  if (authorization.signal?.aborted)
13384
- return err(HaiAIError.MCP_TOOL_CANCELLED, aiM("ai_mcpServiceCancelled"));
13381
+ return core.err(HaiAIError.MCP_TOOL_CANCELLED, aiM("ai_mcpServiceCancelled"));
13385
13382
  const input = parsed.data;
13386
13383
  const service = await read(input.serviceId);
13387
13384
  if (!service?.allowedTools?.includes(input.tool) || typeof authorization.authorize !== "function")
13388
- return err(HaiAIError.MCP_TOOL_FORBIDDEN, aiM("ai_mcpServiceForbidden"));
13385
+ return core.err(HaiAIError.MCP_TOOL_FORBIDDEN, aiM("ai_mcpServiceForbidden"));
13389
13386
  if (service.transport === "job" && !jobs)
13390
- return err(HaiAIError.MCP_CONNECTION_ERROR, aiM("ai_mcpServiceConnectionFailed"));
13387
+ return core.err(HaiAIError.MCP_CONNECTION_ERROR, aiM("ai_mcpServiceConnectionFailed"));
13391
13388
  if (service.transport !== "job" && (service.transport !== "http" || !service.url))
13392
- return err(HaiAIError.MCP_PROTOCOL_ERROR, aiM("ai_mcpServiceConnectionFailed"));
13389
+ return core.err(HaiAIError.MCP_PROTOCOL_ERROR, aiM("ai_mcpServiceConnectionFailed"));
13393
13390
  const timeoutMs = service.timeoutMs ?? 3e4;
13394
13391
  timeout = AbortSignal.timeout(timeoutMs);
13395
13392
  const signal = AbortSignal.any([
@@ -13415,24 +13412,24 @@ function createMCPServiceOperations(read, runner, files, configuredServices = []
13415
13412
  listener?.[Symbol.dispose]();
13416
13413
  }
13417
13414
  if (allowed !== true)
13418
- return err(HaiAIError.MCP_TOOL_FORBIDDEN, aiM("ai_mcpServiceForbidden"));
13415
+ return core.err(HaiAIError.MCP_TOOL_FORBIDDEN, aiM("ai_mcpServiceForbidden"));
13419
13416
  if (JSON.stringify(await read(input.serviceId)) !== JSON.stringify(service))
13420
- return err(HaiAIError.RESOURCE_CONFLICT, aiM("ai_resourceConflict"));
13417
+ return core.err(HaiAIError.RESOURCE_CONFLICT, aiM("ai_resourceConflict"));
13421
13418
  signal.throwIfAborted();
13422
13419
  if (service.transport === "job" && jobs) {
13423
13420
  connected = true;
13424
- 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));
13425
13422
  }
13426
13423
  if (!service.url)
13427
- return err(HaiAIError.MCP_PROTOCOL_ERROR, aiM("ai_mcpServiceConnectionFailed"));
13424
+ return core.err(HaiAIError.MCP_PROTOCOL_ERROR, aiM("ai_mcpServiceConnectionFailed"));
13428
13425
  const url = new URL(service.url);
13429
13426
  if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.hash)
13430
- return err(HaiAIError.MCP_PROTOCOL_ERROR, aiM("ai_mcpServiceConnectionFailed"));
13427
+ return core.err(HaiAIError.MCP_PROTOCOL_ERROR, aiM("ai_mcpServiceConnectionFailed"));
13431
13428
  const headers = new Headers();
13432
13429
  for (const [key, reference2] of Object.entries(service.headerEnv)) {
13433
13430
  const value = process2.env[reference2];
13434
13431
  if (!value || forbiddenHeaders.test(key))
13435
- return err(HaiAIError.MCP_CONNECTION_ERROR, aiM("ai_mcpServiceConnectionFailed"));
13432
+ return core.err(HaiAIError.MCP_CONNECTION_ERROR, aiM("ai_mcpServiceConnectionFailed"));
13436
13433
  headers.set(key, value);
13437
13434
  }
13438
13435
  let received = 0;
@@ -13473,16 +13470,16 @@ function createMCPServiceOperations(read, runner, files, configuredServices = []
13473
13470
  await client2.connect(transport, { signal, timeout: timeoutMs });
13474
13471
  connected = true;
13475
13472
  if (JSON.stringify(await read(input.serviceId)) !== JSON.stringify(service))
13476
- return err(HaiAIError.RESOURCE_CONFLICT, aiM("ai_resourceConflict"));
13473
+ return core.err(HaiAIError.RESOURCE_CONFLICT, aiM("ai_resourceConflict"));
13477
13474
  signal.throwIfAborted();
13478
13475
  const result = CallToolResultSchema.parse(await client2.callTool({ name: input.tool, arguments: input.arguments }, CallToolResultSchema, { signal, timeout: timeoutMs }));
13479
- 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);
13480
13477
  } catch {
13481
13478
  if (timeout?.aborted)
13482
- return err(HaiAIError.TIMEOUT, aiM("ai_requestTimeout"));
13479
+ return core.err(HaiAIError.TIMEOUT, aiM("ai_requestTimeout"));
13483
13480
  if (lifecycle.signal.aborted || authorization?.signal?.aborted)
13484
- return err(HaiAIError.MCP_TOOL_CANCELLED, aiM("ai_mcpServiceCancelled"));
13485
- 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"));
13486
13483
  } finally {
13487
13484
  fetchSignal = AbortSignal.timeout(1e3);
13488
13485
  await transport?.terminateSession().catch(() => void 0);
@@ -13498,27 +13495,27 @@ function createMCPServiceOperations(read, runner, files, configuredServices = []
13498
13495
  }
13499
13496
  };
13500
13497
  }
13501
- function createScopedMemory(core39, binding) {
13498
+ function createScopedMemory(memoryCore, binding) {
13502
13499
  if (typeof binding.objectId !== "string" || !binding.objectId.trim())
13503
13500
  throw new TypeError(aiM("ai_memoryScopeInvalid"));
13504
13501
  const { objectId, scope } = binding;
13505
13502
  const accessScope = { objectId, scope };
13506
13503
  return {
13507
- extract: (messages, options) => core39.extract(messages, { ...options, objectId, scope }),
13508
- recall: (query, options) => core39.recall(query, { ...options, objectId, scope }),
13509
- injectMemories: (messages, options) => core39.injectMemories(messages, { ...options, objectId, scope }),
13510
- add: (entry) => core39.add({ ...entry, objectId, scope }),
13511
- update: (memoryId, updates) => core39.update(memoryId, updates, accessScope),
13512
- get: (memoryId) => core39.get(memoryId, accessScope),
13513
- remove: (memoryId) => core39.remove(memoryId, accessScope),
13514
- list: (options) => core39.list({ ...options, objectId, scope }),
13515
- listPage: (options) => core39.listPage({ ...options, objectId, scope }),
13516
- 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 })
13517
13514
  };
13518
13515
  }
13519
- function createMemoryOperations(core39) {
13516
+ function createMemoryOperations(memoryCore) {
13520
13517
  return {
13521
- ...core39,
13518
+ ...memoryCore,
13522
13519
  /**
13523
13520
  * 清空记忆(空过滤保护)。
13524
13521
  *
@@ -13527,20 +13524,20 @@ function createMemoryOperations(core39) {
13527
13524
  */
13528
13525
  async clear(options) {
13529
13526
  if (options?.objectId !== void 0 && (typeof options.objectId !== "string" || !options.objectId.trim()))
13530
- return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryScopeInvalid"));
13527
+ return core.err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryScopeInvalid"));
13531
13528
  const hasFilter = Boolean(options?.objectId?.trim()) || Boolean(options?.types?.length) || Boolean(options?.scope && Object.keys(options.scope).length);
13532
13529
  if (!hasFilter) {
13533
- return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryClearRequiresFilter"));
13530
+ return core.err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryClearRequiresFilter"));
13534
13531
  }
13535
- return core39.clear(options);
13532
+ return memoryCore.clear(options);
13536
13533
  },
13537
- scoped: (binding) => createScopedMemory(core39, binding),
13534
+ scoped: (binding) => createScopedMemory(memoryCore, binding),
13538
13535
  admin: {
13539
13536
  async clearAll(options) {
13540
13537
  if (options?.confirm !== true) {
13541
- return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryClearAllUnconfirmed"));
13538
+ return core.err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryClearAllUnconfirmed"));
13542
13539
  }
13543
- return core39.clear();
13540
+ return memoryCore.clear();
13544
13541
  }
13545
13542
  }
13546
13543
  };
@@ -13700,7 +13697,7 @@ function formatMessages(messages) {
13700
13697
  async function extractMemories(llm, messages, options) {
13701
13698
  const conversationText = formatMessages(messages);
13702
13699
  if (!conversationText.trim()) {
13703
- return ok([]);
13700
+ return core.ok([]);
13704
13701
  }
13705
13702
  try {
13706
13703
  let userPrompt = conversationText;
@@ -13721,7 +13718,7 @@ Only extract memories of these types: ${options.types.join(", ")}`;
13721
13718
  });
13722
13719
  if (!chatResult.success) {
13723
13720
  logger22.warn("Memory extraction LLM call failed", { error: chatResult.error });
13724
- return err(HaiAIError.MEMORY_EXTRACT_FAILED, aiM("ai_memoryExtractFailed", {
13721
+ return core.err(HaiAIError.MEMORY_EXTRACT_FAILED, aiM("ai_memoryExtractFailed", {
13725
13722
  params: {
13726
13723
  error: String(chatResult.error.message)
13727
13724
  }
@@ -13740,10 +13737,10 @@ Only extract memories of these types: ${options.types.join(", ")}`;
13740
13737
  entries = entries.map((e) => ({ ...e, objectId: options.objectId }));
13741
13738
  }
13742
13739
  logger22.trace("Memory extraction completed", { messageCount: messages.length, extractedCount: entries.length });
13743
- return ok(entries);
13740
+ return core.ok(entries);
13744
13741
  } catch (error) {
13745
13742
  logger22.error("Memory extraction failed", { error });
13746
- return err(HaiAIError.MEMORY_EXTRACT_FAILED, aiM("ai_memoryExtractFailed", {
13743
+ return core.err(HaiAIError.MEMORY_EXTRACT_FAILED, aiM("ai_memoryExtractFailed", {
13747
13744
  params: {
13748
13745
  error: String(error)
13749
13746
  }
@@ -13828,7 +13825,7 @@ async function injectRelevantMemories(messages, options, recall) {
13828
13825
  try {
13829
13826
  const query = extractQueryFromMessages(messages);
13830
13827
  if (!query)
13831
- return ok([...messages]);
13828
+ return core.ok([...messages]);
13832
13829
  const recallResult = await recall(query, {
13833
13830
  topK,
13834
13831
  candidateMultiplier: options?.candidateMultiplier,
@@ -13838,12 +13835,12 @@ async function injectRelevantMemories(messages, options, recall) {
13838
13835
  minImportance: options?.minImportance
13839
13836
  });
13840
13837
  if (!recallResult.success) {
13841
- return err(HaiAIError.MEMORY_ENRICH_FAILED, aiM("ai_memoryEnrichFailed", {
13838
+ return core.err(HaiAIError.MEMORY_ENRICH_FAILED, aiM("ai_memoryEnrichFailed", {
13842
13839
  params: { error: recallResult.error.message }
13843
13840
  }), recallResult.error);
13844
13841
  }
13845
13842
  if (recallResult.data.length === 0)
13846
- return ok([...messages]);
13843
+ return core.ok([...messages]);
13847
13844
  let memoryText = recallResult.data.map((memory, index) => `[${index + 1}] (${memory.type}) ${memory.content}`).join("\n");
13848
13845
  if (options?.maxTokens && options.maxTokens > 0) {
13849
13846
  const estimatedTokens = memoryText.length * 0.25;
@@ -13888,10 +13885,10 @@ ${memoryText}
13888
13885
  }
13889
13886
  }
13890
13887
  logger23.trace("Memories enriched", { count: recallResult.data.length, position });
13891
- return ok(result);
13888
+ return core.ok(result);
13892
13889
  } catch (error) {
13893
13890
  logger23.error("Memory enrichment failed", { error });
13894
- return err(HaiAIError.MEMORY_ENRICH_FAILED, aiM("ai_memoryEnrichFailed", {
13891
+ return core.err(HaiAIError.MEMORY_ENRICH_FAILED, aiM("ai_memoryEnrichFailed", {
13895
13892
  params: {
13896
13893
  error: String(error)
13897
13894
  }
@@ -14221,7 +14218,7 @@ var MEMORY_TYPES = /* @__PURE__ */ new Set([
14221
14218
  var Mem0ListIncompleteError = class extends Error {
14222
14219
  };
14223
14220
  function memoryWriteFailure(definition, message, memoryIds) {
14224
- const failure = err(definition, message);
14221
+ const failure = core.err(definition, message);
14225
14222
  if (!failure.success) {
14226
14223
  failure.error.ext = {
14227
14224
  requiresEffectReconciliation: true,
@@ -14302,20 +14299,20 @@ function buildVectorStoreConfig(deps) {
14302
14299
  } catch {
14303
14300
  }
14304
14301
  if (!validConnection) {
14305
- return err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_memoryBackendConnectionRequired", {
14302
+ return core.err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_memoryBackendConnectionRequired", {
14306
14303
  params: { backend: backend.type }
14307
14304
  }));
14308
14305
  }
14309
- return ok({
14306
+ return core.ok({
14310
14307
  provider: "qdrant",
14311
14308
  persistent: true,
14312
14309
  backend: { url: backend.url, apiKey: backend.apiKey }
14313
14310
  });
14314
14311
  }
14315
14312
  if (backend?.type === "pgvector")
14316
- return err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_memoryBackendUnsupported"));
14313
+ return core.err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_memoryBackendUnsupported"));
14317
14314
  if (backend && !deps.config.allowEphemeralFallback) {
14318
- return err(
14315
+ return core.err(
14319
14316
  HaiAIError.CONFIGURATION_ERROR,
14320
14317
  aiM("ai_memoryEphemeralFallbackDenied", {
14321
14318
  params: { backend: backend.type }
@@ -14324,7 +14321,7 @@ function buildVectorStoreConfig(deps) {
14324
14321
  }
14325
14322
  if (backend)
14326
14323
  logger24.warn("Mem0 format falls back to in-memory vector store (allowEphemeralFallback=true); data will not survive restart", { backend: backend.type });
14327
- return ok({
14324
+ return core.ok({
14328
14325
  provider: "memory",
14329
14326
  persistent: false
14330
14327
  });
@@ -14344,7 +14341,7 @@ async function extractMemories2(context, messages, options) {
14344
14341
  if (!extracted.success)
14345
14342
  return extracted;
14346
14343
  if (extracted.data.length === 0)
14347
- return ok([]);
14344
+ return core.ok([]);
14348
14345
  try {
14349
14346
  const stored = await Promise.allSettled(extracted.data.map(async (entry) => {
14350
14347
  const id3 = await context.memory.add(entry.content, objectId, buildMetadata({
@@ -14362,7 +14359,7 @@ async function extractMemories2(context, messages, options) {
14362
14359
  const failed = stored.find((result) => result.status === "rejected");
14363
14360
  if (failed?.status === "rejected")
14364
14361
  throw failed.reason;
14365
- return ok(stored.flatMap((result) => result.status === "fulfilled" ? [result.value] : []));
14362
+ return core.ok(stored.flatMap((result) => result.status === "fulfilled" ? [result.value] : []));
14366
14363
  } catch (error) {
14367
14364
  logger24.error("Mem0 format extract failed", {
14368
14365
  error: core.sanitize.sanitizeSensitiveFields(error)
@@ -14389,12 +14386,12 @@ async function recallMemories(context, query, options) {
14389
14386
  return { entry, score: relevance * (1 - recencyWeight) + recency * recencyWeight };
14390
14387
  }).sort((a, b) => b.score - a.score).map((ranked) => ranked.entry);
14391
14388
  }
14392
- return ok(entries.slice(0, topK));
14389
+ return core.ok(entries.slice(0, topK));
14393
14390
  } catch (error) {
14394
14391
  logger24.error("Mem0 format recall failed", {
14395
14392
  error: core.sanitize.sanitizeSensitiveFields(error)
14396
14393
  });
14397
- return err(HaiAIError.MEMORY_RECALL_FAILED, aiM("ai_memoryOperationFailed"));
14394
+ return core.err(HaiAIError.MEMORY_RECALL_FAILED, aiM("ai_memoryOperationFailed"));
14398
14395
  }
14399
14396
  }
14400
14397
  async function addMemory(context, entry) {
@@ -14406,7 +14403,7 @@ async function addMemory(context, entry) {
14406
14403
  const persisted = await context.memory.get(id3);
14407
14404
  if (!persisted)
14408
14405
  throw new Error("Mem0 format stored memory could not be read back");
14409
- return ok(toMemoryEntry(persisted, objectId));
14406
+ return core.ok(toMemoryEntry(persisted, objectId));
14410
14407
  } catch (error) {
14411
14408
  logger24.error("Mem0 format add failed", {
14412
14409
  error: core.sanitize.sanitizeSensitiveFields(error)
@@ -14418,13 +14415,13 @@ async function updateMemory(context, memoryId, updates, accessScope) {
14418
14415
  try {
14419
14416
  const item2 = await context.memory.get(memoryId);
14420
14417
  if (!item2) {
14421
- return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14418
+ return core.err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14422
14419
  params: { id: memoryId }
14423
14420
  }));
14424
14421
  }
14425
14422
  const existing = toMemoryEntry(item2, context.defaultObjectId);
14426
14423
  if (isMemoryAccessDenied(existing, accessScope)) {
14427
- return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14424
+ return core.err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14428
14425
  params: { id: memoryId }
14429
14426
  }));
14430
14427
  }
@@ -14440,11 +14437,11 @@ async function updateMemory(context, memoryId, updates, accessScope) {
14440
14437
  await context.memory.update(memoryId, updates.content, buildMetadata(merged, objectId), objectId);
14441
14438
  const refreshed = await context.memory.get(memoryId);
14442
14439
  if (!refreshed) {
14443
- return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14440
+ return core.err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14444
14441
  params: { id: memoryId }
14445
14442
  }));
14446
14443
  }
14447
- return ok(toMemoryEntry(refreshed, objectId));
14444
+ return core.ok(toMemoryEntry(refreshed, objectId));
14448
14445
  } catch (error) {
14449
14446
  logger24.error("Mem0 format update failed", {
14450
14447
  id: memoryId,
@@ -14457,22 +14454,22 @@ async function getMemory(context, memoryId, accessScope) {
14457
14454
  try {
14458
14455
  const item2 = await context.memory.get(memoryId);
14459
14456
  if (!item2) {
14460
- return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14457
+ return core.err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14461
14458
  params: { id: memoryId }
14462
14459
  }));
14463
14460
  }
14464
14461
  const entry = toMemoryEntry(item2, context.defaultObjectId);
14465
14462
  if (isMemoryAccessDenied(entry, accessScope)) {
14466
- return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14463
+ return core.err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14467
14464
  params: { id: memoryId }
14468
14465
  }));
14469
14466
  }
14470
- return ok(entry);
14467
+ return core.ok(entry);
14471
14468
  } catch (error) {
14472
14469
  logger24.error("Mem0 format read failed", {
14473
14470
  error: core.sanitize.sanitizeSensitiveFields(error)
14474
14471
  });
14475
- return err(HaiAIError.MEMORY_RECALL_FAILED, aiM("ai_memoryOperationFailed"));
14472
+ return core.err(HaiAIError.MEMORY_RECALL_FAILED, aiM("ai_memoryOperationFailed"));
14476
14473
  }
14477
14474
  }
14478
14475
  async function removeMemory(context, memoryId, accessScope) {
@@ -14480,18 +14477,18 @@ async function removeMemory(context, memoryId, accessScope) {
14480
14477
  if (accessScope) {
14481
14478
  const item2 = await context.memory.get(memoryId);
14482
14479
  if (!item2 || isMemoryAccessDenied(toMemoryEntry(item2, context.defaultObjectId), accessScope)) {
14483
- return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14480
+ return core.err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
14484
14481
  params: { id: memoryId }
14485
14482
  }));
14486
14483
  }
14487
14484
  }
14488
14485
  await context.memory.remove(memoryId);
14489
- return ok(void 0);
14486
+ return core.ok(void 0);
14490
14487
  } catch (error) {
14491
14488
  logger24.error("Mem0 format delete failed", {
14492
14489
  error: core.sanitize.sanitizeSensitiveFields(error)
14493
14490
  });
14494
- return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
14491
+ return core.err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
14495
14492
  }
14496
14493
  }
14497
14494
  function isExpiredMemory(item2, today) {
@@ -14524,7 +14521,7 @@ async function createMem0MemoryOperations(deps) {
14524
14521
  if (!configResult.success)
14525
14522
  throw configResult.error;
14526
14523
  if (core.module.requiresSharedState(process2.env) && !configResult.data.persistent) {
14527
- const failure = err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_memorySharedBackendRequired"));
14524
+ const failure = core.err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_memorySharedBackendRequired"));
14528
14525
  if (!failure.success)
14529
14526
  throw failure.error;
14530
14527
  }
@@ -14540,7 +14537,7 @@ async function createMem0MemoryOperations(deps) {
14540
14537
  logger24.error("Mem0 data storage initialization failed", {
14541
14538
  error: core.sanitize.sanitizeSensitiveFields(error)
14542
14539
  });
14543
- const failure = err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_memoryOperationFailed"));
14540
+ const failure = core.err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_memoryOperationFailed"));
14544
14541
  if (!failure.success)
14545
14542
  throw failure.error;
14546
14543
  throw new Error("Unreachable memory initialization state");
@@ -14576,7 +14573,7 @@ async function createMem0MemoryOperations(deps) {
14576
14573
  remove: (memoryId, accessScope) => removeMemory(context, memoryId, accessScope),
14577
14574
  async list(options) {
14578
14575
  try {
14579
- return ok(await listMemories(context, options));
14576
+ return core.ok(await listMemories(context, options));
14580
14577
  } catch (error) {
14581
14578
  logger24.error("Mem0 data list failed", {
14582
14579
  operation: "list",
@@ -14584,8 +14581,8 @@ async function createMem0MemoryOperations(deps) {
14584
14581
  error: core.sanitize.sanitizeSensitiveFields(error)
14585
14582
  });
14586
14583
  if (error instanceof Mem0ListIncompleteError)
14587
- return err(HaiAIError.MEMORY_LIST_INCOMPLETE, error.message);
14588
- 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"));
14589
14586
  }
14590
14587
  },
14591
14588
  async listPage(options) {
@@ -14593,7 +14590,7 @@ async function createMem0MemoryOperations(deps) {
14593
14590
  const offset = options?.offset ?? 0;
14594
14591
  const limit = options?.limit ?? 20;
14595
14592
  const all = await listMemories(context, { objectId: options?.objectId, types: options?.types, scope: options?.scope });
14596
- return ok({
14593
+ return core.ok({
14597
14594
  items: all.slice(offset, offset + limit),
14598
14595
  total: all.length
14599
14596
  });
@@ -14604,8 +14601,8 @@ async function createMem0MemoryOperations(deps) {
14604
14601
  error: core.sanitize.sanitizeSensitiveFields(error)
14605
14602
  });
14606
14603
  if (error instanceof Mem0ListIncompleteError)
14607
- return err(HaiAIError.MEMORY_LIST_INCOMPLETE, error.message);
14608
- 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"));
14609
14606
  }
14610
14607
  },
14611
14608
  /**
@@ -14620,11 +14617,11 @@ async function createMem0MemoryOperations(deps) {
14620
14617
  const hasTypeOrScope = Boolean(options?.types?.length) || Boolean(options?.scope);
14621
14618
  if (!options?.objectId && !hasTypeOrScope) {
14622
14619
  await context.memory.clear();
14623
- return ok(void 0);
14620
+ return core.ok(void 0);
14624
14621
  }
14625
14622
  if (options?.objectId && !hasTypeOrScope) {
14626
14623
  await context.memory.removeObject(options.objectId);
14627
- return ok(void 0);
14624
+ return core.ok(void 0);
14628
14625
  }
14629
14626
  const matched = await listMemories(context, { objectId: options?.objectId, types: options?.types, scope: options?.scope });
14630
14627
  for (const entry of matched)
@@ -14635,7 +14632,7 @@ async function createMem0MemoryOperations(deps) {
14635
14632
  types: options?.types,
14636
14633
  scoped: Boolean(options?.scope)
14637
14634
  });
14638
- return ok(void 0);
14635
+ return core.ok(void 0);
14639
14636
  } catch (error) {
14640
14637
  logger24.error("Mem0 data clear failed", {
14641
14638
  operation: "clear",
@@ -14643,8 +14640,8 @@ async function createMem0MemoryOperations(deps) {
14643
14640
  error: core.sanitize.sanitizeSensitiveFields(error)
14644
14641
  });
14645
14642
  if (error instanceof Mem0ListIncompleteError)
14646
- return err(HaiAIError.MEMORY_LIST_INCOMPLETE, error.message);
14647
- 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"));
14648
14645
  }
14649
14646
  }
14650
14647
  };
@@ -14709,7 +14706,7 @@ async function collectRelated(deps, candidates, options) {
14709
14706
  for (const entry of result.data)
14710
14707
  related.set(entry.id, entry);
14711
14708
  }
14712
- return ok([
14709
+ return core.ok([
14713
14710
  ...related.values()
14714
14711
  ]);
14715
14712
  }
@@ -14807,7 +14804,7 @@ async function applyConsolidationOps(deps, ops, options) {
14807
14804
  return addResult;
14808
14805
  entries.push(addResult.data);
14809
14806
  }
14810
- return ok(entries);
14807
+ return core.ok(entries);
14811
14808
  }
14812
14809
  async function extractAndConsolidate(deps, messages, options) {
14813
14810
  logger25.trace("Consolidation extract", { messageCount: messages.length });
@@ -14824,7 +14821,7 @@ async function extractAndConsolidate(deps, messages, options) {
14824
14821
  return extractResult;
14825
14822
  const candidates = extractResult.data;
14826
14823
  if (candidates.length === 0)
14827
- return ok([]);
14824
+ return core.ok([]);
14828
14825
  const relatedResult = await collectRelated(deps, candidates, options);
14829
14826
  if (!relatedResult.success)
14830
14827
  return relatedResult;
@@ -14856,7 +14853,7 @@ async function extractAndConsolidate(deps, messages, options) {
14856
14853
  signal: options?.signal
14857
14854
  });
14858
14855
  if (!consolidationResult.success) {
14859
- return err(HaiAIError.MEMORY_EXTRACT_FAILED, aiM("ai_memoryExtractFailed", {
14856
+ return core.err(HaiAIError.MEMORY_EXTRACT_FAILED, aiM("ai_memoryExtractFailed", {
14860
14857
  params: {
14861
14858
  error: String(consolidationResult.error.message)
14862
14859
  }
@@ -14887,7 +14884,7 @@ async function extractAndConsolidate(deps, messages, options) {
14887
14884
  ops: ops.length,
14888
14885
  written: applyResult.data.length
14889
14886
  });
14890
- return ok(applyResult.data);
14887
+ return core.ok(applyResult.data);
14891
14888
  }
14892
14889
  var logger26 = core.logger.child({ module: "ai", scope: "memory-vector-scan" });
14893
14890
  var checkpointId = "scan";
@@ -15228,7 +15225,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
15228
15225
  logger28.error("Memory storage operation failed", {
15229
15226
  error: core.sanitize.sanitizeSensitiveFields(error)
15230
15227
  });
15231
- return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
15228
+ return core.err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
15232
15229
  }
15233
15230
  }
15234
15231
  async function touchEntry(memoryId, accessScope) {
@@ -15346,7 +15343,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
15346
15343
  try {
15347
15344
  const before = await store.get(memoryId);
15348
15345
  if (!before || isMemoryAccessDenied(before, accessScope)) {
15349
- return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
15346
+ return core.err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
15350
15347
  params: { id: memoryId }
15351
15348
  }));
15352
15349
  }
@@ -15390,18 +15387,18 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
15390
15387
  return publicEntry(changed);
15391
15388
  });
15392
15389
  if (!existing) {
15393
- return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
15390
+ return core.err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
15394
15391
  params: { id: memoryId }
15395
15392
  }));
15396
15393
  }
15397
15394
  logger28.trace("Memory updated", { id: memoryId });
15398
- return ok(existing);
15395
+ return core.ok(existing);
15399
15396
  } catch (error) {
15400
15397
  logger28.error("Memory update failed", {
15401
15398
  id: memoryId,
15402
15399
  error: core.sanitize.sanitizeSensitiveFields(error)
15403
15400
  });
15404
- return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
15401
+ return core.err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
15405
15402
  }
15406
15403
  }
15407
15404
  async function recallEntries(query, options, updateAccessStats = true) {
@@ -15431,7 +15428,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
15431
15428
  });
15432
15429
  const candidates = options?.scope ? allCandidates.filter((e) => matchScope2(e, options.scope)) : allCandidates;
15433
15430
  if (candidates.length === 0) {
15434
- return ok([]);
15431
+ return core.ok([]);
15435
15432
  }
15436
15433
  let queryVector;
15437
15434
  if (config.embeddingEnabled && embedding) {
@@ -15487,12 +15484,12 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
15487
15484
  resultCount: results.length,
15488
15485
  updateAccessStats
15489
15486
  });
15490
- return ok(results);
15487
+ return core.ok(results);
15491
15488
  } catch (error) {
15492
15489
  logger28.error("Memory recall failed", {
15493
15490
  error: core.sanitize.sanitizeSensitiveFields(error)
15494
15491
  });
15495
- return err(HaiAIError.MEMORY_RECALL_FAILED, aiM("ai_memoryOperationFailed"));
15492
+ return core.err(HaiAIError.MEMORY_RECALL_FAILED, aiM("ai_memoryOperationFailed"));
15496
15493
  }
15497
15494
  }
15498
15495
  const operations2 = {
@@ -15540,14 +15537,14 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
15540
15537
  const vector = await computeVector(entry.content);
15541
15538
  const stored = await saveEntry(entry, vector);
15542
15539
  if (!stored)
15543
- return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
15540
+ return core.err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
15544
15541
  logger28.trace("Memory added", { id: stored.id, type: stored.type });
15545
- return ok(stored);
15542
+ return core.ok(stored);
15546
15543
  } catch (error) {
15547
15544
  logger28.error("Memory add failed", {
15548
15545
  error: core.sanitize.sanitizeSensitiveFields(error)
15549
15546
  });
15550
- return err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
15547
+ return core.err(HaiAIError.MEMORY_STORE_FAILED, aiM("ai_memoryOperationFailed"));
15551
15548
  }
15552
15549
  },
15553
15550
  /**
@@ -15566,11 +15563,11 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
15566
15563
  async get(memoryId, accessScope) {
15567
15564
  const entry = await touchEntry(memoryId, accessScope);
15568
15565
  if (!entry) {
15569
- return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
15566
+ return core.err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
15570
15567
  params: { id: memoryId }
15571
15568
  }));
15572
15569
  }
15573
- return ok(publicEntry(entry));
15570
+ return core.ok(publicEntry(entry));
15574
15571
  },
15575
15572
  /**
15576
15573
  * 根据 ID 删除一条记忆(同时清理关系存储与向量库)
@@ -15587,12 +15584,12 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
15587
15584
  return deleteEntry(active, existing, pending);
15588
15585
  });
15589
15586
  if (!removed2) {
15590
- return err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
15587
+ return core.err(HaiAIError.MEMORY_NOT_FOUND, aiM("ai_memoryNotFound", {
15591
15588
  params: { id: memoryId }
15592
15589
  }));
15593
15590
  }
15594
15591
  logger28.trace("Memory removed", { id: memoryId });
15595
- return ok(void 0);
15592
+ return core.ok(void 0);
15596
15593
  },
15597
15594
  /**
15598
15595
  * 列出记忆条目(不分页)
@@ -15617,9 +15614,9 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
15617
15614
  limit: options?.scope ? void 0 : options?.limit
15618
15615
  });
15619
15616
  if (!options?.scope)
15620
- return ok(results.map(publicEntry));
15617
+ return core.ok(results.map(publicEntry));
15621
15618
  const filtered = results.filter((e) => matchScope2(e, options.scope));
15622
- 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));
15623
15620
  },
15624
15621
  /**
15625
15622
  * 分页列出记忆条目
@@ -15647,7 +15644,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
15647
15644
  },
15648
15645
  { offset, limit }
15649
15646
  );
15650
- return ok({
15647
+ return core.ok({
15651
15648
  ...page,
15652
15649
  items: page.items.map(publicEntry)
15653
15650
  });
@@ -15659,7 +15656,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
15659
15656
  orderBy: { field: "createdAt", direction: "desc" }
15660
15657
  });
15661
15658
  const filtered = all.filter((e) => matchScope2(e, options.scope));
15662
- return ok({
15659
+ return core.ok({
15663
15660
  items: filtered.slice(offset, offset + limit).map(publicEntry),
15664
15661
  total: filtered.length
15665
15662
  });
@@ -15678,7 +15675,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
15678
15675
  await vectorStore.clear();
15679
15676
  await store.clear();
15680
15677
  logger28.debug("All memories cleared");
15681
- return ok(void 0);
15678
+ return core.ok(void 0);
15682
15679
  }
15683
15680
  const where = {};
15684
15681
  if (options?.types && options.types.length === 1)
@@ -15714,7 +15711,7 @@ function assembleNativeMemory(config, llm, embedding, store, vectorStore, vector
15714
15711
  types: options?.types,
15715
15712
  scoped: Boolean(scope)
15716
15713
  });
15717
- return ok(void 0);
15714
+ return core.ok(void 0);
15718
15715
  }
15719
15716
  };
15720
15717
  return {
@@ -15751,7 +15748,7 @@ function createPersonaOperations(store) {
15751
15748
  logger29.error("Persona storage operation failed", {
15752
15749
  error: core.sanitize.sanitizeSensitiveFields(error)
15753
15750
  });
15754
- return err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
15751
+ return core.err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
15755
15752
  }
15756
15753
  }
15757
15754
  const operations2 = {
@@ -15773,30 +15770,30 @@ function createPersonaOperations(store) {
15773
15770
  };
15774
15771
  await store.save(key, profile, { objectId });
15775
15772
  logger29.trace("Persona saved", { id: profile.id, objectId });
15776
- return ok(profile);
15773
+ return core.ok(profile);
15777
15774
  } catch (error) {
15778
15775
  logger29.error("Persona save failed", {
15779
15776
  error: core.sanitize.sanitizeSensitiveFields(error)
15780
15777
  });
15781
- return err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
15778
+ return core.err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
15782
15779
  }
15783
15780
  },
15784
15781
  async get(id3, options) {
15785
15782
  const objectId = options?.objectId ?? DEFAULT_OBJECT_ID2;
15786
15783
  const profile = await store.get(personaKey(objectId, id3));
15787
15784
  if (!profile) {
15788
- return err(HaiAIError.PERSONA_NOT_FOUND, aiM("ai_personaNotFound", {
15785
+ return core.err(HaiAIError.PERSONA_NOT_FOUND, aiM("ai_personaNotFound", {
15789
15786
  params: { id: id3 }
15790
15787
  }));
15791
15788
  }
15792
- return ok(profile);
15789
+ return core.ok(profile);
15793
15790
  },
15794
15791
  async update(id3, updates, options) {
15795
15792
  const objectId = options?.objectId ?? DEFAULT_OBJECT_ID2;
15796
15793
  const key = personaKey(objectId, id3);
15797
15794
  const existing = await store.get(key);
15798
15795
  if (!existing) {
15799
- return err(HaiAIError.PERSONA_NOT_FOUND, aiM("ai_personaNotFound", {
15796
+ return core.err(HaiAIError.PERSONA_NOT_FOUND, aiM("ai_personaNotFound", {
15800
15797
  params: { id: id3 }
15801
15798
  }));
15802
15799
  }
@@ -15810,18 +15807,18 @@ function createPersonaOperations(store) {
15810
15807
  updatedAt: Date.now()
15811
15808
  };
15812
15809
  await store.save(key, profile, { objectId });
15813
- return ok(profile);
15810
+ return core.ok(profile);
15814
15811
  } catch (error) {
15815
15812
  logger29.error("Persona update failed", {
15816
15813
  error: core.sanitize.sanitizeSensitiveFields(error)
15817
15814
  });
15818
- return err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
15815
+ return core.err(HaiAIError.PERSONA_SAVE_FAILED, aiM("ai_personaOperationFailed"));
15819
15816
  }
15820
15817
  },
15821
15818
  async remove(id3, options) {
15822
15819
  const objectId = options?.objectId ?? DEFAULT_OBJECT_ID2;
15823
15820
  await store.remove(personaKey(objectId, id3));
15824
- return ok(void 0);
15821
+ return core.ok(void 0);
15825
15822
  },
15826
15823
  async list(options) {
15827
15824
  const objectId = options?.objectId ?? DEFAULT_OBJECT_ID2;
@@ -15829,17 +15826,17 @@ function createPersonaOperations(store) {
15829
15826
  objectId,
15830
15827
  orderBy: { field: "createdAt", direction: "asc" }
15831
15828
  });
15832
- return ok(profiles);
15829
+ return core.ok(profiles);
15833
15830
  },
15834
15831
  async compose(id3, options) {
15835
15832
  const objectId = options?.objectId ?? DEFAULT_OBJECT_ID2;
15836
15833
  const profile = await store.get(personaKey(objectId, id3));
15837
15834
  if (!profile) {
15838
- return err(HaiAIError.PERSONA_NOT_FOUND, aiM("ai_personaNotFound", {
15835
+ return core.err(HaiAIError.PERSONA_NOT_FOUND, aiM("ai_personaNotFound", {
15839
15836
  params: { id: id3 }
15840
15837
  }));
15841
15838
  }
15842
- return ok(composeSystemPrompt(profile));
15839
+ return core.ok(composeSystemPrompt(profile));
15843
15840
  }
15844
15841
  };
15845
15842
  return {
@@ -15893,7 +15890,7 @@ function createRagOperations(llm, retrieval) {
15893
15890
  rerankModel: options?.rerankModel
15894
15891
  });
15895
15892
  if (!retrieveResult.success) {
15896
- return err(HaiAIError.RAG_CONTEXT_BUILD_FAILED, aiM("ai_internalError", {
15893
+ return core.err(HaiAIError.RAG_CONTEXT_BUILD_FAILED, aiM("ai_internalError", {
15897
15894
  params: { error: "Failed to retrieve context" }
15898
15895
  }), retrieveResult.error);
15899
15896
  }
@@ -15929,7 +15926,7 @@ ${contextText}
15929
15926
  signal: options?.signal
15930
15927
  });
15931
15928
  if (!chatResult.success) {
15932
- return err(HaiAIError.RAG_FAILED, aiM("ai_internalError", {
15929
+ return core.err(HaiAIError.RAG_FAILED, aiM("ai_internalError", {
15933
15930
  params: { error: "LLM generation failed" }
15934
15931
  }), chatResult.error);
15935
15932
  }
@@ -15949,7 +15946,7 @@ ${contextText}
15949
15946
  }
15950
15947
  }
15951
15948
  const citations = Array.from(citationMap.values());
15952
- return ok({
15949
+ return core.ok({
15953
15950
  answer,
15954
15951
  context: contextItems,
15955
15952
  citations,
@@ -15963,7 +15960,7 @@ ${contextText}
15963
15960
  });
15964
15961
  } catch (error) {
15965
15962
  logger30.error("RAG query failed", { code: HaiAIError.RAG_FAILED.code, queryLength: query.length });
15966
- return err(HaiAIError.RAG_FAILED, aiM("ai_internalError", {
15963
+ return core.err(HaiAIError.RAG_FAILED, aiM("ai_internalError", {
15967
15964
  params: {
15968
15965
  error: String(error)
15969
15966
  }
@@ -16108,7 +16105,7 @@ function createReasoningOperations(config, llm) {
16108
16105
  return chatResult;
16109
16106
  const choice = chatResult.data.choices[0];
16110
16107
  if (!choice) {
16111
- return err(HaiAIError.REASONING_FAILED, aiM("ai_internalError", {
16108
+ return core.err(HaiAIError.REASONING_FAILED, aiM("ai_internalError", {
16112
16109
  params: { error: "No response from LLM" }
16113
16110
  }));
16114
16111
  }
@@ -16153,7 +16150,7 @@ function createReasoningOperations(config, llm) {
16153
16150
  if (choice.finish_reason === "stop") {
16154
16151
  const answer = typeof assistantMessage.content === "string" ? assistantMessage.content : "";
16155
16152
  steps.push({ type: "answer", content: answer, index: stepIndex });
16156
- return ok({
16153
+ return core.ok({
16157
16154
  answer,
16158
16155
  steps,
16159
16156
  strategy: "react",
@@ -16162,7 +16159,7 @@ function createReasoningOperations(config, llm) {
16162
16159
  });
16163
16160
  }
16164
16161
  }
16165
- return err(HaiAIError.REASONING_MAX_ROUNDS, aiM("ai_internalError", {
16162
+ return core.err(HaiAIError.REASONING_MAX_ROUNDS, aiM("ai_internalError", {
16166
16163
  params: { error: `Max rounds (${maxRounds}) reached` }
16167
16164
  }));
16168
16165
  }
@@ -16204,7 +16201,7 @@ Please think step by step.` }
16204
16201
  });
16205
16202
  }
16206
16203
  messages.push({ role: "assistant", content: answer });
16207
- return ok({
16204
+ return core.ok({
16208
16205
  answer,
16209
16206
  steps,
16210
16207
  strategy: "cot",
@@ -16292,7 +16289,7 @@ ${query}` }
16292
16289
  if (choice.finish_reason === "stop") {
16293
16290
  const answer = typeof msg.content === "string" ? msg.content : "";
16294
16291
  steps.push({ type: "answer", content: answer, index: stepIndex });
16295
- return ok({
16292
+ return core.ok({
16296
16293
  answer,
16297
16294
  steps,
16298
16295
  strategy: "plan-execute",
@@ -16301,7 +16298,7 @@ ${query}` }
16301
16298
  });
16302
16299
  }
16303
16300
  }
16304
- return err(HaiAIError.REASONING_MAX_ROUNDS, aiM("ai_internalError", {
16301
+ return core.err(HaiAIError.REASONING_MAX_ROUNDS, aiM("ai_internalError", {
16305
16302
  params: { error: `Max rounds (${maxRounds}) reached` }
16306
16303
  }));
16307
16304
  }
@@ -16318,13 +16315,13 @@ ${query}` }
16318
16315
  case "plan-execute":
16319
16316
  return await runPlanExecute(query, options ?? {});
16320
16317
  default:
16321
- return err(HaiAIError.REASONING_STRATEGY_NOT_FOUND, aiM("ai_internalError", {
16318
+ return core.err(HaiAIError.REASONING_STRATEGY_NOT_FOUND, aiM("ai_internalError", {
16322
16319
  params: { error: `Unknown strategy: ${strategy}` }
16323
16320
  }));
16324
16321
  }
16325
16322
  } catch (error) {
16326
16323
  logger31.error("Reasoning failed", { error });
16327
- return err(HaiAIError.REASONING_FAILED, aiM("ai_internalError", {
16324
+ return core.err(HaiAIError.REASONING_FAILED, aiM("ai_internalError", {
16328
16325
  params: {
16329
16326
  error: String(error)
16330
16327
  }
@@ -16385,7 +16382,7 @@ function createRerankOperations(config, loadModels = () => config.llm) {
16385
16382
  const resolved = resolvedResult.data;
16386
16383
  const { texts, ids } = normalizeDocuments(request2.documents);
16387
16384
  if (texts.length === 0) {
16388
- return err(HaiAIError.RERANK_INVALID_REQUEST, aiM("ai_rerankInvalidRequest", {
16385
+ return core.err(HaiAIError.RERANK_INVALID_REQUEST, aiM("ai_rerankInvalidRequest", {
16389
16386
  params: { reason: "documents cannot be empty" }
16390
16387
  }));
16391
16388
  }
@@ -16419,7 +16416,7 @@ function createRerankOperations(config, loadModels = () => config.llm) {
16419
16416
  status: response.status,
16420
16417
  providerRequestId: requestId && /^[\w.:-]{1,128}$/.test(requestId) ? requestId : void 0
16421
16418
  });
16422
- return err(HaiAIError.RERANK_API_ERROR, aiM("ai_rerankApiFailed", {
16419
+ return core.err(HaiAIError.RERANK_API_ERROR, aiM("ai_rerankApiFailed", {
16423
16420
  params: { error: `HTTP ${response.status}` }
16424
16421
  }));
16425
16422
  }
@@ -16431,11 +16428,11 @@ function createRerankOperations(config, loadModels = () => config.llm) {
16431
16428
  document: item2.document?.text
16432
16429
  }));
16433
16430
  logger32.trace("Rerank completed", { resultCount: results.length });
16434
- return ok({ model: resolved.model, results });
16431
+ return core.ok({ model: resolved.model, results });
16435
16432
  } catch (error) {
16436
16433
  const causeName = error instanceof Error ? error.name : void 0;
16437
16434
  logger32.error("Rerank API call failed", { causeName });
16438
- return err(HaiAIError.RERANK_API_ERROR, aiM("ai_rerankApiFailed", {
16435
+ return core.err(HaiAIError.RERANK_API_ERROR, aiM("ai_rerankApiFailed", {
16439
16436
  params: {
16440
16437
  error: causeName ?? core.i18n.coreM("core_errorInternal")
16441
16438
  }
@@ -16466,7 +16463,7 @@ function createRerankOperations(config, loadModels = () => config.llm) {
16466
16463
  const result = await callRerankAPI({ query, documents: texts, topN });
16467
16464
  if (!result.success)
16468
16465
  return result;
16469
- return ok(result.data.results);
16466
+ return core.ok(result.data.results);
16470
16467
  }
16471
16468
  };
16472
16469
  }
@@ -16494,17 +16491,17 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
16494
16491
  async addSource(source) {
16495
16492
  if (registry) {
16496
16493
  const result = await registry.operations.register(source);
16497
- return result.success ? ok(void 0) : result;
16494
+ return result.success ? core.ok(void 0) : result;
16498
16495
  }
16499
16496
  const existing = await sourceStore.get(source.id);
16500
16497
  if (existing) {
16501
- return err(HaiAIError.RETRIEVAL_FAILED, aiM("ai_internalError", {
16498
+ return core.err(HaiAIError.RETRIEVAL_FAILED, aiM("ai_internalError", {
16502
16499
  params: { error: `Source '${source.id}' already exists` }
16503
16500
  }));
16504
16501
  }
16505
16502
  await sourceStore.save(source.id, source);
16506
16503
  logger33.debug("Retrieval source added", { sourceId: source.id, collection: source.collection });
16507
- return ok(void 0);
16504
+ return core.ok(void 0);
16508
16505
  },
16509
16506
  /**
16510
16507
  * 取消注册检索源
@@ -16519,13 +16516,13 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
16519
16516
  return registry.operations.remove(sourceId);
16520
16517
  const existing = await sourceStore.get(sourceId);
16521
16518
  if (!existing) {
16522
- return err(HaiAIError.RETRIEVAL_SOURCE_NOT_FOUND, aiM("ai_internalError", {
16519
+ return core.err(HaiAIError.RETRIEVAL_SOURCE_NOT_FOUND, aiM("ai_internalError", {
16523
16520
  params: { error: `Source '${sourceId}' not found` }
16524
16521
  }));
16525
16522
  }
16526
16523
  await sourceStore.remove(sourceId);
16527
16524
  logger33.debug("Retrieval source removed", { sourceId });
16528
- return ok(void 0);
16525
+ return core.ok(void 0);
16529
16526
  },
16530
16527
  /**
16531
16528
  * 列出所有已注册的检索源
@@ -16557,13 +16554,13 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
16557
16554
  } : {}
16558
16555
  );
16559
16556
  if (targetSources.length === 0) {
16560
- return err(HaiAIError.RETRIEVAL_SOURCE_NOT_FOUND, aiM("ai_internalError", {
16557
+ return core.err(HaiAIError.RETRIEVAL_SOURCE_NOT_FOUND, aiM("ai_internalError", {
16561
16558
  params: { error: "No retrieval sources configured" }
16562
16559
  }));
16563
16560
  }
16564
16561
  const embedResult = await embeddingOps.embedText(request2.query);
16565
16562
  if (!embedResult.success) {
16566
- return err(HaiAIError.RETRIEVAL_FAILED, aiM("ai_internalError", {
16563
+ return core.err(HaiAIError.RETRIEVAL_FAILED, aiM("ai_internalError", {
16567
16564
  params: { error: "Failed to embed query" }
16568
16565
  }), embedResult.error);
16569
16566
  }
@@ -16619,14 +16616,14 @@ function createRetrievalOperations(embeddingOps, storeProvider, sourceStore, rer
16619
16616
  const limitedItems = allItems.slice(0, topK);
16620
16617
  const duration = Date.now() - startTime;
16621
16618
  logger33.trace("Retrieval completed", { queryLength: request2.query.length, resultCount: limitedItems.length, duration });
16622
- return ok({
16619
+ return core.ok({
16623
16620
  items: limitedItems,
16624
16621
  query: request2.query,
16625
16622
  duration
16626
16623
  });
16627
16624
  } catch (error) {
16628
16625
  logger33.error("Retrieval failed", { error });
16629
- return err(HaiAIError.RETRIEVAL_FAILED, aiM("ai_internalError", {
16626
+ return core.err(HaiAIError.RETRIEVAL_FAILED, aiM("ai_internalError", {
16630
16627
  params: {
16631
16628
  error: String(error)
16632
16629
  }
@@ -16684,13 +16681,13 @@ ${INCREMENTAL_SUMMARIZE_SUFFIX.replace("{previousSummary}", options.previousSumm
16684
16681
  enablePersist: false
16685
16682
  });
16686
16683
  if (!chatResult.success) {
16687
- return err(HaiAIError.CONTEXT_SUMMARIZE_FAILED, aiM("ai_contextSummarizeFailed", {
16684
+ return core.err(HaiAIError.CONTEXT_SUMMARIZE_FAILED, aiM("ai_contextSummarizeFailed", {
16688
16685
  params: {
16689
16686
  error: String(chatResult.error.message)
16690
16687
  }
16691
16688
  }), chatResult.error);
16692
16689
  }
16693
- return ok(chatResult.data.choices[0]?.message?.content ?? "");
16690
+ return core.ok(chatResult.data.choices[0]?.message?.content ?? "");
16694
16691
  }
16695
16692
  async function summarize(messages, options) {
16696
16693
  logger34.trace("Summarizing messages", { messageCount: messages.length });
@@ -16699,14 +16696,14 @@ ${INCREMENTAL_SUMMARIZE_SUFFIX.replace("{previousSummary}", options.previousSumm
16699
16696
  if (!result.success)
16700
16697
  return result;
16701
16698
  const summary = result.data;
16702
- return ok({
16699
+ return core.ok({
16703
16700
  summary,
16704
16701
  tokenCount: token.estimateText(summary),
16705
16702
  coveredMessages: messages.filter((m) => m.role !== "system").length
16706
16703
  });
16707
16704
  } catch (error) {
16708
16705
  logger34.error("Context summarization failed", { error });
16709
- return err(HaiAIError.CONTEXT_SUMMARIZE_FAILED, aiM("ai_contextSummarizeFailed", {
16706
+ return core.err(HaiAIError.CONTEXT_SUMMARIZE_FAILED, aiM("ai_contextSummarizeFailed", {
16710
16707
  params: {
16711
16708
  error: String(error)
16712
16709
  }
@@ -16910,7 +16907,7 @@ async function createAISubsystems(config, deps) {
16910
16907
  try {
16911
16908
  return await operation();
16912
16909
  } catch {
16913
- return err(
16910
+ return core.err(
16914
16911
  HaiAIError.RESOURCE_OPERATION_FAILED,
16915
16912
  aiM("ai_resourceOperationFailed")
16916
16913
  );
@@ -17054,8 +17051,8 @@ async function createAISubsystems(config, deps) {
17054
17051
  );
17055
17052
  const managedMCPServers = {
17056
17053
  ...mcpServers.operations,
17057
- register: (input) => input?.pool?.maxTotal === void 0 ? mcpServers.operations.register(input) : Promise.resolve(err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"))),
17058
- 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")))
17059
17056
  };
17060
17057
  const mcp = Object.assign(createAIMCPFunctions(), {
17061
17058
  servers: managedMCPServers,
@@ -18505,7 +18502,7 @@ function createMemoryStoreProvider() {
18505
18502
  function createBuiltinToolBroker(options) {
18506
18503
  const lifecycle = new AbortController();
18507
18504
  const serviceId = "hai-local-tools";
18508
- const forbidden = () => err(HaiAIError.MCP_TOOL_FORBIDDEN, aiM("ai_mcpServiceForbidden"));
18505
+ const forbidden = () => core.err(HaiAIError.MCP_TOOL_FORBIDDEN, aiM("ai_mcpServiceForbidden"));
18509
18506
  const created = createMCPServiceBroker(async () => void 0, async () => forbidden(), {
18510
18507
  url: options.url,
18511
18508
  authorize: () => true
@@ -18513,15 +18510,15 @@ function createBuiltinToolBroker(options) {
18513
18510
  id: serviceId,
18514
18511
  async catalog(scope, sessionId, signal) {
18515
18512
  const result = await options.service.catalog({ scope, sessionId, signal });
18516
- return result.success ? ok(result.data.tools) : result;
18513
+ return result.success ? core.ok(result.data.tools) : result;
18517
18514
  },
18518
18515
  async invoke(request2, authorization, idempotencyKey) {
18519
18516
  if (!authorization.taskId)
18520
18517
  return forbidden();
18521
18518
  const result = await options.service.invoke({ name: request2.tool, input: request2.arguments ?? {}, idempotencyKey }, { scope: authorization.principal, sessionId: authorization.taskId, signal: authorization.signal });
18522
18519
  if (!result.success)
18523
- return err(core.error.toPublic(result.error));
18524
- return ok({
18520
+ return core.err(core.error.toPublic(result.error));
18521
+ return core.ok({
18525
18522
  content: [
18526
18523
  {
18527
18524
  type: "text",
@@ -18535,7 +18532,7 @@ function createBuiltinToolBroker(options) {
18535
18532
  if (!created.success)
18536
18533
  return created;
18537
18534
  const broker = created.data;
18538
- return ok({
18535
+ return core.ok({
18539
18536
  async bind(input) {
18540
18537
  const catalog = await options.service.catalog({ scope: input.scope, sessionId: input.sessionId, signal: input.signal });
18541
18538
  if (!catalog.success)
@@ -18665,7 +18662,7 @@ function parameterSchema() {
18665
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));
18666
18663
  }
18667
18664
  function invalid(cause) {
18668
- return err(HaiAIError.INVALID_REQUEST, aiM("ai_toolVideoInvalid"), cause);
18665
+ return core.err(HaiAIError.INVALID_REQUEST, aiM("ai_toolVideoInvalid"), cause);
18669
18666
  }
18670
18667
  function readScreenshots(names, files) {
18671
18668
  let pixels = 0;
@@ -18792,7 +18789,7 @@ function createWebsiteVideoTool(options, dependencies) {
18792
18789
  };
18793
18790
  const stage = async (phase, progress) => {
18794
18791
  if (!context.execution)
18795
- return ok(void 0);
18792
+ return core.ok(void 0);
18796
18793
  return context.execution.emit({ type: "phase", phase, progress });
18797
18794
  };
18798
18795
  const captureStage = await stage("capture", 0.05);
@@ -18840,7 +18837,7 @@ function createWebsiteVideoTool(options, dependencies) {
18840
18837
  const palette = capture.colors.map(color).filter((value) => !!value);
18841
18838
  const accent = input.brandColor ?? palette.find((value) => !/^#(?:000000|ffffff)$/i.test(value)) ?? palette[0];
18842
18839
  if (!accent)
18843
- return err(HaiAIError.INVALID_REQUEST, aiM("ai_toolVideoMissingBrand"));
18840
+ return core.err(HaiAIError.INVALID_REQUEST, aiM("ai_toolVideoMissingBrand"));
18844
18841
  const scriptStage = await stage("script", 0.2);
18845
18842
  if (!scriptStage.success)
18846
18843
  return scriptStage;
@@ -18963,7 +18960,7 @@ Do not execute website scripts, insert remote media, invent claims, or clip narr
18963
18960
  if (!playable.success)
18964
18961
  return playable;
18965
18962
  if (playable.data.format !== "wav")
18966
- return err(HaiAIError.AUDIO_INVALID_REQUEST, aiM("ai_toolVideoWavRequired"));
18963
+ return core.err(HaiAIError.AUDIO_INVALID_REQUEST, aiM("ai_toolVideoWavRequired"));
18967
18964
  bytes = Buffer.from(playable.data.audioBase64, "base64");
18968
18965
  }
18969
18966
  let voiceMs;
@@ -18990,7 +18987,7 @@ Do not execute website scripts, insert remote media, invent claims, or clip narr
18990
18987
  }
18991
18988
  const voiceTotal = narrated.reduce((sum, scene) => sum + scene.voiceMs, 0);
18992
18989
  if (voiceTotal + narrated.length * 100 > input.durationSeconds * 1e3)
18993
- return err(HaiAIError.AUDIO_INVALID_REQUEST, aiM("ai_toolVideoNarrationTooLong"));
18990
+ return core.err(HaiAIError.AUDIO_INVALID_REQUEST, aiM("ai_toolVideoNarrationTooLong"));
18994
18991
  const padding = (input.durationSeconds * 1e3 - voiceTotal) / narrated.length;
18995
18992
  let startMs = 0;
18996
18993
  const scenes = narrated.map((scene) => {
@@ -19080,7 +19077,7 @@ ${scene.narration.replaceAll("-->", "\u2192")}
19080
19077
  const done = await stage("complete", 1);
19081
19078
  if (!done.success)
19082
19079
  return done;
19083
- return ok({ ...manifest, artifacts });
19080
+ return core.ok({ ...manifest, artifacts });
19084
19081
  }
19085
19082
  });
19086
19083
  }
@@ -19127,7 +19124,7 @@ function createBuiltinTools(options, dependencies) {
19127
19124
  if (!read.success)
19128
19125
  return read;
19129
19126
  if (!read.data.mediaType.startsWith("image/"))
19130
- return err(HaiAIError.IMAGE_INVALID_REQUEST, aiM("ai_toolInvalidMedia"));
19127
+ return core.err(HaiAIError.IMAGE_INVALID_REQUEST, aiM("ai_toolInvalidMedia"));
19131
19128
  referenceImages.push({ data: read.data.data, mimeType: read.data.mediaType });
19132
19129
  }
19133
19130
  const generated = await dependencies.image().generate({
@@ -19144,7 +19141,7 @@ function createBuiltinTools(options, dependencies) {
19144
19141
  execution.signal.throwIfAborted();
19145
19142
  const extension = imageExtensions[image2.mimeType];
19146
19143
  if (!extension)
19147
- return err(HaiAIError.IMAGE_INVALID_REQUEST, aiM("ai_toolInvalidMedia"));
19144
+ return core.err(HaiAIError.IMAGE_INVALID_REQUEST, aiM("ai_toolInvalidMedia"));
19148
19145
  const published = await options.files.publish(context, {
19149
19146
  name: `generated-${index + 1}.${extension}`,
19150
19147
  kind: "image",
@@ -19155,7 +19152,7 @@ function createBuiltinTools(options, dependencies) {
19155
19152
  return published;
19156
19153
  artifacts.push(published.data);
19157
19154
  }
19158
- return ok({ artifacts });
19155
+ return core.ok({ artifacts });
19159
19156
  }
19160
19157
  });
19161
19158
  const synthesize = tools.define({
@@ -19197,7 +19194,7 @@ function createBuiltinTools(options, dependencies) {
19197
19194
  });
19198
19195
  if (!published.success)
19199
19196
  return published;
19200
- return ok({
19197
+ return core.ok({
19201
19198
  artifacts: [published.data],
19202
19199
  ...result.data.durationMs === void 0 ? {} : { durationMs: result.data.durationMs }
19203
19200
  });
@@ -19221,7 +19218,7 @@ function createBuiltinTools(options, dependencies) {
19221
19218
  return read;
19222
19219
  const format = audioFormat(read.data.name, read.data.mediaType);
19223
19220
  if (!format)
19224
- return err(HaiAIError.AUDIO_UNSUPPORTED_INPUT, aiM("ai_toolInvalidMedia"));
19221
+ return core.err(HaiAIError.AUDIO_UNSUPPORTED_INPUT, aiM("ai_toolInvalidMedia"));
19225
19222
  const transcribed = await dependencies.audio().transcribe({
19226
19223
  audio: { data: read.data.data, format },
19227
19224
  model: input.model,
@@ -19239,7 +19236,7 @@ function createBuiltinTools(options, dependencies) {
19239
19236
  });
19240
19237
  if (!published.success)
19241
19238
  return published;
19242
- return ok({
19239
+ return core.ok({
19243
19240
  text: transcribed.data.text,
19244
19241
  ...transcribed.data.language ? { language: transcribed.data.language } : {},
19245
19242
  ...transcribed.data.segments ? { segments: transcribed.data.segments } : {},
@@ -19266,18 +19263,18 @@ function createBuiltinTools(options, dependencies) {
19266
19263
  return read;
19267
19264
  const baseVersion = input.baseVersion ?? read.data.version;
19268
19265
  if (baseVersion === void 0 || read.data.version !== baseVersion)
19269
- return err(HaiAIError.RESOURCE_CONFLICT, aiM("ai_toolRewriteConflict"));
19266
+ return core.err(HaiAIError.RESOURCE_CONFLICT, aiM("ai_toolRewriteConflict"));
19270
19267
  if (!["text/markdown", "text/plain"].includes(read.data.mediaType))
19271
- return err(HaiAIError.INVALID_REQUEST, aiM("ai_toolInvalidMedia"));
19268
+ return core.err(HaiAIError.INVALID_REQUEST, aiM("ai_toolInvalidMedia"));
19272
19269
  let draft;
19273
19270
  try {
19274
19271
  draft = input.content ?? new TextDecoder("utf-8", { fatal: true }).decode(read.data.data);
19275
19272
  } catch {
19276
- return err(HaiAIError.INVALID_REQUEST, aiM("ai_toolInvalidMedia"));
19273
+ return core.err(HaiAIError.INVALID_REQUEST, aiM("ai_toolInvalidMedia"));
19277
19274
  }
19278
19275
  const start = input.selectedText === void 0 ? 0 : draft.indexOf(input.selectedText);
19279
19276
  if (start < 0 || input.selectedText !== void 0 && draft.lastIndexOf(input.selectedText) !== start)
19280
- return err(HaiAIError.INVALID_REQUEST, aiM("ai_toolRewriteSelection"));
19277
+ return core.err(HaiAIError.INVALID_REQUEST, aiM("ai_toolRewriteSelection"));
19281
19278
  const target = input.selectedText ?? draft;
19282
19279
  const result = await dependencies.llm().chat({
19283
19280
  model: input.model,
@@ -19295,9 +19292,9 @@ function createBuiltinTools(options, dependencies) {
19295
19292
  return result;
19296
19293
  const replacement = result.data.choices[0]?.message.content;
19297
19294
  if (typeof replacement !== "string" || !replacement.trim())
19298
- return err(HaiAIError.TOOL_RESULT_ERROR, aiM("ai_toolInvalidResult"));
19295
+ return core.err(HaiAIError.TOOL_RESULT_ERROR, aiM("ai_toolInvalidResult"));
19299
19296
  const content = input.selectedText === void 0 ? replacement : `${draft.slice(0, start)}${replacement}${draft.slice(start + target.length)}`;
19300
- return ok({
19297
+ return core.ok({
19301
19298
  id: input.id,
19302
19299
  content,
19303
19300
  baseVersion,
@@ -19355,7 +19352,7 @@ function createMcpTools(options, services) {
19355
19352
  resultHandler: async (input, { signal }) => {
19356
19353
  const args = z.record(z.string(), z.unknown()).safeParse(input);
19357
19354
  if (!args.success)
19358
- return err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
19355
+ return core.err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"));
19359
19356
  const result = await services().invoke({ serviceId: definition.serviceId, tool: definition.tool, arguments: args.data }, {
19360
19357
  principal: options.context.scope,
19361
19358
  taskId: options.context.sessionId,
@@ -19365,12 +19362,12 @@ function createMcpTools(options, services) {
19365
19362
  if (!result.success)
19366
19363
  return result;
19367
19364
  if (result.data.isError)
19368
- return err(HaiAIError.MCP_TOOL_ERROR, aiM("ai_mcpServiceCallFailed"));
19369
- return ok(result.data);
19365
+ return core.err(HaiAIError.MCP_TOOL_ERROR, aiM("ai_mcpServiceCallFailed"));
19366
+ return core.ok(result.data);
19370
19367
  }
19371
19368
  });
19372
19369
  });
19373
- return ok({
19370
+ return core.ok({
19374
19371
  tools: definitions,
19375
19372
  groups: [
19376
19373
  {
@@ -19381,7 +19378,7 @@ function createMcpTools(options, services) {
19381
19378
  ]
19382
19379
  });
19383
19380
  } catch (cause) {
19384
- return err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"), cause);
19381
+ return core.err(HaiAIError.RESOURCE_INVALID, aiM("ai_resourceInvalid"), cause);
19385
19382
  }
19386
19383
  }
19387
19384
 
@@ -19590,10 +19587,30 @@ var streamOperations = {
19590
19587
  encodeSSE
19591
19588
  };
19592
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,
19593
19610
  async init(config, options) {
19594
19611
  if (initInProgress || closingPromise) {
19595
19612
  logger36.warn("AI init already in progress, skipping concurrent call");
19596
- return err(HaiAIError.INIT_IN_PROGRESS, aiM("ai_initInProgress"));
19613
+ return core.err(HaiAIError.INIT_IN_PROGRESS, aiM("ai_initInProgress"));
19597
19614
  }
19598
19615
  initInProgress = true;
19599
19616
  let resolveInit;
@@ -19612,7 +19629,7 @@ var ai = {
19612
19629
  const parseResult = AIConfigSchema.safeParse(config ?? {});
19613
19630
  if (!parseResult.success) {
19614
19631
  logger36.error("AI config validation failed", { error: parseResult.error.message });
19615
- return err(
19632
+ return core.err(
19616
19633
  HaiAIError.CONFIGURATION_ERROR,
19617
19634
  aiM("ai_configError", {
19618
19635
  params: { error: parseResult.error.message }
@@ -19631,7 +19648,7 @@ var ai = {
19631
19648
  logger36.warn("AI is using the ephemeral in-memory store; initialize reldb and vecdb before ai.init() for persistent data");
19632
19649
  }
19633
19650
  if (core.module.requiresSharedState(process2.env) && storeProvider.stateScope !== "shared")
19634
- return err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_sharedBackendRequired"));
19651
+ return core.err(HaiAIError.CONFIGURATION_ERROR, aiM("ai_sharedBackendRequired"));
19635
19652
  currentStoreProvider = storeProvider;
19636
19653
  const subs = await createAISubsystems(parsed, {
19637
19654
  storeProvider,
@@ -19665,7 +19682,7 @@ var ai = {
19665
19682
  currentA2AStores = subs.a2aStores;
19666
19683
  currentConfig = parsed;
19667
19684
  logger36.info("AI module initialized", { model: parsed.llm?.model });
19668
- return ok(void 0);
19685
+ return core.ok(void 0);
19669
19686
  } catch (error) {
19670
19687
  if (!closingPrevious) {
19671
19688
  try {
@@ -19675,7 +19692,7 @@ var ai = {
19675
19692
  }
19676
19693
  }
19677
19694
  logger36.error("AI module initialization failed", { error });
19678
- return err(
19695
+ return core.err(
19679
19696
  HaiAIError.CONFIGURATION_ERROR,
19680
19697
  aiM("ai_initFailed", {
19681
19698
  params: {
@@ -19775,6 +19792,6 @@ var ai = {
19775
19792
  }
19776
19793
  };
19777
19794
 
19778
- export { ai, createMcpServer };
19795
+ export { ai };
19779
19796
  //# sourceMappingURL=index.js.map
19780
19797
  //# sourceMappingURL=index.js.map