nolo-cli 0.1.13 → 0.1.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -2
- package/agent-runtime/hostAdapter.ts +53 -0
- package/agent-runtime/index.ts +28 -0
- package/agent-runtime/localLoop.ts +62 -0
- package/agent-runtime/runtimeDecision.ts +70 -0
- package/agent-runtime/types.ts +87 -0
- package/agentRuntimeCommands.ts +139 -22
- package/agentRuntimeLocal.ts +7 -0
- package/ai/agent/_executeModel.ts +118 -0
- package/ai/agent/agentSlice.ts +544 -1
- package/ai/agent/appWorkingMemory.ts +126 -0
- package/ai/agent/avatarUtils.ts +24 -0
- package/ai/agent/buildEditingContext.ts +373 -0
- package/ai/agent/buildSystemPrompt.ts +532 -0
- package/ai/agent/cleanAgentMessages.ts +140 -0
- package/ai/agent/cliChatClient.ts +119 -0
- package/ai/agent/contextCompiler.ts +107 -0
- package/ai/agent/contextLayerContract.ts +44 -0
- package/ai/agent/createAgentSchema.ts +234 -0
- package/ai/agent/executeToolCall.ts +58 -0
- package/ai/agent/fetchAgentContexts.ts +42 -0
- package/ai/agent/generatePrompt.ts +3 -0
- package/ai/agent/getFullChatContextKeys.ts +168 -0
- package/ai/agent/hooks/fetchPublicAgents.ts +133 -0
- package/ai/agent/hooks/useAgentConfig.ts +61 -0
- package/ai/agent/hooks/useAgentDialog.ts +35 -0
- package/ai/agent/hooks/useAgentFormValidation.ts +202 -0
- package/ai/agent/hooks/usePublicAgents.ts +473 -0
- package/ai/agent/persistMessageWithFixedId.ts +37 -0
- package/ai/agent/planSlice.ts +259 -0
- package/ai/agent/referenceUtils.ts +229 -0
- package/ai/agent/runAgentBackground.ts +238 -0
- package/ai/agent/runAgentClientLoop.ts +138 -0
- package/ai/agent/runtimeGuidance.ts +97 -0
- package/ai/agent/runtimeServerBase.ts +37 -0
- package/ai/agent/server/fetchPublicAgents.ts +128 -0
- package/ai/agent/startParallelAgentStreams.ts +424 -0
- package/ai/agent/startupProtocol.ts +53 -0
- package/ai/agent/streamAgentChatTurn.ts +1299 -0
- package/ai/agent/streamAgentChatTurnUtils.ts +738 -0
- package/ai/agent/types.ts +71 -0
- package/ai/agent/utils/imageOutput.ts +39 -0
- package/ai/agent/utils/publicImageAgentMode.ts +26 -0
- package/ai/agent/utils/sortUtils.ts +250 -0
- package/ai/agent/web/referencePickerUtils.ts +146 -0
- package/ai/ai.locale.ts +1083 -0
- package/ai/chat/accumulateToolCallChunks.ts +95 -0
- package/ai/chat/fetchUtils.native.ts +276 -0
- package/ai/chat/fetchUtils.ts +153 -0
- package/ai/chat/inlineImageUrlsForCustomProvider.ts +117 -0
- package/ai/chat/parseApiError.ts +64 -0
- package/ai/chat/parseMultilineSSE.ts +95 -0
- package/ai/chat/sendOpenAICompletionsRequest.native.ts +682 -0
- package/ai/chat/sendOpenAICompletionsRequest.ts +712 -0
- package/ai/chat/sendOpenAIResponseRequest.ts +512 -0
- package/ai/chat/shouldUseServerProxy.ts +18 -0
- package/ai/chat/sseClient.native.ts +91 -0
- package/ai/chat/sseClient.ts +67 -0
- package/ai/chat/streamReader.native.ts +31 -0
- package/ai/chat/streamReader.ts +62 -0
- package/ai/chat/updateTotalUsage.ts +72 -0
- package/ai/context/buildReferenceContext.ts +437 -0
- package/ai/context/calculateContextUsage.ts +133 -0
- package/ai/context/retention.ts +165 -0
- package/ai/context/tokenUtils.ts +78 -0
- package/ai/index.ts +1 -1
- package/ai/llm/agentCapabilities.ts +74 -0
- package/ai/llm/calculateGeminiImageTokens.ts +57 -0
- package/ai/llm/deepinfra.ts +28 -0
- package/ai/llm/fireworks.ts +68 -0
- package/ai/llm/generateRequestBody.ts +165 -0
- package/ai/llm/getModelContextWindow.ts +84 -0
- package/ai/llm/getNoloKey.ts +37 -0
- package/ai/llm/getPricing.ts +232 -0
- package/ai/llm/hooks/useModelPricing.ts +75 -0
- package/ai/llm/imagePricing.ts +66 -0
- package/ai/llm/isResponseAPIModel.ts +13 -0
- package/ai/llm/kimi.ts +18 -0
- package/ai/llm/mimo.ts +71 -0
- package/ai/llm/mistral.ts +22 -0
- package/ai/llm/modelAvatar.ts +427 -0
- package/ai/llm/models.ts +45 -0
- package/ai/llm/openrouterModels.ts +141 -0
- package/ai/llm/providers.ts +307 -0
- package/ai/llm/reasoningModels.ts +28 -0
- package/ai/llm/types.ts +59 -0
- package/ai/llm/usageRequestOptions.ts +59 -0
- package/ai/memory/capture.ts +148 -0
- package/ai/memory/consolidate.ts +104 -0
- package/ai/memory/delete.ts +147 -0
- package/ai/memory/overlay.ts +84 -0
- package/ai/memory/query.ts +38 -0
- package/ai/memory/queryShared.ts +160 -0
- package/ai/memory/rank.ts +105 -0
- package/ai/memory/recentRelationshipRecap.ts +247 -0
- package/ai/memory/remember.ts +167 -0
- package/ai/memory/runtime.ts +76 -0
- package/ai/memory/store.ts +20 -0
- package/ai/memory/storeShared.ts +76 -0
- package/ai/memory/types.ts +46 -0
- package/ai/memory/understanding.ts +349 -0
- package/ai/memory/understandingGreeting.ts +264 -0
- package/ai/messages/type.ts +20 -0
- package/ai/policy/personalizationDialog.ts +333 -0
- package/ai/policy/runtimePolicy.ts +440 -0
- package/ai/policy/selfUpdateFields.ts +48 -0
- package/ai/policy/types.ts +64 -0
- package/ai/skills/referenceRuntime.ts +274 -0
- package/ai/skills/skillDiagnostics.ts +251 -0
- package/ai/skills/skillDocBuilder.ts +139 -0
- package/ai/skills/skillDocProtocol.ts +434 -0
- package/ai/skills/skillReferenceSummary.ts +63 -0
- package/ai/skills/skillSummaryMarker.ts +26 -0
- package/ai/token/calculatePrice.ts +546 -0
- package/ai/token/db.ts +98 -0
- package/ai/token/externalToolCost.ts +321 -0
- package/ai/token/hooks/useRecords.ts +65 -0
- package/ai/token/missingUsageEstimate.ts +42 -0
- package/ai/token/modelUsageQuery.ts +252 -0
- package/ai/token/normalizeUsage.ts +84 -0
- package/ai/token/openaiImageGenerationUsage.ts +56 -0
- package/ai/token/prepareTokenUsageData.ts +88 -0
- package/ai/token/query.ts +88 -0
- package/ai/token/queryUserTokens.ts +59 -0
- package/ai/token/resolveBillingTarget.ts +52 -0
- package/ai/token/saveTokenRecord.ts +53 -0
- package/ai/token/serverDialogProjection.ts +78 -0
- package/ai/token/serverTokenWriter.ts +143 -0
- package/ai/token/stats.ts +21 -0
- package/ai/token/tokenThunks.ts +24 -0
- package/ai/token/types.ts +93 -0
- package/ai/tools/agent/agentTools.ts +176 -0
- package/ai/tools/agent/agentUpdateShared.ts +311 -0
- package/ai/tools/agent/callAgentTool.ts +139 -0
- package/ai/tools/agent/createAgentTool.ts +512 -0
- package/ai/tools/agent/createDialogTool.ts +69 -0
- package/ai/tools/agent/createSkillAgentTool.ts +62 -0
- package/ai/tools/agent/parallelBudget.ts +221 -0
- package/ai/tools/agent/presets/appBuilderPreset.ts +147 -0
- package/ai/tools/agent/runLlmTool.ts +96 -0
- package/ai/tools/agent/runStreamingAgentTool.ts +73 -0
- package/ai/tools/agent/skillAgentArgs.ts +106 -0
- package/ai/tools/agent/skillAgentPreset.ts +89 -0
- package/ai/tools/agent/streamParallelAgentsTool.ts +122 -0
- package/ai/tools/agent/updateAgentTool.ts +96 -0
- package/ai/tools/agent/updateSelfTool.ts +113 -0
- package/ai/tools/amazonProductScraperTool.ts +86 -0
- package/ai/tools/apifyActorClient.ts +45 -0
- package/ai/tools/appEditGuard.ts +372 -0
- package/ai/tools/appReadSnapshot.ts +153 -0
- package/ai/tools/appTools.ts +1549 -0
- package/ai/tools/applyEditTool.ts +256 -0
- package/ai/tools/applyLineEditsTool.ts +312 -0
- package/ai/tools/browserTools/click.ts +33 -0
- package/ai/tools/browserTools/closeSession.ts +29 -0
- package/ai/tools/browserTools/common.ts +27 -0
- package/ai/tools/browserTools/openSession.ts +48 -0
- package/ai/tools/browserTools/readContent.ts +38 -0
- package/ai/tools/browserTools/selectOption.ts +46 -0
- package/ai/tools/browserTools/typeText.ts +42 -0
- package/ai/tools/category/createCategoryTool.ts +66 -0
- package/ai/tools/category/queryContentsByCategoryTool.ts +69 -0
- package/ai/tools/category/updateContentCategoryTool.ts +75 -0
- package/ai/tools/cfBrowserTools.ts +319 -0
- package/ai/tools/cfSpeechToTextTool.ts +49 -0
- package/ai/tools/checkEnvTool.ts +65 -0
- package/ai/tools/cloudflareCrawlTool.ts +289 -0
- package/ai/tools/codeSearchTool.ts +111 -0
- package/ai/tools/codeTools.ts +101 -0
- package/ai/tools/createDocTool.ts +132 -0
- package/ai/tools/createPlanTool.ts +999 -0
- package/ai/tools/createSkillDocTool.ts +155 -0
- package/ai/tools/createWorkflowTool.ts +154 -0
- package/ai/tools/deepseekOcrTool.ts +34 -0
- package/ai/tools/delayTool.ts +31 -0
- package/ai/tools/deleteSpacesTool.ts +325 -0
- package/ai/tools/deleteSpacesToolModel.ts +159 -0
- package/ai/tools/devReloadUtils.ts +29 -0
- package/ai/tools/dialogMessageSearch.ts +137 -0
- package/ai/tools/doctorSkillTool.ts +72 -0
- package/ai/tools/ecommerceScraperTool.ts +86 -0
- package/ai/tools/emailTools.ts +549 -0
- package/ai/tools/evalSkillTool.ts +92 -0
- package/ai/tools/exaSearchTool.ts +64 -0
- package/ai/tools/execBashTool.ts +379 -0
- package/ai/tools/executeSqlTool.ts +192 -0
- package/ai/tools/fetchWebpageSupport.ts +309 -0
- package/ai/tools/fetchWebpageTool.ts +84 -0
- package/ai/tools/geminiImagePreviewTool.ts +361 -0
- package/ai/tools/generateDocxTool.ts +215 -0
- package/ai/tools/googleSearchScraperTool.ts +106 -0
- package/ai/tools/importDataTool.ts +133 -0
- package/ai/tools/importSkillTool.ts +162 -0
- package/ai/tools/index.ts +1927 -0
- package/ai/tools/listFilesTool.ts +82 -0
- package/ai/tools/listUserSpacesTool.ts +113 -0
- package/ai/tools/modelUsageTools.ts +199 -0
- package/ai/tools/olmOcrTool.ts +34 -0
- package/ai/tools/openaiImageTool.ts +267 -0
- package/ai/tools/prepareTools.ts +23 -0
- package/ai/tools/readDocTool.ts +84 -0
- package/ai/tools/readFileTool.ts +211 -0
- package/ai/tools/readTool.ts +163 -0
- package/ai/tools/readXPostTool.ts +233 -0
- package/ai/tools/rememberMemoryTool.ts +84 -0
- package/ai/tools/remotionVideoTool.ts +151 -0
- package/ai/tools/searchDialogMessagesTool.ts +222 -0
- package/ai/tools/searchRepoTool.ts +115 -0
- package/ai/tools/searchWorkspaceTool.ts +259 -0
- package/ai/tools/skillFollowup.ts +86 -0
- package/ai/tools/surfWeatherTool.ts +169 -0
- package/ai/tools/table/addTableRowTool.ts +217 -0
- package/ai/tools/table/createTableTool.ts +315 -0
- package/ai/tools/table/rowTools.ts +366 -0
- package/ai/tools/table/schemaTools.ts +244 -0
- package/ai/tools/table/shareTableTool.ts +148 -0
- package/ai/tools/table/toolShared.ts +129 -0
- package/ai/tools/toolApiClient.ts +198 -0
- package/ai/tools/toolNameAliases.ts +57 -0
- package/ai/tools/toolResultError.ts +42 -0
- package/ai/tools/toolRunSlice.ts +303 -0
- package/ai/tools/toolSchemaCompatibility.ts +53 -0
- package/ai/tools/toolVisibility.ts +4 -0
- package/ai/tools/types.ts +20 -0
- package/ai/tools/uiAskChoiceTool.ts +104 -0
- package/ai/tools/updateContentTitleTool.ts +84 -0
- package/ai/tools/updateDocTool.ts +105 -0
- package/ai/tools/updateUserPreferenceProfileTool.ts +145 -0
- package/ai/tools/whisperTool.ts +77 -0
- package/ai/tools/writeFileTool.ts +210 -0
- package/ai/tools/youtubeScraperTool.ts +116 -0
- package/ai/tools/ziweiChartTool.ts +678 -0
- package/ai/types.ts +55 -0
- package/ai/workflow/workflowExecutor.ts +323 -0
- package/ai/workflow/workflowSlice.ts +73 -0
- package/ai/workflow/workflowTypes.ts +106 -0
- package/client/agentRun.test.ts +240 -0
- package/client/agentRun.ts +182 -19
- package/client/compactDialog.test.ts +238 -0
- package/client/localRuntimeAdapter.test.ts +135 -0
- package/client/localRuntimeAdapter.ts +244 -0
- package/client/profileConfig.test.ts +40 -0
- package/client/streamingOutput.test.ts +22 -0
- package/client/streamingOutput.ts +38 -0
- package/commandRegistry.ts +9 -2
- package/connector-experimental/index.ts +5 -0
- package/database/actions/cacheMergedUserData.ts +64 -0
- package/database/actions/common.ts +242 -0
- package/database/actions/deleteFile.ts +40 -0
- package/database/actions/fetchUserData.ts +16 -0
- package/database/actions/fileContent.ts +125 -0
- package/database/actions/patch.ts +155 -0
- package/database/actions/read.ts +337 -0
- package/database/actions/readAndWait.ts +224 -0
- package/database/actions/readRequestManager.ts +120 -0
- package/database/actions/remove.ts +94 -0
- package/database/actions/replication.ts +366 -0
- package/database/actions/upload.ts +174 -0
- package/database/actions/upsert.ts +56 -0
- package/database/actions/write.ts +126 -0
- package/database/client/db.native.ts +73 -0
- package/database/client/db.ts +51 -0
- package/database/client/fetchUserData.ts +61 -0
- package/database/client/handleError.ts +19 -0
- package/database/client/queryRequest.ts +21 -0
- package/database/config.ts +21 -0
- package/database/dbActionThunks.ts +1 -0
- package/database/dbSlice.ts +149 -0
- package/database/email.ts +42 -0
- package/database/fileRing.ts +51 -0
- package/database/fileSharding.ts +70 -0
- package/database/fileStorage.native.ts +92 -0
- package/database/fileStorage.ts +232 -0
- package/database/fileUrl.ts +34 -0
- package/database/hooks/useUserData.ts +489 -0
- package/database/index.ts +1 -0
- package/database/keys.ts +765 -0
- package/database/queryPrefixes.ts +14 -0
- package/database/requests.ts +443 -0
- package/database/runtimeServerContext.ts +35 -0
- package/database/server/MemoryDB.ts +76 -0
- package/database/server/actorAccess.ts +76 -0
- package/database/server/agentDelegation.ts +124 -0
- package/database/server/coreDataOwnership.ts +13 -0
- package/database/server/coreDataProxy.ts +76 -0
- package/database/server/cybotReadonly.ts +18 -0
- package/database/server/dataHandlers.ts +111 -0
- package/database/server/db.ts +118 -0
- package/database/server/dbPath.ts +20 -0
- package/database/server/delete.ts +499 -0
- package/database/server/emailRepository.ts +1480 -0
- package/database/server/ensureDbOpen.ts +12 -0
- package/database/server/fileRead.ts +337 -0
- package/database/server/fileService.ts +436 -0
- package/database/server/handleTransaction.ts +86 -0
- package/database/server/patch.ts +282 -0
- package/database/server/query.ts +138 -0
- package/database/server/read.ts +325 -0
- package/database/server/resourceAccess.ts +211 -0
- package/database/server/routes.ts +110 -0
- package/database/server/spaceMemberAuthority.ts +67 -0
- package/database/server/upload.ts +159 -0
- package/database/server/write.ts +494 -0
- package/database/server/writeAuthority.ts +133 -0
- package/database/sqliteDb.ts +46 -0
- package/database/table/deleteTable.ts +120 -0
- package/database/tenantPlacement.ts +57 -0
- package/database/tombstones.ts +52 -0
- package/database/userDataLoadDecision.ts +17 -0
- package/database/userDataMerge.ts +95 -0
- package/database/userPreferenceRegister.ts +108 -0
- package/database/utils/dbPath.ts +47 -0
- package/database/utils/ulid.native.ts +6 -0
- package/database/utils/ulid.ts +1 -0
- package/index.ts +25 -15
- package/localRuntimeDb.ts +28 -0
- package/package.json +16 -4
- package/runtimeModeArgs.ts +33 -0
- package/tui/readlineWorkspace.ts +1 -0
- package/tui/session.ts +22 -0
|
@@ -0,0 +1,512 @@
|
|
|
1
|
+
import {
|
|
2
|
+
addActiveController,
|
|
3
|
+
removeActiveController,
|
|
4
|
+
tokenUsageLiveUpdate,
|
|
5
|
+
} from "chat/dialog/dialogSlice";
|
|
6
|
+
import {
|
|
7
|
+
messageStreaming,
|
|
8
|
+
messageStreamEnd,
|
|
9
|
+
} from "chat/messages/messageSlice";
|
|
10
|
+
import { handleToolCalls } from "chat/messages/toolThunks";
|
|
11
|
+
import type { Message } from "chat/messages/types";
|
|
12
|
+
import { selectRuntimeCurrentServer } from "app/stateViews/runtime";
|
|
13
|
+
import { selectCurrentSpaceId } from "create/space/spaceSlice";
|
|
14
|
+
import { getApiEndpoint } from "ai/llm/providers";
|
|
15
|
+
import { createDialogMessageKeyAndId } from "database/keys";
|
|
16
|
+
import { selectCurrentToken } from "auth/authSlice";
|
|
17
|
+
import { extractCustomId } from "core/prefix";
|
|
18
|
+
import type { RootState } from "app/store";
|
|
19
|
+
import { performFetchRequest } from "./fetchUtils";
|
|
20
|
+
import { createSSEParser } from "./parseMultilineSSE";
|
|
21
|
+
import { parseApiError } from "./parseApiError";
|
|
22
|
+
import { updateTotalUsage } from "./updateTotalUsage";
|
|
23
|
+
import type { CompletionMeta } from "./sendOpenAICompletionsRequest";
|
|
24
|
+
import { prepareTools } from "../tools/prepareTools";
|
|
25
|
+
import {
|
|
26
|
+
extractImagePartsFromResponseOutput,
|
|
27
|
+
extractTextFromResponseOutput,
|
|
28
|
+
toResponsesTools,
|
|
29
|
+
type AssistantToolCall,
|
|
30
|
+
} from "integrations/openai/responsesHelpers";
|
|
31
|
+
import { getModelInfo } from "ai/llm/getModelContextWindow";
|
|
32
|
+
import {
|
|
33
|
+
getPublicImageAgentDefaultProfile,
|
|
34
|
+
getPublicImageAgentMode,
|
|
35
|
+
} from "ai/agent/utils/publicImageAgentMode";
|
|
36
|
+
|
|
37
|
+
type Segment = { type: "text"; text: string };
|
|
38
|
+
const seg = (txt: string): Segment[] => [{ type: "text", text: txt ?? "" }];
|
|
39
|
+
|
|
40
|
+
const shouldEnableBuiltInImageGeneration = (agentConfig: any): boolean =>
|
|
41
|
+
String(agentConfig?.provider || "").toLowerCase() === "openai" &&
|
|
42
|
+
!getModelInfo(String(agentConfig?.model || ""))?.hasImageOutput &&
|
|
43
|
+
!!agentConfig?.imageConfig?.enabled;
|
|
44
|
+
|
|
45
|
+
type StreamState = {
|
|
46
|
+
content: string;
|
|
47
|
+
contentBuffer: Array<
|
|
48
|
+
{ type: "text"; text: string } | { type: "image_url"; image_url: { url: string } }
|
|
49
|
+
>;
|
|
50
|
+
reasoning: string;
|
|
51
|
+
usage: any | null;
|
|
52
|
+
assistantToolCalls: AssistantToolCall[];
|
|
53
|
+
completedResponse: any | null;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const safeCancel = async (
|
|
57
|
+
reader?: ReadableStreamDefaultReader<Uint8Array>
|
|
58
|
+
): Promise<void> => {
|
|
59
|
+
if (!reader) return;
|
|
60
|
+
try {
|
|
61
|
+
await reader.cancel();
|
|
62
|
+
} catch {
|
|
63
|
+
/* noop */
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const ensureToolCall = (
|
|
68
|
+
state: StreamState,
|
|
69
|
+
key: string,
|
|
70
|
+
partial: Partial<AssistantToolCall>
|
|
71
|
+
) => {
|
|
72
|
+
let toolCall = state.assistantToolCalls.find((call) => call.id === key);
|
|
73
|
+
if (!toolCall) {
|
|
74
|
+
toolCall = {
|
|
75
|
+
id: key,
|
|
76
|
+
type: "function",
|
|
77
|
+
function: { name: "", arguments: "" },
|
|
78
|
+
};
|
|
79
|
+
state.assistantToolCalls.push(toolCall);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (partial.id) toolCall.id = partial.id;
|
|
83
|
+
if (partial.function?.name) toolCall.function.name = partial.function.name;
|
|
84
|
+
if (typeof partial.function?.arguments === "string") {
|
|
85
|
+
toolCall.function.arguments = partial.function.arguments;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return toolCall;
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
const extractTextFromOutputItem = (item: any): string => {
|
|
92
|
+
if (item?.type !== "message" || !Array.isArray(item.content)) return "";
|
|
93
|
+
return item.content
|
|
94
|
+
.filter(
|
|
95
|
+
(content: any) =>
|
|
96
|
+
content?.type === "output_text" && typeof content.text === "string"
|
|
97
|
+
)
|
|
98
|
+
.map((content: any) => content.text)
|
|
99
|
+
.join("");
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
const getStreamErrorMessage = (event: any): string => {
|
|
103
|
+
const directMessage =
|
|
104
|
+
typeof event?.message === "string" && event.message.trim()
|
|
105
|
+
? event.message.trim()
|
|
106
|
+
: null;
|
|
107
|
+
if (directMessage) return directMessage;
|
|
108
|
+
|
|
109
|
+
const nestedMessage =
|
|
110
|
+
typeof event?.error?.message === "string" && event.error.message.trim()
|
|
111
|
+
? event.error.message.trim()
|
|
112
|
+
: typeof event?.error?.msg === "string" && event.error.msg.trim()
|
|
113
|
+
? event.error.msg.trim()
|
|
114
|
+
: null;
|
|
115
|
+
if (nestedMessage) return nestedMessage;
|
|
116
|
+
|
|
117
|
+
const nestedCode =
|
|
118
|
+
typeof event?.error?.code === "string" && event.error.code.trim()
|
|
119
|
+
? event.error.code.trim()
|
|
120
|
+
: typeof event?.code === "string" && event.code.trim()
|
|
121
|
+
? event.code.trim()
|
|
122
|
+
: null;
|
|
123
|
+
if (nestedCode) return nestedCode;
|
|
124
|
+
|
|
125
|
+
const nestedType =
|
|
126
|
+
typeof event?.error?.type === "string" && event.error.type.trim()
|
|
127
|
+
? event.error.type.trim()
|
|
128
|
+
: typeof event?.type === "string" && event.type.trim() && event.type !== "error"
|
|
129
|
+
? event.type.trim()
|
|
130
|
+
: null;
|
|
131
|
+
if (nestedType) return nestedType;
|
|
132
|
+
|
|
133
|
+
return "Unknown error";
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
export const sendOpenAIResponseRequest = async ({
|
|
137
|
+
bodyData,
|
|
138
|
+
agentConfig,
|
|
139
|
+
thunkApi,
|
|
140
|
+
dialogKey,
|
|
141
|
+
parentMessageId,
|
|
142
|
+
messageMetadata,
|
|
143
|
+
}: {
|
|
144
|
+
bodyData: any;
|
|
145
|
+
agentConfig: any;
|
|
146
|
+
thunkApi: any;
|
|
147
|
+
dialogKey: string;
|
|
148
|
+
parentMessageId?: string;
|
|
149
|
+
messageMetadata?: Partial<Message>;
|
|
150
|
+
}): Promise<CompletionMeta> => {
|
|
151
|
+
const { dispatch, getState, signal: thunkSignal } = thunkApi;
|
|
152
|
+
const dialogId = extractCustomId(dialogKey);
|
|
153
|
+
const controller = new AbortController();
|
|
154
|
+
thunkSignal.addEventListener("abort", () => controller.abort());
|
|
155
|
+
const signal = controller.signal;
|
|
156
|
+
const streamSpaceId = selectCurrentSpaceId(getState() as RootState) || undefined;
|
|
157
|
+
|
|
158
|
+
let messageId: string;
|
|
159
|
+
let msgKey: string;
|
|
160
|
+
if (parentMessageId) {
|
|
161
|
+
messageId = parentMessageId;
|
|
162
|
+
msgKey = `msg:${dialogId}:${messageId}`;
|
|
163
|
+
} else {
|
|
164
|
+
const newIds = createDialogMessageKeyAndId(dialogId);
|
|
165
|
+
messageId = newIds.messageId;
|
|
166
|
+
msgKey = newIds.key;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
dispatch(addActiveController({ messageId, controller, dialogKey }));
|
|
170
|
+
|
|
171
|
+
const state: StreamState = {
|
|
172
|
+
content: "",
|
|
173
|
+
contentBuffer: [],
|
|
174
|
+
reasoning: "",
|
|
175
|
+
usage: null,
|
|
176
|
+
assistantToolCalls: [],
|
|
177
|
+
completedResponse: null,
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
const buildMeta = (
|
|
181
|
+
hasPendingInteraction = false,
|
|
182
|
+
hasHandedOff = false,
|
|
183
|
+
finishReason: string | null = null
|
|
184
|
+
): CompletionMeta => ({
|
|
185
|
+
hasToolCalls: state.assistantToolCalls.length > 0,
|
|
186
|
+
hasPendingInteraction,
|
|
187
|
+
hasHandedOff,
|
|
188
|
+
finishReason,
|
|
189
|
+
messageId,
|
|
190
|
+
usage: state.usage ?? undefined,
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
const flush = () =>
|
|
194
|
+
dispatch(
|
|
195
|
+
messageStreaming({
|
|
196
|
+
id: messageId,
|
|
197
|
+
dialogId,
|
|
198
|
+
dbKey: msgKey,
|
|
199
|
+
content: state.contentBuffer,
|
|
200
|
+
thinkContent: state.reasoning,
|
|
201
|
+
role: "assistant",
|
|
202
|
+
agentKey: agentConfig.dbKey,
|
|
203
|
+
cybotKey: agentConfig.dbKey,
|
|
204
|
+
...(typeof agentConfig?.name === "string" && agentConfig.name.trim()
|
|
205
|
+
? { agentName: agentConfig.name.trim() }
|
|
206
|
+
: {}),
|
|
207
|
+
...(messageMetadata ?? {}),
|
|
208
|
+
})
|
|
209
|
+
);
|
|
210
|
+
|
|
211
|
+
const finalize = async () => {
|
|
212
|
+
if (!state.content) {
|
|
213
|
+
const completedText = extractTextFromResponseOutput(state.completedResponse);
|
|
214
|
+
if (completedText) {
|
|
215
|
+
state.content = completedText;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const completedImages = extractImagePartsFromResponseOutput(state.completedResponse);
|
|
220
|
+
if (state.contentBuffer.length === 0) {
|
|
221
|
+
state.contentBuffer = [
|
|
222
|
+
...(state.content ? seg(state.content) : []),
|
|
223
|
+
...completedImages,
|
|
224
|
+
];
|
|
225
|
+
} else if (
|
|
226
|
+
completedImages.length > 0 &&
|
|
227
|
+
!state.contentBuffer.some((part) => part.type === "image_url")
|
|
228
|
+
) {
|
|
229
|
+
state.contentBuffer = [...state.contentBuffer, ...completedImages];
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
if (state.contentBuffer.length === 0 && state.content) {
|
|
233
|
+
state.contentBuffer = seg(state.content);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
flush();
|
|
237
|
+
await dispatch(
|
|
238
|
+
messageStreamEnd({
|
|
239
|
+
finalContentBuffer: state.contentBuffer,
|
|
240
|
+
totalUsage: state.usage,
|
|
241
|
+
msgKey,
|
|
242
|
+
agentConfig,
|
|
243
|
+
dialogId,
|
|
244
|
+
dialogKey,
|
|
245
|
+
messageId,
|
|
246
|
+
reasoningBuffer: state.reasoning,
|
|
247
|
+
messageMetadata,
|
|
248
|
+
toolCalls: state.assistantToolCalls,
|
|
249
|
+
spaceId: streamSpaceId,
|
|
250
|
+
})
|
|
251
|
+
);
|
|
252
|
+
};
|
|
253
|
+
|
|
254
|
+
const processToolCalls = async () => {
|
|
255
|
+
if (!state.assistantToolCalls.length) {
|
|
256
|
+
await finalize();
|
|
257
|
+
return buildMeta(false, false, null);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
if (state.usage) {
|
|
261
|
+
dispatch(
|
|
262
|
+
tokenUsageLiveUpdate({
|
|
263
|
+
input_tokens: state.usage.prompt_tokens ?? state.usage.input_tokens,
|
|
264
|
+
output_tokens:
|
|
265
|
+
state.usage.completion_tokens ?? state.usage.output_tokens,
|
|
266
|
+
cost: state.usage.cost,
|
|
267
|
+
dialogKey,
|
|
268
|
+
})
|
|
269
|
+
);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
const result = await dispatch(
|
|
273
|
+
handleToolCalls({
|
|
274
|
+
accumulatedCalls: state.assistantToolCalls,
|
|
275
|
+
currentContentBuffer: state.contentBuffer,
|
|
276
|
+
agentConfig,
|
|
277
|
+
messageId,
|
|
278
|
+
dialogId,
|
|
279
|
+
dialogKey,
|
|
280
|
+
parallelSessionId: messageMetadata?.parallelSessionId,
|
|
281
|
+
parallelBranchId: messageMetadata?.parallelBranchId,
|
|
282
|
+
parallelLabel: messageMetadata?.parallelLabel,
|
|
283
|
+
parallelIndex: messageMetadata?.parallelIndex,
|
|
284
|
+
})
|
|
285
|
+
).unwrap();
|
|
286
|
+
|
|
287
|
+
state.content = Array.isArray(result.finalContentBuffer)
|
|
288
|
+
? result.finalContentBuffer
|
|
289
|
+
.filter((part: any) => part?.type === "text")
|
|
290
|
+
.map((part: any) => part.text ?? "")
|
|
291
|
+
.join("")
|
|
292
|
+
: state.content;
|
|
293
|
+
state.contentBuffer = Array.isArray(result.finalContentBuffer)
|
|
294
|
+
? result.finalContentBuffer
|
|
295
|
+
: state.contentBuffer;
|
|
296
|
+
|
|
297
|
+
await finalize();
|
|
298
|
+
return buildMeta(result.hasPendingInteraction, result.hasHandedOff, null);
|
|
299
|
+
};
|
|
300
|
+
|
|
301
|
+
let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
|
|
302
|
+
|
|
303
|
+
try {
|
|
304
|
+
if (!parentMessageId) {
|
|
305
|
+
dispatch(
|
|
306
|
+
messageStreaming({
|
|
307
|
+
id: messageId,
|
|
308
|
+
dialogId,
|
|
309
|
+
dbKey: msgKey,
|
|
310
|
+
content: "",
|
|
311
|
+
role: "assistant",
|
|
312
|
+
agentKey: agentConfig.dbKey,
|
|
313
|
+
cybotKey: agentConfig.dbKey,
|
|
314
|
+
...(typeof agentConfig?.name === "string" && agentConfig.name.trim()
|
|
315
|
+
? { agentName: agentConfig.name.trim() }
|
|
316
|
+
: {}),
|
|
317
|
+
...(messageMetadata ?? {}),
|
|
318
|
+
isStreaming: true,
|
|
319
|
+
})
|
|
320
|
+
);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
const functionTools = getModelInfo(agentConfig.model)?.hasImageOutput
|
|
324
|
+
? []
|
|
325
|
+
: prepareTools(agentConfig.tools ?? [], { provider: agentConfig.provider });
|
|
326
|
+
|
|
327
|
+
const imageMode = getPublicImageAgentMode(agentConfig);
|
|
328
|
+
const imageProfile =
|
|
329
|
+
imageMode === "continuous"
|
|
330
|
+
? getPublicImageAgentDefaultProfile("continuous")
|
|
331
|
+
: null;
|
|
332
|
+
|
|
333
|
+
const tools = [
|
|
334
|
+
...(toResponsesTools(functionTools) ?? []),
|
|
335
|
+
...(shouldEnableBuiltInImageGeneration(agentConfig)
|
|
336
|
+
? [{ type: "image_generation" as const }]
|
|
337
|
+
: []),
|
|
338
|
+
...(imageMode === "continuous"
|
|
339
|
+
? [
|
|
340
|
+
{
|
|
341
|
+
type: "image_generation" as const,
|
|
342
|
+
action: "auto" as const,
|
|
343
|
+
quality: imageProfile?.quality,
|
|
344
|
+
output_format: imageProfile?.outputFormat,
|
|
345
|
+
},
|
|
346
|
+
]
|
|
347
|
+
: []),
|
|
348
|
+
];
|
|
349
|
+
const requestBody = {
|
|
350
|
+
...bodyData,
|
|
351
|
+
...(tools.length ? { tools, tool_choice: bodyData.tool_choice ?? "auto" } : {}),
|
|
352
|
+
stream: true,
|
|
353
|
+
};
|
|
354
|
+
|
|
355
|
+
const api = getApiEndpoint(agentConfig);
|
|
356
|
+
const token = selectCurrentToken(getState() as RootState);
|
|
357
|
+
const response = await performFetchRequest({
|
|
358
|
+
agentConfig,
|
|
359
|
+
api,
|
|
360
|
+
bodyData: requestBody,
|
|
361
|
+
currentServer: selectRuntimeCurrentServer(getState() as RootState),
|
|
362
|
+
signal,
|
|
363
|
+
token,
|
|
364
|
+
});
|
|
365
|
+
|
|
366
|
+
if (!response.ok) {
|
|
367
|
+
const errorMessage = await parseApiError(response);
|
|
368
|
+
state.content = `[错误: ${errorMessage}]`;
|
|
369
|
+
await finalize();
|
|
370
|
+
return buildMeta();
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
reader = response.body?.getReader();
|
|
374
|
+
if (!reader) {
|
|
375
|
+
await finalize();
|
|
376
|
+
return buildMeta();
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const parseSSE = createSSEParser();
|
|
380
|
+
const decoder = new TextDecoder();
|
|
381
|
+
let finishReason: string | null = null;
|
|
382
|
+
|
|
383
|
+
while (true) {
|
|
384
|
+
const { done, value } = await reader.read();
|
|
385
|
+
if (done) break;
|
|
386
|
+
|
|
387
|
+
const chunk = decoder.decode(value, { stream: true });
|
|
388
|
+
const events = parseSSE(chunk);
|
|
389
|
+
const eventList = Array.isArray(events) ? events : [events];
|
|
390
|
+
|
|
391
|
+
for (const event of eventList) {
|
|
392
|
+
if (event?.usage) {
|
|
393
|
+
state.usage = updateTotalUsage(state.usage, event.usage);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
if (event?.type === "error" || event?.error) {
|
|
397
|
+
state.content += `\n[Error: ${getStreamErrorMessage(event)}]`;
|
|
398
|
+
await finalize();
|
|
399
|
+
return buildMeta();
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
switch (event?.type) {
|
|
403
|
+
case "response.output_text.delta":
|
|
404
|
+
if (event.delta) {
|
|
405
|
+
state.content += event.delta;
|
|
406
|
+
state.contentBuffer = seg(state.content);
|
|
407
|
+
flush();
|
|
408
|
+
}
|
|
409
|
+
break;
|
|
410
|
+
case "response.reasoning.delta":
|
|
411
|
+
if (event.delta?.text) {
|
|
412
|
+
state.reasoning += event.delta.text;
|
|
413
|
+
flush();
|
|
414
|
+
}
|
|
415
|
+
break;
|
|
416
|
+
case "response.reasoning.done":
|
|
417
|
+
if (event.text) {
|
|
418
|
+
state.reasoning += event.text;
|
|
419
|
+
flush();
|
|
420
|
+
}
|
|
421
|
+
break;
|
|
422
|
+
case "response.output_item.added":
|
|
423
|
+
case "response.output_item.done": {
|
|
424
|
+
const item = event.item;
|
|
425
|
+
if (!state.content) {
|
|
426
|
+
const itemText = extractTextFromOutputItem(item);
|
|
427
|
+
if (itemText) {
|
|
428
|
+
state.content = itemText;
|
|
429
|
+
state.contentBuffer = seg(state.content);
|
|
430
|
+
flush();
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
if (item?.type === "function_call") {
|
|
434
|
+
ensureToolCall(state, item.call_id || item.id, {
|
|
435
|
+
id: item.call_id || item.id,
|
|
436
|
+
function: {
|
|
437
|
+
name: item.name || "",
|
|
438
|
+
arguments:
|
|
439
|
+
typeof item.arguments === "string" ? item.arguments : "",
|
|
440
|
+
},
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
break;
|
|
444
|
+
}
|
|
445
|
+
case "response.function_call_arguments.delta": {
|
|
446
|
+
const key = event.call_id || event.item_id || `${event.output_index ?? 0}`;
|
|
447
|
+
const toolCall = ensureToolCall(state, key, {
|
|
448
|
+
id: event.call_id || key,
|
|
449
|
+
function: { name: event.name || "", arguments: "" },
|
|
450
|
+
});
|
|
451
|
+
toolCall.function.arguments += event.delta ?? "";
|
|
452
|
+
break;
|
|
453
|
+
}
|
|
454
|
+
case "response.function_call_arguments.done": {
|
|
455
|
+
const key = event.call_id || event.item_id || `${event.output_index ?? 0}`;
|
|
456
|
+
ensureToolCall(state, key, {
|
|
457
|
+
id: event.call_id || key,
|
|
458
|
+
function: {
|
|
459
|
+
name: event.name || "",
|
|
460
|
+
arguments:
|
|
461
|
+
typeof event.arguments === "string"
|
|
462
|
+
? event.arguments
|
|
463
|
+
: typeof event.output?.arguments === "string"
|
|
464
|
+
? event.output.arguments
|
|
465
|
+
: "",
|
|
466
|
+
},
|
|
467
|
+
});
|
|
468
|
+
break;
|
|
469
|
+
}
|
|
470
|
+
case "response.completed":
|
|
471
|
+
state.completedResponse = event.response ?? null;
|
|
472
|
+
finishReason =
|
|
473
|
+
event.response?.status === "completed"
|
|
474
|
+
? "stop"
|
|
475
|
+
: event.response?.status ?? null;
|
|
476
|
+
if (event.response?.usage) {
|
|
477
|
+
state.usage = updateTotalUsage(state.usage, event.response.usage);
|
|
478
|
+
}
|
|
479
|
+
break;
|
|
480
|
+
case "response.failed":
|
|
481
|
+
state.content += `\n[API Failed: ${event.response?.error?.message || "unknown"}]`;
|
|
482
|
+
finishReason = "error";
|
|
483
|
+
await finalize();
|
|
484
|
+
return buildMeta(false, false, finishReason);
|
|
485
|
+
case "response.incomplete":
|
|
486
|
+
state.content += `\n[Incomplete: ${event.response?.incomplete_details?.reason || "unknown"}]`;
|
|
487
|
+
finishReason = "incomplete";
|
|
488
|
+
await finalize();
|
|
489
|
+
return buildMeta(false, false, finishReason);
|
|
490
|
+
default:
|
|
491
|
+
break;
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
const meta = await processToolCalls();
|
|
497
|
+
return {
|
|
498
|
+
...meta,
|
|
499
|
+
finishReason: meta.finishReason ?? finishReason,
|
|
500
|
+
};
|
|
501
|
+
} catch (error: any) {
|
|
502
|
+
state.content +=
|
|
503
|
+
error?.name === "AbortError"
|
|
504
|
+
? "[用户中断]"
|
|
505
|
+
: `[异常: ${error?.message || "unknown"}]`;
|
|
506
|
+
await finalize();
|
|
507
|
+
return buildMeta(false, false, "error");
|
|
508
|
+
} finally {
|
|
509
|
+
dispatch(removeActiveController({ messageId, dialogKey }));
|
|
510
|
+
await safeCancel(reader);
|
|
511
|
+
}
|
|
512
|
+
};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Agent } from "app/types";
|
|
2
|
+
|
|
3
|
+
export const shouldUseServerProxy = (
|
|
4
|
+
agentConfig: Pick<Agent, "provider" | "useServerProxy">,
|
|
5
|
+
requestProvider?: string
|
|
6
|
+
): boolean => {
|
|
7
|
+
const effectiveProvider = (requestProvider || agentConfig.provider || "").toLowerCase();
|
|
8
|
+
|
|
9
|
+
// Google requests are forced through the server proxy for now because the
|
|
10
|
+
// native Gemini image bridge, provider fallback, and request translation live
|
|
11
|
+
// on the server. Keep this centralized so we can later add direct/custom-url
|
|
12
|
+
// opt-out for user-managed keys without having to update web/native twice.
|
|
13
|
+
if (effectiveProvider === "google") {
|
|
14
|
+
return true;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
return !!agentConfig.useServerProxy;
|
|
18
|
+
};
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// 文件路径: ai/chat/sseClient.native.ts
|
|
2
|
+
// React Native 版 SSE 客户端实现 - 使用 react-native-sse
|
|
3
|
+
|
|
4
|
+
import EventSource from 'react-native-sse';
|
|
5
|
+
|
|
6
|
+
export interface SSEClientOptions {
|
|
7
|
+
url: string;
|
|
8
|
+
method: 'POST';
|
|
9
|
+
headers: Record<string, string>;
|
|
10
|
+
body: string;
|
|
11
|
+
signal?: AbortSignal;
|
|
12
|
+
onMessage: (data: string) => void;
|
|
13
|
+
onError: (error: Error) => void;
|
|
14
|
+
onComplete: () => void;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* React Native 版 SSE 客户端
|
|
19
|
+
* 使用 react-native-sse 库实现
|
|
20
|
+
*/
|
|
21
|
+
export async function createSSEClient(options: SSEClientOptions): Promise<void> {
|
|
22
|
+
const { url, method, headers, body, signal, onMessage, onError, onComplete } = options;
|
|
23
|
+
|
|
24
|
+
return new Promise<void>((resolve) => {
|
|
25
|
+
const es = new EventSource(url, {
|
|
26
|
+
method,
|
|
27
|
+
headers: {
|
|
28
|
+
...headers,
|
|
29
|
+
'Accept': 'text/event-stream',
|
|
30
|
+
},
|
|
31
|
+
body,
|
|
32
|
+
pollingInterval: 0, // 禁用轮询,使用真正的 SSE
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
let isCompleted = false;
|
|
36
|
+
|
|
37
|
+
const cleanup = () => {
|
|
38
|
+
if (!isCompleted) {
|
|
39
|
+
isCompleted = true;
|
|
40
|
+
es.close();
|
|
41
|
+
resolve();
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
// 处理原始消息事件
|
|
46
|
+
es.addEventListener('message', (event: any) => {
|
|
47
|
+
if (event.data) {
|
|
48
|
+
// react-native-sse 返回的是已解析的单行数据
|
|
49
|
+
// 需要包装成 SSE 格式以便 parseMultilineSSE 处理
|
|
50
|
+
onMessage(`data: ${event.data}\n\n`);
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
// 处理打开事件
|
|
55
|
+
es.addEventListener('open', () => {
|
|
56
|
+
console.log('[SSE Native] Connection opened');
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
// 处理错误
|
|
60
|
+
es.addEventListener('error', (event: any) => {
|
|
61
|
+
console.error('[SSE Native] Error:', event);
|
|
62
|
+
if (!isCompleted) {
|
|
63
|
+
// 检查是否是正常结束
|
|
64
|
+
if (event.message?.includes('DONE') || event.type === 'close') {
|
|
65
|
+
onComplete();
|
|
66
|
+
} else {
|
|
67
|
+
onError(new Error(event.message || 'SSE connection error'));
|
|
68
|
+
}
|
|
69
|
+
cleanup();
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
// 处理关闭事件
|
|
74
|
+
es.addEventListener('close', () => {
|
|
75
|
+
console.log('[SSE Native] Connection closed');
|
|
76
|
+
if (!isCompleted) {
|
|
77
|
+
onComplete();
|
|
78
|
+
cleanup();
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
// 处理 abort signal
|
|
83
|
+
if (signal) {
|
|
84
|
+
signal.addEventListener('abort', () => {
|
|
85
|
+
console.log('[SSE Native] Aborted by signal');
|
|
86
|
+
cleanup();
|
|
87
|
+
onComplete();
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// 文件路径: ai/chat/sseClient.ts
|
|
2
|
+
// Web 版 SSE 客户端实现 - 使用 fetch + ReadableStream
|
|
3
|
+
|
|
4
|
+
export interface SSEClientOptions {
|
|
5
|
+
url: string;
|
|
6
|
+
method: 'POST';
|
|
7
|
+
headers: Record<string, string>;
|
|
8
|
+
body: string;
|
|
9
|
+
signal?: AbortSignal;
|
|
10
|
+
onMessage: (data: string) => void;
|
|
11
|
+
onError: (error: Error) => void;
|
|
12
|
+
onComplete: () => void;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Web 版 SSE 客户端
|
|
17
|
+
* 使用 fetch + ReadableStream.getReader() 实现流式读取
|
|
18
|
+
*/
|
|
19
|
+
export async function createSSEClient(options: SSEClientOptions): Promise<void> {
|
|
20
|
+
const { url, method, headers, body, signal, onMessage, onError, onComplete } = options;
|
|
21
|
+
|
|
22
|
+
try {
|
|
23
|
+
const response = await fetch(url, {
|
|
24
|
+
method,
|
|
25
|
+
headers,
|
|
26
|
+
body,
|
|
27
|
+
signal,
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
if (!response.ok) {
|
|
31
|
+
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const reader = response.body?.getReader();
|
|
35
|
+
if (!reader) {
|
|
36
|
+
throw new Error('Response body is not readable');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const decoder = new TextDecoder();
|
|
40
|
+
|
|
41
|
+
try {
|
|
42
|
+
while (true) {
|
|
43
|
+
const { done, value } = await reader.read();
|
|
44
|
+
|
|
45
|
+
if (done) {
|
|
46
|
+
onComplete();
|
|
47
|
+
break;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const chunk = decoder.decode(value, { stream: true });
|
|
51
|
+
onMessage(chunk);
|
|
52
|
+
}
|
|
53
|
+
} finally {
|
|
54
|
+
try {
|
|
55
|
+
await reader.cancel();
|
|
56
|
+
} catch (_e) {
|
|
57
|
+
// ignore cancel errors
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
} catch (error: any) {
|
|
61
|
+
if (error?.name === 'AbortError') {
|
|
62
|
+
onComplete();
|
|
63
|
+
} else {
|
|
64
|
+
onError(error instanceof Error ? error : new Error(String(error)));
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|