@midscene/core 1.16.1 → 1.16.2
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/es/agent/utils.mjs +4 -4
- package/dist/es/agent/utils.mjs.map +1 -1
- package/dist/es/ai-model/models/auto-glm/parser.mjs +1 -1
- package/dist/es/ai-model/models/auto-glm/parser.mjs.map +1 -1
- package/dist/es/ai-model/models/kimi.mjs +1 -1
- package/dist/es/ai-model/models/kimi.mjs.map +1 -1
- package/dist/es/ai-model/service-caller/call-ai.mjs +10 -1
- package/dist/es/ai-model/service-caller/call-ai.mjs.map +1 -1
- package/dist/es/ai-model/service-caller/openai/call-openai.mjs +7 -2
- package/dist/es/ai-model/service-caller/openai/call-openai.mjs.map +1 -1
- package/dist/es/ai-model/shared/model-locate-result/errors.mjs +1 -1
- package/dist/es/ai-model/shared/model-locate-result/errors.mjs.map +1 -1
- package/dist/es/ai-model/shared/model-locate-result/parse.mjs +6 -2
- package/dist/es/ai-model/shared/model-locate-result/parse.mjs.map +1 -1
- package/dist/es/device/index.mjs +9 -8
- package/dist/es/device/index.mjs.map +1 -1
- package/dist/es/report-generator.mjs +3 -3
- package/dist/es/report-generator.mjs.map +1 -1
- package/dist/es/report-html-template.mjs +1 -1
- package/dist/es/test-run-report.mjs.map +1 -1
- package/dist/es/test-runner/reporting/merge-report.mjs +3 -1
- package/dist/es/test-runner/reporting/merge-report.mjs.map +1 -1
- package/dist/es/test-runner/reporting/metrics.mjs +39 -2
- package/dist/es/test-runner/reporting/metrics.mjs.map +1 -1
- package/dist/es/utils.mjs +1 -1
- package/dist/lib/agent/utils.js +2 -2
- package/dist/lib/agent/utils.js.map +1 -1
- package/dist/lib/ai-model/models/auto-glm/parser.js +1 -1
- package/dist/lib/ai-model/models/auto-glm/parser.js.map +1 -1
- package/dist/lib/ai-model/models/kimi.js +1 -1
- package/dist/lib/ai-model/models/kimi.js.map +1 -1
- package/dist/lib/ai-model/service-caller/call-ai.js +10 -1
- package/dist/lib/ai-model/service-caller/call-ai.js.map +1 -1
- package/dist/lib/ai-model/service-caller/openai/call-openai.js +7 -2
- package/dist/lib/ai-model/service-caller/openai/call-openai.js.map +1 -1
- package/dist/lib/ai-model/shared/model-locate-result/errors.js +1 -1
- package/dist/lib/ai-model/shared/model-locate-result/errors.js.map +1 -1
- package/dist/lib/ai-model/shared/model-locate-result/parse.js +6 -2
- package/dist/lib/ai-model/shared/model-locate-result/parse.js.map +1 -1
- package/dist/lib/device/index.js +9 -8
- package/dist/lib/device/index.js.map +1 -1
- package/dist/lib/report-generator.js +2 -2
- package/dist/lib/report-generator.js.map +1 -1
- package/dist/lib/report-html-template.js +1 -1
- package/dist/lib/test-run-report.js.map +1 -1
- package/dist/lib/test-runner/reporting/merge-report.js +3 -1
- package/dist/lib/test-runner/reporting/merge-report.js.map +1 -1
- package/dist/lib/test-runner/reporting/metrics.js +39 -2
- package/dist/lib/test-runner/reporting/metrics.js.map +1 -1
- package/dist/lib/utils.js +1 -1
- package/dist/types/ai-model/models/auto-glm/parser.d.ts.map +1 -1
- package/dist/types/ai-model/service-caller/openai/call-openai.d.ts.map +1 -1
- package/dist/types/ai-model/shared/model-locate-result/errors.d.ts +1 -1
- package/dist/types/ai-model/shared/model-locate-result/errors.d.ts.map +1 -1
- package/dist/types/ai-model/shared/model-locate-result/parse.d.ts.map +1 -1
- package/dist/types/device/index.d.ts +7 -7
- package/dist/types/device/index.d.ts.map +1 -1
- package/dist/types/test-run-report.d.ts +4 -1
- package/dist/types/test-run-report.d.ts.map +1 -1
- package/dist/types/test-runner/parser/types.d.ts +5 -0
- package/dist/types/test-runner/parser/types.d.ts.map +1 -1
- package/dist/types/test-runner/reporting/merge-report.d.ts.map +1 -1
- package/dist/types/test-runner/reporting/metrics.d.ts.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ai-model/models/kimi.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../../src/ai-model/models/kimi.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import type { TModelFamily } from '@midscene/shared/env';\nimport type {\n ChatCompletionCallContext,\n ChatCompletionParamsResult,\n ModelAdapterDefinition,\n} from '../model-adapter/types';\nimport {\n type LocateResultValue,\n createLocateResultValue,\n parseCoordinateList,\n} from '../shared/model-locate-result';\n\nconst kimiNormalizedPointCoordinatesMeta = {\n shape: 'point',\n order: 'xy',\n normalizedBy: 1,\n rounding: 'round',\n} as const;\nconst kimiPixelPointCoordinatesMeta = {\n shape: 'point',\n order: 'xy',\n rounding: 'round',\n} as const;\n\nfunction parseKimiRawLocateValue(input: unknown): LocateResultValue {\n const point = parseCoordinateList(input, 'point');\n if (point.length
|
|
1
|
+
{"version":3,"file":"ai-model/models/kimi.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../../src/ai-model/models/kimi.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import type { TModelFamily } from '@midscene/shared/env';\nimport type {\n ChatCompletionCallContext,\n ChatCompletionParamsResult,\n ModelAdapterDefinition,\n} from '../model-adapter/types';\nimport {\n type LocateResultValue,\n createLocateResultValue,\n parseCoordinateList,\n} from '../shared/model-locate-result';\n\nconst kimiNormalizedPointCoordinatesMeta = {\n shape: 'point',\n order: 'xy',\n normalizedBy: 1,\n rounding: 'round',\n} as const;\nconst kimiPixelPointCoordinatesMeta = {\n shape: 'point',\n order: 'xy',\n rounding: 'round',\n} as const;\n\nfunction parseKimiRawLocateValue(input: unknown): LocateResultValue {\n const point = parseCoordinateList(input, 'point');\n if (point.length !== 2) {\n throw new Error(`invalid point data: ${JSON.stringify(input)} `);\n }\n const [x, y] = point;\n // Keep this compatible with OSWorld's Kimi adapter: values <= 1 are\n // normalized coordinates, otherwise they are treated as screenshot pixels.\n const coordinatesMeta =\n x <= 1 && y <= 1\n ? kimiNormalizedPointCoordinatesMeta\n : kimiPixelPointCoordinatesMeta;\n return createLocateResultValue(coordinatesMeta, [x, y]);\n}\n\nconst buildKimiChatCompletionParams = (\n input: ChatCompletionCallContext,\n): ChatCompletionParamsResult => {\n const { midsceneDefaults, userConfig } = input;\n const { reasoningEnabled } = userConfig;\n const effectiveReasoningEnabled = reasoningEnabled ?? false;\n const commonOverrideConfig: Record<string, unknown> = {};\n\n // kimi disallow custom temperature\n commonOverrideConfig.temperature = undefined;\n\n // Kimi Chat Completions response_format:\n // https://platform.kimi.com/docs/api/chat\n if (\n userConfig.responseFormat !== 'none' &&\n input.expectedJsonObjectResponse\n ) {\n commonOverrideConfig.response_format = { type: 'json_object' };\n }\n\n const modelSpecificConfig: Record<string, unknown> = {\n thinking: {\n type: effectiveReasoningEnabled ? 'enabled' : 'disabled',\n },\n };\n\n return {\n config: {\n ...midsceneDefaults,\n ...commonOverrideConfig,\n ...modelSpecificConfig,\n },\n };\n};\n\nconst buildKimi3ChatCompletionParams = (\n input: ChatCompletionCallContext,\n): ChatCompletionParamsResult => {\n const { midsceneDefaults, userConfig } = input;\n const commonOverrideConfig: Record<string, unknown> = {};\n\n // Kimi disallows custom temperature.\n commonOverrideConfig.temperature = undefined;\n\n if (\n userConfig.responseFormat !== 'none' &&\n input.expectedJsonObjectResponse\n ) {\n commonOverrideConfig.response_format = { type: 'json_object' };\n }\n\n // Kimi K3 currently only supports reasoning_effort=\"max\"; its docs say\n // additional effort levels will be available later.\n const reasoningEffort = userConfig.reasoningEffort;\n\n return {\n config: {\n ...midsceneDefaults,\n ...commonOverrideConfig,\n ...(reasoningEffort ? { reasoning_effort: reasoningEffort } : {}),\n },\n };\n};\n\nexport const kimiAdapters = {\n kimi: {\n chatCompletion: {\n unsupportedUserConfig: ['reasoningEffort', 'reasoningBudget'],\n buildChatCompletionParams: buildKimiChatCompletionParams,\n useReasoningAsContentFallback: true,\n },\n locate: {\n element: {\n resultFormat: {\n coordinates: kimiNormalizedPointCoordinatesMeta,\n parseRawLocateValue: parseKimiRawLocateValue,\n },\n },\n },\n },\n kimi3: {\n chatCompletion: {\n unsupportedUserConfig: ['reasoningEnabled', 'reasoningBudget'],\n buildChatCompletionParams: buildKimi3ChatCompletionParams,\n useReasoningAsContentFallback: true,\n // Kimi K3 multi-turn and tool calls must replay the complete assistant\n // message, including reasoning_content and tool_calls.\n // https://platform.kimi.com/docs/guide/use-thinking-effort\n replayRawAssistantMessage: true,\n },\n locate: {\n element: {\n resultFormat: {\n coordinates: kimiNormalizedPointCoordinatesMeta,\n parseRawLocateValue: parseKimiRawLocateValue,\n },\n },\n },\n },\n} satisfies Pick<\n Record<TModelFamily, ModelAdapterDefinition>,\n 'kimi' | 'kimi3'\n>;\n"],"names":["__webpack_require__","definition","key","Object","obj","prop","Symbol","kimiNormalizedPointCoordinatesMeta","kimiPixelPointCoordinatesMeta","parseKimiRawLocateValue","input","point","parseCoordinateList","Error","JSON","x","y","coordinatesMeta","createLocateResultValue","buildKimiChatCompletionParams","midsceneDefaults","userConfig","reasoningEnabled","effectiveReasoningEnabled","commonOverrideConfig","undefined","modelSpecificConfig","buildKimi3ChatCompletionParams","reasoningEffort","kimiAdapters"],"mappings":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBAAoB,CAAC,CAAC,UAASE,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAF,oBAAoB,CAAC,GAAG,CAACI,KAAKC,OAAUF,OAAO,SAAS,CAAC,cAAc,CAAC,IAAI,CAACC,KAAKC;;;ICClFL,oBAAoB,CAAC,GAAG,CAAC;QACxB,IAAG,AAAkB,eAAlB,OAAOM,UAA0BA,OAAO,WAAW,EACrDH,OAAO,cAAc,CAAC,UAASG,OAAO,WAAW,EAAE;YAAE,OAAO;QAAS;QAEtEH,OAAO,cAAc,CAAC,UAAS,cAAc;YAAE,OAAO;QAAK;IAC5D;;;;;;;;ACMA,MAAMI,qCAAqC;IACzC,OAAO;IACP,OAAO;IACP,cAAc;IACd,UAAU;AACZ;AACA,MAAMC,gCAAgC;IACpC,OAAO;IACP,OAAO;IACP,UAAU;AACZ;AAEA,SAASC,wBAAwBC,KAAc;IAC7C,MAAMC,QAAQC,AAAAA,IAAAA,yBAAAA,mBAAAA,AAAAA,EAAoBF,OAAO;IACzC,IAAIC,AAAiB,MAAjBA,MAAM,MAAM,EACd,MAAM,IAAIE,MAAM,CAAC,oBAAoB,EAAEC,KAAK,SAAS,CAACJ,OAAO,CAAC,CAAC;IAEjE,MAAM,CAACK,GAAGC,EAAE,GAAGL;IAGf,MAAMM,kBACJF,KAAK,KAAKC,KAAK,IACXT,qCACAC;IACN,OAAOU,AAAAA,IAAAA,yBAAAA,uBAAAA,AAAAA,EAAwBD,iBAAiB;QAACF;Q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B;YAC3B,+BAA+B;YAI/B,2BAA2B;QAC7B;QACA,QAAQ;YACN,SAAS;gBACP,cAAc;oBACZ,aAAapB;oBACb,qBAAqBE;gBACvB;YACF;QACF;IACF;AACF"}
|
|
@@ -154,7 +154,16 @@ async function callModelWithRetry(input) {
|
|
|
154
154
|
});
|
|
155
155
|
if (attempt === maxAttempts) throw (0, external_utils_js_namespaceObject.appendAIRequestFailureSummary)(lastError, attemptErrors, maxAttempts);
|
|
156
156
|
(0, logger_namespaceObject.getDebug)('ai:call', {
|
|
157
|
-
console: true
|
|
157
|
+
console: true,
|
|
158
|
+
warning: {
|
|
159
|
+
kind: 'model-request-retry',
|
|
160
|
+
modelName: config.modelName,
|
|
161
|
+
error: lastError,
|
|
162
|
+
callId: input.internalCallId,
|
|
163
|
+
attempt,
|
|
164
|
+
maxAttempts,
|
|
165
|
+
delayMs: retryInterval
|
|
166
|
+
}
|
|
158
167
|
})(`AI call failed (attempt ${attempt}/${maxAttempts}), retrying in ${retryInterval}ms... Error: ${lastError.message}`);
|
|
159
168
|
}
|
|
160
169
|
await (0, external_request_timeout_js_namespaceObject.waitForRetry)(retryInterval, options?.abortSignal);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ai-model/service-caller/call-ai.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../../src/ai-model/service-caller/call-ai.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import { getDebug } from '@midscene/shared/logger';\nimport { assert, uuid } from '@midscene/shared/utils';\nimport type { ModelRuntime } from '../models';\nimport { callCodex, prepareCodexCall } from './codex/call-codex';\nimport { isCodexAppServerProvider } from './codex/codex-app-server';\nimport {\n isModelCallRecordingEnabled,\n recordModelCallEvent,\n} from './model-call-recorder';\nimport { type PreparedOpenAIInput, callOpenAI } from './openai/call-openai';\nimport { prepareChatCompletion } from './openai/chat-completion/chat-completion';\nimport { prepareResponses } from './openai/responses/responses';\nimport {\n buildRequestAbortSignal,\n resolveEffectiveTimeoutMs,\n runWithAbortSignal,\n waitForRetry,\n} from './request-timeout';\nimport { callSystemOne, prepareSystemOne } from './system-one';\nimport type { ModelCallMessages } from './types';\nimport type {\n AICallResult,\n CallAIOptions,\n ModelCallContext,\n ModelCallResult,\n} from './types';\nimport {\n appendAIRequestFailureSummary,\n buildUsageInfo,\n nextInternalCallId,\n normalizeRetryCount,\n toError,\n} from './utils';\n\nconst DEFAULT_MODEL_PROTOCOL = 'openai-chat';\n\nexport async function callAI(\n messages: ModelCallMessages,\n modelRuntime: ModelRuntime,\n options?: CallAIOptions,\n): Promise<AICallResult> {\n options?.abortSignal?.throwIfAborted();\n const isStreaming = options?.stream === true;\n if (isStreaming) {\n // Explicit streaming is currently used only by recorder code generation.\n // Streaming can also be aggregated without onChunk, but then the caller\n // cannot consume incremental output, which is the purpose of this option.\n // Environment-enabled streaming supports that aggregation-only use case.\n // Once onChunk delivers a chunk, later errors are not retried to avoid\n // delivering duplicate content. Errors before the first chunk can retry.\n assert(\n typeof options?.onChunk === 'function',\n 'onChunk is required when stream: true is explicitly specified',\n );\n }\n\n // Low-level callers without a TaskRunner still need a stable ID for the\n // lifetime of this model call (including its network retries).\n const executionId = modelRuntime.executionId ?? `unscoped-${uuid()}`;\n\n // Stable internal ID for this call, used by the agent to deduplicate usage\n // across the onUsage callback and the task-dump-based collectUsageMetrics()\n // path when the provider does not return a request_id.\n const internalCallId = nextInternalCallId();\n\n const { config: modelConfig } = modelRuntime;\n\n const prepare = async (): Promise<PreparedModelInput> => {\n if (options?.systemOneRequest) {\n assert(\n modelConfig.modelFamily === 'jev',\n 'System One requests require the Jev model family',\n );\n return {\n protocol: 'system-one',\n input: await prepareSystemOne(modelConfig, options.systemOneRequest),\n };\n }\n const input = { messages, modelRuntime, options };\n if (isCodexAppServerProvider(modelConfig.openaiBaseURL)) {\n return { protocol: 'codex', input: prepareCodexCall(input) };\n }\n const protocol = modelConfig.protocol ?? DEFAULT_MODEL_PROTOCOL;\n\n assert(\n modelRuntime.adapter.supportedProtocols.includes(protocol),\n `Model adapter \"${modelConfig.modelFamily ?? 'default'}\" does not support protocol \"${protocol}\"`,\n );\n if (protocol === 'openai-responses') {\n return { protocol: 'responses', input: await prepareResponses(input) };\n }\n return {\n protocol: 'chat-completion',\n input: await prepareChatCompletion(input),\n };\n };\n\n const prepared = options?.abortSignal\n ? await runWithAbortSignal(options.abortSignal, prepare)\n : await prepare();\n\n const result = await callModelWithRetry({\n messages,\n modelRuntime,\n options,\n executionId,\n internalCallId,\n prepared,\n });\n\n const {\n rawUsage,\n timeCost,\n totalTimeCost,\n retryCount,\n requestId,\n responseModelName,\n ...response\n } = result;\n\n const rawUsageInfo = buildUsageInfo({\n apiProtocol: prepared.protocol,\n stream: response.isStreamed,\n usageData: rawUsage,\n timeCost,\n totalTimeCost,\n retryCount,\n requestId,\n responseModelName,\n modelName: modelConfig.modelName,\n modelDescription: modelConfig.modelDescription,\n slot: modelConfig.slot,\n internalCallId,\n });\n\n const usage = rawUsageInfo\n ? { ...rawUsageInfo, modelRouting: modelRuntime.modelRouting }\n : undefined;\n\n const debugProfileStats = getDebug('ai:profile:stats');\n const debugProfileDetail = getDebug('ai:profile:detail');\n debugProfileStats(\n `model, ${modelConfig.modelName}, mode, ${modelConfig.modelFamily || 'default'}, streaming, ${response.isStreamed}, prompt-tokens, ${usage?.prompt_tokens ?? ''}, completion-tokens, ${usage?.completion_tokens ?? ''}, total-tokens, ${usage?.total_tokens ?? ''}, cached-input, ${usage?.cached_input ?? ''}, cost-ms, ${timeCost ?? ''}, requestId, ${requestId ?? ''}, slot, ${modelConfig.slot}, configured-temperature, ${modelConfig.temperature ?? ''}`,\n );\n debugProfileDetail(`model usage detail: ${JSON.stringify(usage)}`);\n\n if (usage && modelRuntime.onUsage) {\n modelRuntime.onUsage(usage);\n }\n return { ...response, usage };\n}\n\ntype PreparedModelInput =\n | {\n protocol: 'system-one';\n input: Awaited<ReturnType<typeof prepareSystemOne>>;\n }\n | { protocol: 'codex'; input: ReturnType<typeof prepareCodexCall> }\n | PreparedOpenAIInput;\n\ntype ModelCallInput = {\n messages: ModelCallMessages;\n modelRuntime: ModelRuntime;\n options?: CallAIOptions;\n executionId: string;\n internalCallId: string;\n prepared: PreparedModelInput;\n};\n\n/** Carries the original failure across the retry boundary without replaying output. */\nclass NonRetryableModelCallError extends Error {\n readonly cause: Error;\n\n constructor(cause: Error) {\n super(cause.message, { cause });\n this.cause = cause;\n }\n}\n\nasync function callModelWithRetry(\n input: ModelCallInput,\n): Promise<ModelCallResult & { totalTimeCost: number; retryCount: number }> {\n const startTime = Date.now();\n const {\n modelRuntime: { config },\n options,\n } = input;\n const maxAttempts = normalizeRetryCount(config.retryCount) + 1;\n const retryInterval = config.retryInterval ?? 2000;\n const attemptErrors: Array<{ attempt: number; error: unknown }> = [];\n\n for (let attempt = 1; ; attempt++) {\n options?.abortSignal?.throwIfAborted();\n try {\n const result = await callModelOnce(input, attempt);\n return {\n ...result,\n totalTimeCost: Date.now() - startTime,\n retryCount: attempt - 1,\n };\n } catch (error) {\n options?.abortSignal?.throwIfAborted();\n if (error instanceof NonRetryableModelCallError) {\n throw error.cause;\n }\n const lastError = toError(error);\n attemptErrors.push({ attempt, error: lastError });\n if (attempt === maxAttempts) {\n throw appendAIRequestFailureSummary(\n lastError,\n attemptErrors,\n maxAttempts,\n );\n }\n getDebug('ai:call', { console: true })(\n `AI call failed (attempt ${attempt}/${maxAttempts}), retrying in ${retryInterval}ms... Error: ${lastError.message}`,\n );\n }\n await waitForRetry(retryInterval, options?.abortSignal);\n }\n}\n\nasync function callModelOnce(\n {\n messages,\n modelRuntime,\n options,\n executionId,\n internalCallId,\n prepared,\n }: ModelCallInput,\n attempt: number,\n): Promise<ModelCallResult> {\n const { config: modelConfig } = modelRuntime;\n const recordingEnabled = isModelCallRecordingEnabled();\n const recordEvent =\n recordingEnabled || modelRuntime.onRequest\n ? (event: Record<string, unknown>) => {\n if (event.type === 'request') {\n const request = event.request as { url?: string } | undefined;\n modelRuntime.onRequest?.(request?.url);\n }\n if (!recordingEnabled) return;\n void recordModelCallEvent({\n executionId,\n callId: internalCallId,\n semanticRetryAttempt: options?.semanticRetryAttempt,\n slot: modelConfig.slot,\n intent: modelConfig.intent,\n modelFamily: modelConfig.modelFamily,\n modelRouting: modelRuntime.modelRouting,\n ...event,\n attempt,\n });\n }\n : undefined;\n const effectiveTimeoutMs = resolveEffectiveTimeoutMs(modelConfig.timeout);\n const { signal: requestSignal, cleanup } = buildRequestAbortSignal(\n effectiveTimeoutMs,\n options?.abortSignal,\n );\n let deliveredChunk = false;\n const onChunk = options?.onChunk;\n const context: ModelCallContext = {\n messages,\n modelRuntime,\n executionId,\n recordEvent,\n requestSignal,\n effectiveTimeoutMs,\n options: onChunk\n ? {\n ...options,\n onChunk: (chunk) => {\n requestSignal.throwIfAborted();\n deliveredChunk = true;\n onChunk(chunk);\n },\n }\n : options,\n };\n try {\n return await runWithAbortSignal(requestSignal, () =>\n prepared.protocol === 'system-one'\n ? callSystemOne(context, prepared.input)\n : prepared.protocol === 'codex'\n ? callCodex(context, prepared.input)\n : callOpenAI(context, prepared),\n );\n } catch (error) {\n options?.abortSignal?.throwIfAborted();\n const lastError = toError(error);\n if (deliveredChunk) {\n throw new NonRetryableModelCallError(lastError);\n }\n throw lastError;\n } finally {\n cleanup();\n }\n}\n"],"names":["__webpack_require__","definition","key","Object","obj","prop","Symbol","DEFAULT_MODEL_PROTOCOL","callAI","messages","modelRuntime","options","isStreaming","assert","executionId","uuid","internalCallId","nextInternalCallId","modelConfig","prepare","prepareSystemOne","input","isCodexAppServerProvider","prepareCodexCall","protocol","prepareResponses","prepareChatCompletion","prepared","runWithAbortSignal","result","callModelWithRetry","rawUsage","timeCost","totalTimeCost","retryCount","requestId","responseModelName","response","rawUsageInfo","buildUsageInfo","usage","undefined","debugProfileStats","getDebug","debugProfileDetail","JSON","NonRetryableModelCallError","Error","cause","startTime","Date","config","maxAttempts","normalizeRetryCount","retryInterval","attemptErrors","attempt","callModelOnce","error","lastError","toError","appendAIRequestFailureSummary","waitForRetry","recordingEnabled","isModelCallRecordingEnabled","recordEvent","event","request","recordModelCallEvent","effectiveTimeoutMs","resolveEffectiveTimeoutMs","requestSignal","cleanup","buildRequestAbortSignal","deliveredChunk","onChunk","context","chunk","callSystemOne","callCodex","callOpenAI"],"mappings":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBAAoB,CAAC,CAAC,UAASE,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAF,oBAAoB,CAAC,GAAG,CAACI,KAAKC,OAAUF,OAAO,SAAS,CAAC,cAAc,CAAC,IAAI,CAACC,KAAKC;;;ICClFL,oBAAoB,CAAC,GAAG,CAAC;QACxB,IAAG,AAAkB,eAAlB,OAAOM,UAA0BA,OAAO,WAAW,EACrDH,OAAO,cAAc,CAAC,UAASG,OAAO,WAAW,EAAE;YAAE,OAAO;QAAS;QAEtEH,OAAO,cAAc,CAAC,UAAS,cAAc;YAAE,OAAO;QAAK;IAC5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC4BA,MAAMI,yBAAyB;AAExB,eAAeC,OACpBC,QAA2B,EAC3BC,YAA0B,EAC1BC,OAAu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BAAiB;gBACjBC,QAAQE;YACV;QACF,IACAlE;IACN;IACA,IAAI;QACF,OAAO,MAAMiB,AAAAA,IAAAA,4CAAAA,kBAAAA,AAAAA,EAAmB2C,eAAe,IAC7C5C,AAAsB,iBAAtBA,SAAS,QAAQ,GACbmD,AAAAA,IAAAA,uCAAAA,aAAAA,AAAAA,EAAcF,SAASjD,SAAS,KAAK,IACrCA,AAAsB,YAAtBA,SAAS,QAAQ,GACfoD,AAAAA,IAAAA,8BAAAA,SAAAA,AAAAA,EAAUH,SAASjD,SAAS,KAAK,IACjCqD,AAAAA,IAAAA,+BAAAA,UAAAA,AAAAA,EAAWJ,SAASjD;IAE9B,EAAE,OAAO+B,OAAO;QACd/C,SAAS,aAAa;QACtB,MAAMgD,YAAYC,AAAAA,IAAAA,kCAAAA,OAAAA,AAAAA,EAAQF;QAC1B,IAAIgB,gBACF,MAAM,IAAI5B,2BAA2Ba;QAEvC,MAAMA;IACR,SAAU;QACRa;IACF;AACF"}
|
|
1
|
+
{"version":3,"file":"ai-model/service-caller/call-ai.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../../src/ai-model/service-caller/call-ai.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import { getDebug } from '@midscene/shared/logger';\nimport { assert, uuid } from '@midscene/shared/utils';\nimport type { ModelRuntime } from '../models';\nimport { callCodex, prepareCodexCall } from './codex/call-codex';\nimport { isCodexAppServerProvider } from './codex/codex-app-server';\nimport {\n isModelCallRecordingEnabled,\n recordModelCallEvent,\n} from './model-call-recorder';\nimport { type PreparedOpenAIInput, callOpenAI } from './openai/call-openai';\nimport { prepareChatCompletion } from './openai/chat-completion/chat-completion';\nimport { prepareResponses } from './openai/responses/responses';\nimport {\n buildRequestAbortSignal,\n resolveEffectiveTimeoutMs,\n runWithAbortSignal,\n waitForRetry,\n} from './request-timeout';\nimport { callSystemOne, prepareSystemOne } from './system-one';\nimport type { ModelCallMessages } from './types';\nimport type {\n AICallResult,\n CallAIOptions,\n ModelCallContext,\n ModelCallResult,\n} from './types';\nimport {\n appendAIRequestFailureSummary,\n buildUsageInfo,\n nextInternalCallId,\n normalizeRetryCount,\n toError,\n} from './utils';\n\nconst DEFAULT_MODEL_PROTOCOL = 'openai-chat';\n\nexport async function callAI(\n messages: ModelCallMessages,\n modelRuntime: ModelRuntime,\n options?: CallAIOptions,\n): Promise<AICallResult> {\n options?.abortSignal?.throwIfAborted();\n const isStreaming = options?.stream === true;\n if (isStreaming) {\n // Explicit streaming is currently used only by recorder code generation.\n // Streaming can also be aggregated without onChunk, but then the caller\n // cannot consume incremental output, which is the purpose of this option.\n // Environment-enabled streaming supports that aggregation-only use case.\n // Once onChunk delivers a chunk, later errors are not retried to avoid\n // delivering duplicate content. Errors before the first chunk can retry.\n assert(\n typeof options?.onChunk === 'function',\n 'onChunk is required when stream: true is explicitly specified',\n );\n }\n\n // Low-level callers without a TaskRunner still need a stable ID for the\n // lifetime of this model call (including its network retries).\n const executionId = modelRuntime.executionId ?? `unscoped-${uuid()}`;\n\n // Stable internal ID for this call, used by the agent to deduplicate usage\n // across the onUsage callback and the task-dump-based collectUsageMetrics()\n // path when the provider does not return a request_id.\n const internalCallId = nextInternalCallId();\n\n const { config: modelConfig } = modelRuntime;\n\n const prepare = async (): Promise<PreparedModelInput> => {\n if (options?.systemOneRequest) {\n assert(\n modelConfig.modelFamily === 'jev',\n 'System One requests require the Jev model family',\n );\n return {\n protocol: 'system-one',\n input: await prepareSystemOne(modelConfig, options.systemOneRequest),\n };\n }\n const input = { messages, modelRuntime, options };\n if (isCodexAppServerProvider(modelConfig.openaiBaseURL)) {\n return { protocol: 'codex', input: prepareCodexCall(input) };\n }\n const protocol = modelConfig.protocol ?? DEFAULT_MODEL_PROTOCOL;\n\n assert(\n modelRuntime.adapter.supportedProtocols.includes(protocol),\n `Model adapter \"${modelConfig.modelFamily ?? 'default'}\" does not support protocol \"${protocol}\"`,\n );\n if (protocol === 'openai-responses') {\n return { protocol: 'responses', input: await prepareResponses(input) };\n }\n return {\n protocol: 'chat-completion',\n input: await prepareChatCompletion(input),\n };\n };\n\n const prepared = options?.abortSignal\n ? await runWithAbortSignal(options.abortSignal, prepare)\n : await prepare();\n\n const result = await callModelWithRetry({\n messages,\n modelRuntime,\n options,\n executionId,\n internalCallId,\n prepared,\n });\n\n const {\n rawUsage,\n timeCost,\n totalTimeCost,\n retryCount,\n requestId,\n responseModelName,\n ...response\n } = result;\n\n const rawUsageInfo = buildUsageInfo({\n apiProtocol: prepared.protocol,\n stream: response.isStreamed,\n usageData: rawUsage,\n timeCost,\n totalTimeCost,\n retryCount,\n requestId,\n responseModelName,\n modelName: modelConfig.modelName,\n modelDescription: modelConfig.modelDescription,\n slot: modelConfig.slot,\n internalCallId,\n });\n\n const usage = rawUsageInfo\n ? { ...rawUsageInfo, modelRouting: modelRuntime.modelRouting }\n : undefined;\n\n const debugProfileStats = getDebug('ai:profile:stats');\n const debugProfileDetail = getDebug('ai:profile:detail');\n debugProfileStats(\n `model, ${modelConfig.modelName}, mode, ${modelConfig.modelFamily || 'default'}, streaming, ${response.isStreamed}, prompt-tokens, ${usage?.prompt_tokens ?? ''}, completion-tokens, ${usage?.completion_tokens ?? ''}, total-tokens, ${usage?.total_tokens ?? ''}, cached-input, ${usage?.cached_input ?? ''}, cost-ms, ${timeCost ?? ''}, requestId, ${requestId ?? ''}, slot, ${modelConfig.slot}, configured-temperature, ${modelConfig.temperature ?? ''}`,\n );\n debugProfileDetail(`model usage detail: ${JSON.stringify(usage)}`);\n\n if (usage && modelRuntime.onUsage) {\n modelRuntime.onUsage(usage);\n }\n return { ...response, usage };\n}\n\ntype PreparedModelInput =\n | {\n protocol: 'system-one';\n input: Awaited<ReturnType<typeof prepareSystemOne>>;\n }\n | { protocol: 'codex'; input: ReturnType<typeof prepareCodexCall> }\n | PreparedOpenAIInput;\n\ntype ModelCallInput = {\n messages: ModelCallMessages;\n modelRuntime: ModelRuntime;\n options?: CallAIOptions;\n executionId: string;\n internalCallId: string;\n prepared: PreparedModelInput;\n};\n\n/** Carries the original failure across the retry boundary without replaying output. */\nclass NonRetryableModelCallError extends Error {\n readonly cause: Error;\n\n constructor(cause: Error) {\n super(cause.message, { cause });\n this.cause = cause;\n }\n}\n\nasync function callModelWithRetry(\n input: ModelCallInput,\n): Promise<ModelCallResult & { totalTimeCost: number; retryCount: number }> {\n const startTime = Date.now();\n const {\n modelRuntime: { config },\n options,\n } = input;\n const maxAttempts = normalizeRetryCount(config.retryCount) + 1;\n const retryInterval = config.retryInterval ?? 2000;\n const attemptErrors: Array<{ attempt: number; error: unknown }> = [];\n\n for (let attempt = 1; ; attempt++) {\n options?.abortSignal?.throwIfAborted();\n try {\n const result = await callModelOnce(input, attempt);\n return {\n ...result,\n totalTimeCost: Date.now() - startTime,\n retryCount: attempt - 1,\n };\n } catch (error) {\n options?.abortSignal?.throwIfAborted();\n if (error instanceof NonRetryableModelCallError) {\n throw error.cause;\n }\n const lastError = toError(error);\n attemptErrors.push({ attempt, error: lastError });\n if (attempt === maxAttempts) {\n throw appendAIRequestFailureSummary(\n lastError,\n attemptErrors,\n maxAttempts,\n );\n }\n getDebug('ai:call', {\n console: true,\n warning: {\n kind: 'model-request-retry',\n modelName: config.modelName,\n error: lastError,\n callId: input.internalCallId,\n attempt,\n maxAttempts,\n delayMs: retryInterval,\n },\n })(\n `AI call failed (attempt ${attempt}/${maxAttempts}), retrying in ${retryInterval}ms... Error: ${lastError.message}`,\n );\n }\n await waitForRetry(retryInterval, options?.abortSignal);\n }\n}\n\nasync function callModelOnce(\n {\n messages,\n modelRuntime,\n options,\n executionId,\n internalCallId,\n prepared,\n }: ModelCallInput,\n attempt: number,\n): Promise<ModelCallResult> {\n const { config: modelConfig } = modelRuntime;\n const recordingEnabled = isModelCallRecordingEnabled();\n const recordEvent =\n recordingEnabled || modelRuntime.onRequest\n ? (event: Record<string, unknown>) => {\n if (event.type === 'request') {\n const request = event.request as { url?: string } | undefined;\n modelRuntime.onRequest?.(request?.url);\n }\n if (!recordingEnabled) return;\n void recordModelCallEvent({\n executionId,\n callId: internalCallId,\n semanticRetryAttempt: options?.semanticRetryAttempt,\n slot: modelConfig.slot,\n intent: modelConfig.intent,\n modelFamily: modelConfig.modelFamily,\n modelRouting: modelRuntime.modelRouting,\n ...event,\n attempt,\n });\n }\n : undefined;\n const effectiveTimeoutMs = resolveEffectiveTimeoutMs(modelConfig.timeout);\n const { signal: requestSignal, cleanup } = buildRequestAbortSignal(\n effectiveTimeoutMs,\n options?.abortSignal,\n );\n let deliveredChunk = false;\n const onChunk = options?.onChunk;\n const context: ModelCallContext = {\n messages,\n modelRuntime,\n executionId,\n recordEvent,\n requestSignal,\n effectiveTimeoutMs,\n options: onChunk\n ? {\n ...options,\n onChunk: (chunk) => {\n requestSignal.throwIfAborted();\n deliveredChunk = true;\n onChunk(chunk);\n },\n }\n : options,\n };\n try {\n return await runWithAbortSignal(requestSignal, () =>\n prepared.protocol === 'system-one'\n ? callSystemOne(context, prepared.input)\n : prepared.protocol === 'codex'\n ? callCodex(context, prepared.input)\n : callOpenAI(context, prepared),\n );\n } catch (error) {\n options?.abortSignal?.throwIfAborted();\n const lastError = toError(error);\n if (deliveredChunk) {\n throw new NonRetryableModelCallError(lastError);\n }\n throw lastError;\n } finally {\n cleanup();\n }\n}\n"],"names":["__webpack_require__","definition","key","Object","obj","prop","Symbol","DEFAULT_MODEL_PROTOCOL","callAI","messages","modelRuntime","options","isStreaming","assert","executionId","uuid","internalCallId","nextInternalCallId","modelConfig","prepare","prepareSystemOne","input","isCodexAppServerProvider","prepareCodexCall","protocol","prepareResponses","prepareChatCompletion","prepared","runWithAbortSignal","result","callModelWithRetry","rawUsage","timeCost","totalTimeCost","retryCount","requestId","responseModelName","response","rawUsageInfo","buildUsageInfo","usage","undefined","debugProfileStats","getDebug","debugProfileDetail","JSON","NonRetryableModelCallError","Error","cause","startTime","Date","config","maxAttempts","normalizeRetryCount","retryInterval","attemptErrors","attempt","callModelOnce","error","lastError","toError","appendAIRequestFailureSummary","waitForRetry","recordingEnabled","isModelCallRecordingEnabled","recordEvent","event","request","recordModelCallEvent","effectiveTimeoutMs","resolveEffectiveTimeoutMs","requestSignal","cleanup","buildRequestAbortSignal","deliveredChunk","onChunk","context","chunk","callSystemOne","callCodex","callOpenAI"],"mappings":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBAAoB,CAAC,CAAC,UAASE,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAF,oBAAoB,CAAC,GAAG,CAACI,KAAKC,OAAUF,OAAO,SAAS,CAAC,cAAc,CAAC,IAAI,CAACC,KAAKC;;;ICClFL,oBAAoB,CAAC,GAAG,CAAC;QACxB,IAAG,AAAkB,eAAlB,OAAOM,UAA0BA,OAAO,WAAW,EACrDH,OAAO,cAAc,CAAC,UAASG,OAAO,WAAW,EAAE;YAAE,OAAO;QAAS;QAEtEH,OAAO,cAAc,CAAC,UAAS,cAAc;YAAE,OAAO;QAAK;IAC5D;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC4BA,MAAMI,yBAAyB;AAExB,eAAeC,OACpBC,QAA2B,EAC3BC,YAA0B,EAC1BC,OAAuB;IAEvBA,SAAS,aAAa;IAC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;QACAmD;QACAM;QACAF;QACA,SAASM,UACL;YACE,GAAGhE,OAAO;YACV,SAAS,CAACkE;gBACRN,cAAc,cAAc;gBAC5BG,iBAAiB;gBACjBC,QAAQE;YACV;QACF,IACAlE;IACN;IACA,IAAI;QACF,OAAO,MAAMiB,AAAAA,IAAAA,4CAAAA,kBAAAA,AAAAA,EAAmB2C,eAAe,IAC7C5C,AAAsB,iBAAtBA,SAAS,QAAQ,GACbmD,AAAAA,IAAAA,uCAAAA,aAAAA,AAAAA,EAAcF,SAASjD,SAAS,KAAK,IACrCA,AAAsB,YAAtBA,SAAS,QAAQ,GACfoD,AAAAA,IAAAA,8BAAAA,SAAAA,AAAAA,EAAUH,SAASjD,SAAS,KAAK,IACjCqD,AAAAA,IAAAA,+BAAAA,UAAAA,AAAAA,EAAWJ,SAASjD;IAE9B,EAAE,OAAO+B,OAAO;QACd/C,SAAS,aAAa;QACtB,MAAMgD,YAAYC,AAAAA,IAAAA,kCAAAA,OAAAA,AAAAA,EAAQF;QAC1B,IAAIgB,gBACF,MAAM,IAAI5B,2BAA2Ba;QAEvC,MAAMA;IACR,SAAU;QACRa;IACF;AACF"}
|
|
@@ -94,10 +94,15 @@ async function callOpenAI({ modelRuntime, options, executionId, recordEvent, req
|
|
|
94
94
|
error: error instanceof Error ? error.message : String(error)
|
|
95
95
|
});
|
|
96
96
|
(0, logger_namespaceObject.getDebug)('ai:call', {
|
|
97
|
-
console: true
|
|
97
|
+
console: true,
|
|
98
|
+
warning: {
|
|
99
|
+
kind: 'model-request-detail',
|
|
100
|
+
modelName,
|
|
101
|
+
error
|
|
102
|
+
}
|
|
98
103
|
})('call AI error', error);
|
|
99
104
|
if (error instanceof external_utils_js_namespaceObject.AIResponseParseError) throw error;
|
|
100
|
-
throw new Error(`failed to call ${isStreaming ? 'streaming ' : ''}AI model service (${modelName}): ${error.message}${(0, external_openai_request_context_js_namespaceObject.formatOpenAIAPIErrorDetails)(error, openAIRequestContext)}\nTrouble shooting: https://midscenejs.com/model-
|
|
105
|
+
throw new Error(`failed to call ${isStreaming ? 'streaming ' : ''}AI model service (${modelName}): ${error.message}${(0, external_openai_request_context_js_namespaceObject.formatOpenAIAPIErrorDetails)(error, openAIRequestContext)}\nTrouble shooting: https://midscenejs.com/model-config#verify-model-connectivity`, {
|
|
101
106
|
cause: error
|
|
102
107
|
});
|
|
103
108
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ai-model/service-caller/openai/call-openai.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../../../src/ai-model/service-caller/openai/call-openai.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import { getDebug } from '@midscene/shared/logger';\nimport type { ModelCallContext, ModelCallResult } from '../types';\nimport { AIResponseParseError } from '../utils';\nimport {\n callChatCompletion,\n type prepareChatCompletion,\n} from './chat-completion/chat-completion';\nimport { createClient } from './openai-client';\nimport { formatOpenAIAPIErrorDetails } from './openai-request-context';\nimport { callResponses, type prepareResponses } from './responses/responses';\n\nexport type PreparedOpenAIInput =\n | {\n protocol: 'chat-completion';\n input: Awaited<ReturnType<typeof prepareChatCompletion>>;\n }\n | {\n protocol: 'responses';\n input: Awaited<ReturnType<typeof prepareResponses>>;\n };\n\nexport async function callOpenAI(\n {\n modelRuntime,\n options,\n executionId,\n recordEvent,\n requestSignal,\n effectiveTimeoutMs,\n }: ModelCallContext,\n prepared: PreparedOpenAIInput,\n): Promise<ModelCallResult> {\n const { config: modelConfig } = modelRuntime;\n const { modelName } = modelConfig;\n const isStreaming = options?.stream ?? modelConfig.streamMode === 'stream';\n const { openai, openAIRequestContext } = await createClient({\n modelConfig,\n proxyAgent: prepared.input.proxyAgent,\n effectiveTimeoutMs,\n executionId,\n recordEvent,\n });\n const debugCall = getDebug('ai:call');\n debugCall(\n `sending ${isStreaming ? 'streaming ' : ''}request to ${modelName}`,\n );\n const requestOptions = {\n requestSignal,\n openAIRequestContext,\n onChunk: options?.onChunk ?? (() => undefined),\n recordEvent,\n };\n try {\n const startTime = Date.now();\n const response =\n prepared.protocol === 'responses'\n ? await callResponses(\n {\n ...requestOptions,\n responses: openai.responses,\n requestBodyParams: prepared.input.requestParams,\n },\n isStreaming,\n )\n : await callChatCompletion(\n {\n ...requestOptions,\n completion: openai.chat.completions,\n requestBodyParams: prepared.input.requestParams,\n extractContentAndReasoning:\n prepared.input.extractContentAndReasoning,\n useReasoningAsContentFallback:\n prepared.input.useReasoningAsContentFallback,\n },\n isStreaming,\n );\n const { reasoningContent, ...result } = response;\n requestSignal.throwIfAborted();\n const timeCost = Date.now() - startTime;\n debugCall(`response reasoning content: ${reasoningContent}`);\n debugCall(`response content: ${result.content}`);\n recordEvent?.({\n type: 'response',\n http: openAIRequestContext.httpResponse,\n final: {\n content: result.content,\n reasoningContent,\n usage: result.rawUsage,\n requestId: result.requestId,\n timeCost,\n responseModelName: result.responseModelName,\n },\n });\n return {\n ...result,\n reasoning_content: reasoningContent,\n isStreamed: isStreaming,\n timeCost,\n };\n } catch (error: any) {\n // Fetch already records non-2xx responses. Preserve successful HTTP\n // responses too when SDK parsing or completion validation fails.\n if (openAIRequestContext.httpResponse?.ok) {\n recordEvent?.({\n type: 'error',\n ...openAIRequestContext.httpResponse,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n getDebug('ai:call', {
|
|
1
|
+
{"version":3,"file":"ai-model/service-caller/openai/call-openai.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../../../src/ai-model/service-caller/openai/call-openai.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import { getDebug } from '@midscene/shared/logger';\nimport type { ModelCallContext, ModelCallResult } from '../types';\nimport { AIResponseParseError } from '../utils';\nimport {\n callChatCompletion,\n type prepareChatCompletion,\n} from './chat-completion/chat-completion';\nimport { createClient } from './openai-client';\nimport { formatOpenAIAPIErrorDetails } from './openai-request-context';\nimport { callResponses, type prepareResponses } from './responses/responses';\n\nexport type PreparedOpenAIInput =\n | {\n protocol: 'chat-completion';\n input: Awaited<ReturnType<typeof prepareChatCompletion>>;\n }\n | {\n protocol: 'responses';\n input: Awaited<ReturnType<typeof prepareResponses>>;\n };\n\nexport async function callOpenAI(\n {\n modelRuntime,\n options,\n executionId,\n recordEvent,\n requestSignal,\n effectiveTimeoutMs,\n }: ModelCallContext,\n prepared: PreparedOpenAIInput,\n): Promise<ModelCallResult> {\n const { config: modelConfig } = modelRuntime;\n const { modelName } = modelConfig;\n const isStreaming = options?.stream ?? modelConfig.streamMode === 'stream';\n const { openai, openAIRequestContext } = await createClient({\n modelConfig,\n proxyAgent: prepared.input.proxyAgent,\n effectiveTimeoutMs,\n executionId,\n recordEvent,\n });\n const debugCall = getDebug('ai:call');\n debugCall(\n `sending ${isStreaming ? 'streaming ' : ''}request to ${modelName}`,\n );\n const requestOptions = {\n requestSignal,\n openAIRequestContext,\n onChunk: options?.onChunk ?? (() => undefined),\n recordEvent,\n };\n try {\n const startTime = Date.now();\n const response =\n prepared.protocol === 'responses'\n ? await callResponses(\n {\n ...requestOptions,\n responses: openai.responses,\n requestBodyParams: prepared.input.requestParams,\n },\n isStreaming,\n )\n : await callChatCompletion(\n {\n ...requestOptions,\n completion: openai.chat.completions,\n requestBodyParams: prepared.input.requestParams,\n extractContentAndReasoning:\n prepared.input.extractContentAndReasoning,\n useReasoningAsContentFallback:\n prepared.input.useReasoningAsContentFallback,\n },\n isStreaming,\n );\n const { reasoningContent, ...result } = response;\n requestSignal.throwIfAborted();\n const timeCost = Date.now() - startTime;\n debugCall(`response reasoning content: ${reasoningContent}`);\n debugCall(`response content: ${result.content}`);\n recordEvent?.({\n type: 'response',\n http: openAIRequestContext.httpResponse,\n final: {\n content: result.content,\n reasoningContent,\n usage: result.rawUsage,\n requestId: result.requestId,\n timeCost,\n responseModelName: result.responseModelName,\n },\n });\n return {\n ...result,\n reasoning_content: reasoningContent,\n isStreamed: isStreaming,\n timeCost,\n };\n } catch (error: any) {\n // Fetch already records non-2xx responses. Preserve successful HTTP\n // responses too when SDK parsing or completion validation fails.\n if (openAIRequestContext.httpResponse?.ok) {\n recordEvent?.({\n type: 'error',\n ...openAIRequestContext.httpResponse,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n getDebug('ai:call', {\n console: true,\n warning: { kind: 'model-request-detail', modelName, error },\n })('call AI error', error);\n if (error instanceof AIResponseParseError) {\n throw error;\n }\n throw new Error(\n `failed to call ${isStreaming ? 'streaming ' : ''}AI model service (${modelName}): ${error.message}${formatOpenAIAPIErrorDetails(error, openAIRequestContext)}\\nTrouble shooting: https://midscenejs.com/model-config#verify-model-connectivity`,\n { cause: error },\n );\n }\n}\n"],"names":["__webpack_require__","definition","key","Object","obj","prop","Symbol","callOpenAI","modelRuntime","options","executionId","recordEvent","requestSignal","effectiveTimeoutMs","prepared","modelConfig","modelName","isStreaming","openai","openAIRequestContext","createClient","debugCall","getDebug","requestOptions","undefined","startTime","Date","response","callResponses","callChatCompletion","reasoningContent","result","timeCost","error","Error","String","AIResponseParseError","formatOpenAIAPIErrorDetails"],"mappings":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBAAoB,CAAC,CAAC,UAASE,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAF,oBAAoB,CAAC,GAAG,CAACI,KAAKC,OAAUF,OAAO,SAAS,CAAC,cAAc,CAAC,IAAI,CAACC,KAAKC;;;ICClFL,oBAAoB,CAAC,GAAG,CAAC;QACxB,IAAG,AAAkB,eAAlB,OAAOM,UAA0BA,OAAO,WAAW,EACrDH,OAAO,cAAc,CAAC,UAASG,OAAO,WAAW,EAAE;YAAE,OAAO;QAAS;QAEtEH,OAAO,cAAc,CAAC,UAAS,cAAc;YAAE,OAAO;QAAK;IAC5D;;;;;;;;;;;;;ACeO,eAAeI,WACpB,EACEC,YAAY,EACZC,OAAO,EACPC,WAAW,EACXC,WAAW,EACXC,aAAa,EACbC,kBAAkB,EACD,EACnBC,QAA6B;IAE7B,MAAM,EAAE,QAAQC,WAAW,EAAE,GAAGP;IAChC,MAAM,EAAEQ,SAAS,EAAE,GAAGD;IACtB,MAAME,cAAcR,SAAS,UAAUM,AAA2B,aAA3BA,YAAY,UAAU;IAC7D,MAAM,EAAEG,MAAM,EAAEC,oBAAoB,EAAE,GAAG,MAAMC,AAAAA,IAAAA,0CAAAA,YAAAA,AAAAA,EAAa;QAC1DL;QACA,YAAYD,SAAS,KAAK,CAAC,UAAU;QACrCD;QACAH;QACAC;IACF;IACA,MAAMU,YAAYC,AAAAA,IAAAA,uBAAAA,QAAAA,AAAAA,EAAS;IAC3BD,UACE,CAAC,QAAQ,EAAEJ,cAAc,eAAe,GAAG,WAAW,E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AAGE,OAAOF;QACzD;QAEFX,IAAAA,uBAAAA,QAAAA,AAAAA,EAAS,WAAW;YAClB,SAAS;YACT,SAAS;gBAAE,MAAM;gBAAwBN;gBAAWiB;YAAM;QAC5D,GAAG,iBAAiBA;QACpB,IAAIA,iBAAiBG,kCAAAA,oBAAoBA,EACvC,MAAMH;QAER,MAAM,IAAIC,MACR,CAAC,eAAe,EAAEjB,cAAc,eAAe,GAAG,kBAAkB,EAAED,UAAU,GAAG,EAAEiB,MAAM,OAAO,GAAGI,AAAAA,IAAAA,mDAAAA,2BAAAA,AAAAA,EAA4BJ,OAAOd,sBAAsB,iFAAiF,CAAC,EAChP;YAAE,OAAOc;QAAM;IAEnB;AACF"}
|
|
@@ -27,7 +27,7 @@ __webpack_require__.d(__webpack_exports__, {
|
|
|
27
27
|
modelFamilyRequiredForLocateMessage: ()=>modelFamilyRequiredForLocateMessage,
|
|
28
28
|
planningModelFamilyRequiredForLocateMessage: ()=>planningModelFamilyRequiredForLocateMessage
|
|
29
29
|
});
|
|
30
|
-
const modelConfigDocUrl = 'https://midscenejs.com/model-config';
|
|
30
|
+
const modelConfigDocUrl = 'https://midscenejs.com/model-config#common-configuration-errors';
|
|
31
31
|
function modelFamilyRequiredForLocateMessage(slot) {
|
|
32
32
|
const role = 'locate' === slot ? 'Locate' : 'Default';
|
|
33
33
|
const configKey = 'locate' === slot ? 'MIDSCENE_LOCATE_MODEL_FAMILY' : 'MIDSCENE_MODEL_FAMILY';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ai-model/shared/model-locate-result/errors.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../../../src/ai-model/shared/model-locate-result/errors.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","const modelConfigDocUrl
|
|
1
|
+
{"version":3,"file":"ai-model/shared/model-locate-result/errors.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../../../src/ai-model/shared/model-locate-result/errors.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","const modelConfigDocUrl =\n 'https://midscenejs.com/model-config#common-configuration-errors';\n\nexport function modelFamilyRequiredForLocateMessage(slot?: string) {\n const role = slot === 'locate' ? 'Locate' : 'Default';\n const configKey =\n slot === 'locate'\n ? 'MIDSCENE_LOCATE_MODEL_FAMILY'\n : 'MIDSCENE_MODEL_FAMILY';\n return `${role} model family is required for locate. Configure ${configKey} so Midscene can parse locate coordinates correctly. ${modelConfigDocUrl}`;\n}\n\nexport function planningModelFamilyRequiredForLocateMessage(slot?: string) {\n if (slot === 'planning') {\n return `Planning model family is required because aiAct is asking the planning model to return locate coordinates. Configure MIDSCENE_PLANNING_MODEL_FAMILY for the planning model, or remove the separate planning model config and configure MIDSCENE_MODEL_FAMILY on the default model. ${modelConfigDocUrl}`;\n }\n\n return `Default model family is required because aiAct is asking the default model to return locate coordinates during planning. Configure MIDSCENE_MODEL_FAMILY so Midscene can parse planning locate coordinates correctly. ${modelConfigDocUrl}`;\n}\n"],"names":["__webpack_require__","definition","key","Object","obj","prop","Symbol","modelConfigDocUrl","modelFamilyRequiredForLocateMessage","slot","role","configKey","planningModelFamilyRequiredForLocateMessage"],"mappings":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBAAoB,CAAC,CAAC,UAASE,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAF,oBAAoB,CAAC,GAAG,CAACI,KAAKC,OAAUF,OAAO,SAAS,CAAC,cAAc,CAAC,IAAI,CAACC,KAAKC;;;ICClFL,oBAAoB,CAAC,GAAG,CAAC;QACxB,IAAG,AAAkB,eAAlB,OAAOM,UAA0BA,OAAO,WAAW,EACrDH,OAAO,cAAc,CAAC,UAASG,OAAO,WAAW,EAAE;YAAE,OAAO;QAAS;QAEtEH,OAAO,cAAc,CAAC,UAAS,cAAc;YAAE,OAAO;QAAK;IAC5D;;;;;;;;ACNA,MAAMI,oBACJ;AAEK,SAASC,oCAAoCC,IAAa;IAC/D,MAAMC,OAAOD,AAAS,aAATA,OAAoB,WAAW;IAC5C,MAAME,YACJF,AAAS,aAATA,OACI,iCACA;IACN,OAAO,GAAGC,KAAK,gDAAgD,EAAEC,UAAU,qDAAqD,EAAEJ,mBAAmB;AACvJ;AAEO,SAASK,4CAA4CH,IAAa;IACvE,IAAIA,AAAS,eAATA,MACF,OAAO,CAAC,mRAAmR,EAAEF,mBAAmB;IAGlT,OAAO,CAAC,sNAAsN,EAAEA,mBAAmB;AACrP"}
|
|
@@ -39,7 +39,11 @@ function parseCoordinateList(input, label) {
|
|
|
39
39
|
const unwrapped = unwrapCoordinateListLikeInput(input);
|
|
40
40
|
const values = 'string' == typeof unwrapped ? unwrapped.trim().split(/[\s,]+/).filter(Boolean) : unwrapped;
|
|
41
41
|
if (!Array.isArray(values)) throw new Error(`invalid ${label} data: ${JSON.stringify(input)} `);
|
|
42
|
-
const numericValues = values.map((value)=>
|
|
42
|
+
const numericValues = values.map((value)=>{
|
|
43
|
+
if ('number' == typeof value) return value;
|
|
44
|
+
if ('string' != typeof value || !/^[+-]?(?:\d+\.?\d*|\.\d+)$/.test(value.trim())) return NaN;
|
|
45
|
+
return Number(value);
|
|
46
|
+
});
|
|
43
47
|
if (!numericValues.every((value)=>Number.isFinite(value))) throw new Error(`invalid ${label} data: ${JSON.stringify(input)} `);
|
|
44
48
|
return numericValues;
|
|
45
49
|
}
|
|
@@ -64,7 +68,7 @@ function createLocateResultValue(coordinatesMeta, coordinates) {
|
|
|
64
68
|
function parseNumericLocateResult(resolvedCoordinates, input) {
|
|
65
69
|
if ('point' === resolvedCoordinates.shape) {
|
|
66
70
|
const point = parseCoordinateList(input, 'point');
|
|
67
|
-
if (point.length
|
|
71
|
+
if (2 !== point.length) throw new Error(`invalid point data: ${JSON.stringify(input)} `);
|
|
68
72
|
return createLocateResultValue(resolvedCoordinates, point);
|
|
69
73
|
}
|
|
70
74
|
const bbox = parseCoordinateList(input, 'bbox');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ai-model/shared/model-locate-result/parse.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../../../src/ai-model/shared/model-locate-result/parse.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import type {\n BboxLocateResultCoordinates,\n BboxLocateResultValue,\n LocateResultBbox,\n LocateResultPoint,\n LocateResultValue,\n PointLocateResultCoordinates,\n PointLocateResultValue,\n ResolvedLocateResultCoordinates,\n} from './types';\n\ntype CoordinateListLikeInput =\n | number[]\n | string[]\n | string\n | (number[] | string[])[];\n\nexport function unwrapCoordinateListLikeInput(\n coordinateList: CoordinateListLikeInput,\n): number[] | string[] | string {\n if (Array.isArray(coordinateList)) {\n if (Array.isArray(coordinateList[0])) {\n return coordinateList[0] as number[] | string[];\n }\n return coordinateList as number[] | string[];\n }\n return coordinateList as string;\n}\n\nexport function parseCoordinateList(input: unknown, label: string): number[] {\n const unwrapped = unwrapCoordinateListLikeInput(\n input as CoordinateListLikeInput,\n );\n const values =\n typeof unwrapped === 'string'\n ? unwrapped\n .trim()\n .split(/[\\s,]+/)\n .filter(Boolean)\n : unwrapped;\n\n if (!Array.isArray(values)) {\n throw new Error(`invalid ${label} data: ${JSON.stringify(input)} `);\n }\n\n const numericValues = values.map((value)
|
|
1
|
+
{"version":3,"file":"ai-model/shared/model-locate-result/parse.js","sources":["webpack/runtime/define_property_getters","webpack/runtime/has_own_property","webpack/runtime/make_namespace_object","../../../../../src/ai-model/shared/model-locate-result/parse.ts"],"sourcesContent":["__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n }\n }\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","import type {\n BboxLocateResultCoordinates,\n BboxLocateResultValue,\n LocateResultBbox,\n LocateResultPoint,\n LocateResultValue,\n PointLocateResultCoordinates,\n PointLocateResultValue,\n ResolvedLocateResultCoordinates,\n} from './types';\n\ntype CoordinateListLikeInput =\n | number[]\n | string[]\n | string\n | (number[] | string[])[];\n\nexport function unwrapCoordinateListLikeInput(\n coordinateList: CoordinateListLikeInput,\n): number[] | string[] | string {\n if (Array.isArray(coordinateList)) {\n if (Array.isArray(coordinateList[0])) {\n return coordinateList[0] as number[] | string[];\n }\n return coordinateList as number[] | string[];\n }\n return coordinateList as string;\n}\n\nexport function parseCoordinateList(input: unknown, label: string): number[] {\n const unwrapped = unwrapCoordinateListLikeInput(\n input as CoordinateListLikeInput,\n );\n const values =\n typeof unwrapped === 'string'\n ? unwrapped\n .trim()\n .split(/[\\s,]+/)\n .filter(Boolean)\n : unwrapped;\n\n if (!Array.isArray(values)) {\n throw new Error(`invalid ${label} data: ${JSON.stringify(input)} `);\n }\n\n const numericValues = values.map((value) => {\n if (typeof value === 'number') {\n return value;\n }\n if (\n typeof value !== 'string' ||\n !/^[+-]?(?:\\d+\\.?\\d*|\\.\\d+)$/.test(value.trim())\n ) {\n return Number.NaN;\n }\n return Number(value);\n });\n\n if (!numericValues.every((value) => Number.isFinite(value))) {\n throw new Error(`invalid ${label} data: ${JSON.stringify(input)} `);\n }\n\n return numericValues;\n}\n\nexport function createLocateResultValue(\n coordinatesMeta: PointLocateResultCoordinates,\n coordinates: number[],\n): PointLocateResultValue;\nexport function createLocateResultValue(\n coordinatesMeta: BboxLocateResultCoordinates,\n coordinates: number[],\n): BboxLocateResultValue;\nexport function createLocateResultValue(\n coordinatesMeta: ResolvedLocateResultCoordinates,\n coordinates: number[],\n): LocateResultValue {\n if (coordinatesMeta.shape === 'point') {\n return {\n coordinates: [coordinates[0], coordinates[1]] as LocateResultPoint,\n coordinatesMeta,\n };\n }\n\n return {\n coordinates: [\n coordinates[0],\n coordinates[1],\n coordinates[2],\n coordinates[3],\n ] as LocateResultBbox,\n coordinatesMeta,\n };\n}\n\nexport function parseNumericLocateResult(\n resolvedCoordinates: ResolvedLocateResultCoordinates,\n input: unknown,\n): LocateResultValue {\n if (resolvedCoordinates.shape === 'point') {\n const point = parseCoordinateList(input, 'point');\n if (point.length !== 2) {\n throw new Error(`invalid point data: ${JSON.stringify(input)} `);\n }\n return createLocateResultValue(resolvedCoordinates, point);\n }\n\n const bbox = parseCoordinateList(input, 'bbox');\n if (bbox.length !== 4) {\n throw new Error(`invalid bbox data: ${JSON.stringify(input)} `);\n }\n\n return createLocateResultValue(resolvedCoordinates, bbox);\n}\n"],"names":["__webpack_require__","definition","key","Object","obj","prop","Symbol","unwrapCoordinateListLikeInput","coordinateList","Array","parseCoordinateList","input","label","unwrapped","values","Boolean","Error","JSON","numericValues","value","Number","createLocateResultValue","coordinatesMeta","coordinates","parseNumericLocateResult","resolvedCoordinates","point","bbox"],"mappings":";;;IAAAA,oBAAoB,CAAC,GAAG,CAAC,UAASC;QACjC,IAAI,IAAIC,OAAOD,WACR,IAAGD,oBAAoB,CAAC,CAACC,YAAYC,QAAQ,CAACF,oBAAoB,CAAC,CAAC,UAASE,MACzEC,OAAO,cAAc,CAAC,UAASD,KAAK;YAAE,YAAY;YAAM,KAAKD,UAAU,CAACC,IAAI;QAAC;IAGzF;;;ICNAF,oBAAoB,CAAC,GAAG,CAACI,KAAKC,OAAUF,OAAO,SAAS,CAAC,cAAc,CAAC,IAAI,CAACC,KAAKC;;;ICClFL,oBAAoB,CAAC,GAAG,CAAC;QACxB,IAAG,AAAkB,eAAlB,OAAOM,UAA0BA,OAAO,WAAW,EACrDH,OAAO,cAAc,CAAC,UAASG,OAAO,WAAW,EAAE;YAAE,OAAO;QAAS;QAEtEH,OAAO,cAAc,CAAC,UAAS,cAAc;YAAE,OAAO;QAAK;IAC5D;;;;;;;;;;ACWO,SAASI,8BACdC,cAAuC;IAEvC,IAAIC,MAAM,OAAO,CAACD,iBAChB;QA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QhB,oBAAoBC,OAAO;QACzC,IAAIe,AAAiB,MAAjBA,MAAM,MAAM,EACd,MAAM,IAAIV,MAAM,CAAC,oBAAoB,EAAEC,KAAK,SAAS,CAACN,OAAO,CAAC,CAAC;QAEjE,OAAOU,wBAAwBI,qBAAqBC;IACtD;IAEA,MAAMC,OAAOjB,oBAAoBC,OAAO;IACxC,IAAIgB,AAAgB,MAAhBA,KAAK,MAAM,EACb,MAAM,IAAIX,MAAM,CAAC,mBAAmB,EAAEC,KAAK,SAAS,CAACN,OAAO,CAAC,CAAC;IAGhE,OAAOU,wBAAwBI,qBAAqBE;AACtD"}
|
package/dist/lib/device/index.js
CHANGED
|
@@ -374,16 +374,20 @@ function createActionSwipeParamSchema(inputMode) {
|
|
|
374
374
|
'left',
|
|
375
375
|
'right'
|
|
376
376
|
]).optional().describe(`${'finger' === movementSource ? 'Finger' : 'Pointer'} movement direction. Required together with a positive distance for a relative swipe. Omit when using end.`),
|
|
377
|
-
distance: external_zod_namespaceObject.z.number().positive().optional().describe(`Positive length of the ${movementSource} movement in pixels. Required together with direction for a relative swipe. Omit when using end.`),
|
|
377
|
+
distance: external_zod_namespaceObject.z.number().finite().positive().optional().describe(`Positive length of the ${movementSource} movement in pixels. Required together with direction for a relative swipe. Omit when using end.`),
|
|
378
378
|
end: (0, external_common_js_namespaceObject.getMidsceneLocationSchema)().optional().describe(`Endpoint of the ${movementSource} movement. Use for an endpoint swipe, optionally with start. Do not provide direction or distance when using end.`),
|
|
379
|
-
duration: external_zod_namespaceObject.z.number().default(300).describe('Duration of the swipe gesture in milliseconds'),
|
|
380
|
-
repeat: external_zod_namespaceObject.z.number().optional().describe('The number of times to repeat the swipe gesture. 1 for default, 0 for
|
|
379
|
+
duration: external_zod_namespaceObject.z.number().finite().positive().default(300).describe('Duration of the swipe gesture in milliseconds'),
|
|
380
|
+
repeat: external_zod_namespaceObject.z.number().finite().int().nonnegative().optional().describe('The number of times to repeat the swipe gesture. 1 for default, 0 for continuous mode capped at 10 repeats')
|
|
381
381
|
});
|
|
382
382
|
}
|
|
383
383
|
const ActionSwipeParamSchema = createActionSwipeParamSchema('touch');
|
|
384
384
|
function normalizeSwipeParam(param, screenSize) {
|
|
385
385
|
const { width, height } = screenSize;
|
|
386
386
|
const { start, end } = param;
|
|
387
|
+
const duration = param.duration ?? 300;
|
|
388
|
+
if (!Number.isFinite(duration) || duration <= 0) throw new Error('duration must be a positive finite number');
|
|
389
|
+
const repeatCount = param.repeat ?? 1;
|
|
390
|
+
if (!Number.isFinite(repeatCount) || !Number.isInteger(repeatCount) || repeatCount < 0) throw new Error('repeat must be a non-negative finite integer');
|
|
387
391
|
const startPoint = start ? {
|
|
388
392
|
x: start.center[0],
|
|
389
393
|
y: start.center[1]
|
|
@@ -400,7 +404,7 @@ function normalizeSwipeParam(param, screenSize) {
|
|
|
400
404
|
};
|
|
401
405
|
}
|
|
402
406
|
if (void 0 === param.direction || void 0 === param.distance) throw new Error('Invalid Swipe parameters: a relative swipe requires both "direction" and a positive "distance".');
|
|
403
|
-
if (param.distance <= 0) throw new Error('Invalid Swipe parameters: "distance" must be a positive number.');
|
|
407
|
+
if (!Number.isFinite(param.distance) || param.distance <= 0) throw new Error('Invalid Swipe parameters: "distance" must be a positive number.');
|
|
404
408
|
return {
|
|
405
409
|
x: startPoint.x + ('right' === param.direction ? param.distance : 'left' === param.direction ? -param.distance : 0),
|
|
406
410
|
y: startPoint.y + ('down' === param.direction ? param.distance : 'up' === param.direction ? -param.distance : 0)
|
|
@@ -408,14 +412,11 @@ function normalizeSwipeParam(param, screenSize) {
|
|
|
408
412
|
})();
|
|
409
413
|
endPoint.x = Math.max(0, Math.min(endPoint.x, width));
|
|
410
414
|
endPoint.y = Math.max(0, Math.min(endPoint.y, height));
|
|
411
|
-
const duration = param.duration ?? 300;
|
|
412
|
-
let repeatCount = 'number' == typeof param.repeat ? param.repeat : 1;
|
|
413
|
-
if (0 === repeatCount) repeatCount = 10;
|
|
414
415
|
return {
|
|
415
416
|
startPoint,
|
|
416
417
|
endPoint,
|
|
417
418
|
duration,
|
|
418
|
-
repeatCount
|
|
419
|
+
repeatCount: 0 === repeatCount ? 10 : repeatCount
|
|
419
420
|
};
|
|
420
421
|
}
|
|
421
422
|
const normalizeMobileSwipeParam = normalizeSwipeParam;
|