@midscene/core 1.17.2-beta-20261027033907.0 → 1.17.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.
Files changed (39) hide show
  1. package/dist/es/agent/tasks.mjs +2 -1
  2. package/dist/es/agent/tasks.mjs.map +1 -1
  3. package/dist/es/agent/utils.mjs +1 -1
  4. package/dist/es/ai-model/models/gemini.mjs +5 -32
  5. package/dist/es/ai-model/models/gemini.mjs.map +1 -1
  6. package/dist/es/ai-model/service-caller/system-one/index.mjs +2 -1
  7. package/dist/es/ai-model/service-caller/system-one/prepare-system-one.mjs +6 -5
  8. package/dist/es/ai-model/service-caller/system-one/prepare-system-one.mjs.map +1 -1
  9. package/dist/es/ai-model/service-caller/system-one/resolve-endpoint.mjs +9 -0
  10. package/dist/es/ai-model/service-caller/system-one/resolve-endpoint.mjs.map +1 -0
  11. package/dist/es/ai-model/service-caller/system-one/utils.mjs.map +1 -1
  12. package/dist/es/report-html-template.mjs +1 -1
  13. package/dist/es/utils.mjs +1 -1
  14. package/dist/lib/agent/tasks.js +2 -1
  15. package/dist/lib/agent/tasks.js.map +1 -1
  16. package/dist/lib/agent/utils.js +1 -1
  17. package/dist/lib/ai-model/models/gemini.js +5 -32
  18. package/dist/lib/ai-model/models/gemini.js.map +1 -1
  19. package/dist/lib/ai-model/service-caller/system-one/index.js +5 -1
  20. package/dist/lib/ai-model/service-caller/system-one/prepare-system-one.js +8 -7
  21. package/dist/lib/ai-model/service-caller/system-one/prepare-system-one.js.map +1 -1
  22. package/dist/lib/ai-model/service-caller/system-one/resolve-endpoint.js +43 -0
  23. package/dist/lib/ai-model/service-caller/system-one/resolve-endpoint.js.map +1 -0
  24. package/dist/lib/ai-model/service-caller/system-one/utils.js.map +1 -1
  25. package/dist/lib/report-html-template.js +1 -1
  26. package/dist/lib/utils.js +1 -1
  27. package/dist/types/agent/tasks.d.ts.map +1 -1
  28. package/dist/types/ai-model/models/gemini.d.ts +2 -14
  29. package/dist/types/ai-model/models/gemini.d.ts.map +1 -1
  30. package/dist/types/ai-model/models/registry.d.ts +1 -15
  31. package/dist/types/ai-model/models/registry.d.ts.map +1 -1
  32. package/dist/types/ai-model/service-caller/system-one/index.d.ts +1 -0
  33. package/dist/types/ai-model/service-caller/system-one/index.d.ts.map +1 -1
  34. package/dist/types/ai-model/service-caller/system-one/prepare-system-one.d.ts +1 -0
  35. package/dist/types/ai-model/service-caller/system-one/prepare-system-one.d.ts.map +1 -1
  36. package/dist/types/ai-model/service-caller/system-one/resolve-endpoint.d.ts +3 -0
  37. package/dist/types/ai-model/service-caller/system-one/resolve-endpoint.d.ts.map +1 -0
  38. package/dist/types/ai-model/service-caller/system-one/utils.d.ts.map +1 -1
  39. package/package.json +2 -2
@@ -8,6 +8,7 @@ import { TaskExecutionError } from "../task-runner.mjs";
8
8
  import { ServiceError, aiActProgressScope } from "../types.mjs";
9
9
  import { getDebug } from "@midscene/shared/logger";
10
10
  import { assert } from "@midscene/shared/utils";
11
+ import { resolveSystemOneEndpoint } from "../ai-model/service-caller/system-one/index.mjs";
11
12
  import { isActionReadinessError } from "./action-readiness.mjs";
12
13
  import { ExecutionSession } from "./execution-session.mjs";
13
14
  import { withFileChooser } from "./file-chooser.mjs";
@@ -222,7 +223,7 @@ class TaskExecutor {
222
223
  const noIndividualLocateModel = 'default' === planningModel.config.slot && 'default' === locateModel.config.slot;
223
224
  const planningConfig = planningModel.config;
224
225
  const locateConfig = locateModel.config;
225
- const sameSystemOneModel = 'system-one' === planningModel.adapter.modelType && 'system-one' === locateModel.adapter.modelType && planningConfig.modelName === locateConfig.modelName && planningConfig.openaiBaseURL === locateConfig.openaiBaseURL;
226
+ const sameSystemOneModel = 'system-one' === planningModel.adapter.modelType && 'system-one' === locateModel.adapter.modelType && planningConfig.modelName === locateConfig.modelName && resolveSystemOneEndpoint(planningConfig) === resolveSystemOneEndpoint(locateConfig);
226
227
  const bothJev = 'jev' === planningConfig.modelFamily && 'jev' === locateConfig.modelFamily;
227
228
  const includeLocateInPlanning = 'deepThink' !== effort && (noIndividualLocateModel || sameSystemOneModel && bothJev);
228
229
  const imagesIncludeCount = 'deepThink' === effort ? 2 : 1;
@@ -1 +1 @@
1
- {"version":3,"file":"agent/tasks.mjs","sources":["../../../src/agent/tasks.ts"],"sourcesContent":["import { AIResponseParseError, ConversationHistory } from '@/ai-model';\nimport type { ModelRuntime } from '@/ai-model/models';\nimport { buildTypeQueryDemandValue } from '@/ai-model/prompt/insight';\nimport { prepareUserPrompt } from '@/ai-model/shared/multimodal-prompt';\nimport { standardPlan } from '@/ai-model/workflows/planning';\nimport {\n type TMultimodalPrompt,\n type TUserPrompt,\n getReadableTimeString,\n userPromptToMultimodalPrompt,\n userPromptToString,\n} from '@/common';\nimport { type AbstractInterface, defineActionSleep } from '@/device';\nimport type Service from '@/service';\nimport type {\n ExecutionReferenceImage,\n TaskRunner,\n TaskRunnerEvent,\n} from '@/task-runner';\nimport { TaskExecutionError } from '@/task-runner';\nimport type {\n AiActEffort,\n AiActProgressData,\n AiActProgressPhase,\n DetailedLocateParam,\n DeviceAction,\n ExecutionRecorderItem,\n ExecutionTask,\n ExecutionTaskApply,\n ExecutionTaskInsightQueryApply,\n ExecutionTaskPlanningApply,\n ExecutionTaskProgressOptions,\n MidsceneYamlFlowItem,\n PlanningAIResponse,\n PlanningAction,\n PlanningActionParamWaitFor,\n ServiceDump,\n ServiceExtractOption,\n ServiceExtractParam,\n UIContext,\n} from '@/types';\nimport { ServiceError, aiActProgressScope } from '@/types';\nimport { getDebug } from '@midscene/shared/logger';\nimport { assert } from '@midscene/shared/utils';\nimport {\n type ActionReadiness,\n isActionReadinessError,\n} from './action-readiness';\nimport { ExecutionSession } from './execution-session';\nimport { withFileChooser } from './file-chooser';\nimport {\n type AgentProgressPublisher,\n createAiActActionReporter,\n errorMessageForAiAct,\n} from './progress';\nimport { renderAIContext } from './prompt-context';\nimport { TaskBuilder } from './task-builder';\nimport type { TaskCache } from './task-cache';\nexport { locatePlanForLocate } from './task-builder';\nimport { setTimingFieldOnce } from '@/task-timing';\nimport { descriptionOfTree } from '@midscene/shared/extractor';\nimport { type TaskTitleType, taskTitleStr } from './ui-utils';\nimport { withUsageIntent } from './usage-intent';\nimport { parsePrompt } from './utils';\n\ninterface ExecutionResult<OutputType = any> {\n output: OutputType;\n thought?: string;\n runner: TaskRunner;\n}\n\ninterface TaskExecutorHooks {\n onExecutionCreated?: (runner: TaskRunner) => void;\n onSnapshotChange?: (\n runner: TaskRunner,\n error?: TaskExecutionError,\n ) => Promise<void> | void;\n // Publish onto the agent's progress bus. The bus owns sequencing, so the\n // executor is a pure producer: it names the scope/phase and hands over data.\n onProgress?: AgentProgressPublisher;\n}\n\nexport type ActionReportOptions = {\n type?: TaskTitleType;\n prompt?: string;\n};\n\nconst debug = getDebug('device-task-executor');\nconst warnLog = getDebug('device-task-executor', { console: true });\nconst maxErrorCountAllowedInOnePlanningLoop = 5;\n\n// Cap planning feedback by default so a large action output (e.g. a long adb\n// shell stdout) cannot blow up the next planning request's context. Actions\n// that require lossless structured feedback can explicitly choose their limit.\nconst maxPlanningFeedbackLength = 500;\n\nfunction truncatePlanningFeedback(\n feedback: string,\n requestedLimit?: number | 'unlimited',\n): string {\n if (requestedLimit === 'unlimited') {\n return feedback;\n }\n const limit =\n requestedLimit && Number.isFinite(requestedLimit) && requestedLimit > 0\n ? Math.floor(requestedLimit)\n : maxPlanningFeedbackLength;\n if (feedback.length <= limit) {\n return feedback;\n }\n\n return `${feedback.slice(0, limit)}\n...[truncated, ${feedback.length - limit} more characters]`;\n}\n\nexport { TaskExecutionError };\nexport { withFileChooser } from './file-chooser';\n\nexport class TaskExecutor {\n interface: AbstractInterface;\n\n service: Service;\n\n taskCache?: TaskCache;\n\n private readonly getDefaultModelRuntime: () => ModelRuntime;\n private readonly providedActionSpace: DeviceAction[];\n\n private readonly taskBuilder: TaskBuilder;\n\n onTaskStartCallback?: ExecutionTaskProgressOptions['onTaskStart'];\n\n private readonly hooks?: TaskExecutorHooks;\n private readonly getAbortSignal?: () => AbortSignal | undefined;\n\n replanningCycleLimit?: number;\n\n waitAfterAction?: number;\n\n useDeviceTime?: boolean;\n\n // @deprecated use .interface instead\n get page() {\n return this.interface;\n }\n\n constructor(\n interfaceInstance: AbstractInterface,\n service: Service,\n opts: {\n taskCache?: TaskCache;\n getDefaultModelRuntime: () => ModelRuntime;\n onTaskStart?: ExecutionTaskProgressOptions['onTaskStart'];\n replanningCycleLimit?: number;\n waitAfterAction?: number;\n actionReadiness?: ActionReadiness;\n useDeviceTime?: boolean;\n hooks?: TaskExecutorHooks;\n getAbortSignal?: () => AbortSignal | undefined;\n operationResource?: object;\n actionSpace: DeviceAction[];\n },\n ) {\n this.getDefaultModelRuntime = opts.getDefaultModelRuntime;\n this.interface = interfaceInstance;\n this.service = service;\n this.taskCache = opts.taskCache;\n this.onTaskStartCallback = opts?.onTaskStart;\n this.replanningCycleLimit = opts.replanningCycleLimit;\n this.waitAfterAction = opts.waitAfterAction;\n this.useDeviceTime = opts.useDeviceTime;\n this.hooks = opts.hooks;\n this.getAbortSignal = opts.getAbortSignal;\n this.providedActionSpace = opts.actionSpace;\n this.taskBuilder = new TaskBuilder({\n getDefaultModelRuntime: opts.getDefaultModelRuntime,\n interfaceInstance,\n service,\n taskCache: opts.taskCache,\n actionSpace: this.getActionSpace(),\n waitAfterAction: opts.waitAfterAction,\n actionReadiness: opts.actionReadiness,\n operationResource: opts.operationResource,\n });\n }\n\n private createExecutionSession(\n title: string,\n options?: {\n tasks?: ExecutionTaskApply[];\n abortSignal?: AbortSignal;\n uiContext?: UIContext;\n referenceImages?: readonly ExecutionReferenceImage[];\n onSnapshotChange?: (\n runner: TaskRunner,\n error?: TaskExecutionError,\n ) => Promise<void> | void;\n onTaskEvent?: (event: TaskRunnerEvent) => Promise<void> | void;\n },\n ) {\n const session = new ExecutionSession(\n title,\n (signal) =>\n options?.uiContext\n ? Promise.resolve(options.uiContext)\n : Promise.resolve(this.service.contextRetrieverFn(signal)),\n {\n abortSignal: options?.abortSignal ?? this.getAbortSignal?.(),\n onTaskStart: this.onTaskStartCallback,\n tasks: options?.tasks,\n referenceImages: options?.referenceImages,\n onSnapshotChange: async (runner, error) => {\n await this.hooks?.onSnapshotChange?.(runner, error);\n await options?.onSnapshotChange?.(runner, error);\n },\n ...(options?.onTaskEvent ? { onTaskEvent: options.onTaskEvent } : {}),\n },\n );\n this.hooks?.onExecutionCreated?.(session.getRunner());\n return session;\n }\n\n private getActionSpace(): DeviceAction[] {\n return this.providedActionSpace;\n }\n\n /**\n * Publish one event onto the agent's progress bus. The task layer is a pure\n * producer here: it names the scope/phase and forwards the structured\n * payload; the bus stamps the sequence and isolates listener errors. It has\n * no knowledge of how the event is rendered or consumed.\n */\n private async emitProgress(\n scope: string,\n phase: string,\n data: unknown,\n ): Promise<void> {\n await this.hooks?.onProgress?.(scope, phase, data);\n }\n\n /**\n * aiAct-flavored convenience over {@link emitProgress}: aiAct is the first\n * producer (\"pilot\") on the generic bus, so its events are simply tagged with\n * the `aiAct` scope.\n */\n private emitAiActProgress(\n phase: AiActProgressPhase,\n data: AiActProgressData,\n ): Promise<void> {\n return this.emitProgress(aiActProgressScope, phase, data);\n }\n\n /**\n * Set the pending feedback message consumed by the next planning round.\n * The message is always prefixed with the current time. When a body is\n * provided it is appended after the timestamp; otherwise only the time\n * context is recorded. This is the single entry point for writing\n * `pendingFeedbackMessage` so the time prefix stays consistent.\n */\n private setPendingFeedbackMessage(\n conversationHistory: ConversationHistory,\n timeString: string,\n body?: string,\n ) {\n conversationHistory.pendingFeedbackMessage = body\n ? `Time: ${timeString}, ${body}`\n : `Current time: ${timeString}`;\n }\n\n /**\n * Collect feedback produced by executed tasks for the next planning round.\n * Returns undefined when no task reported feedback.\n */\n private collectPlanningFeedback(tasks: ExecutionTask[]): string | undefined {\n const feedbackMessages = tasks.flatMap(\n ({ planningFeedback, planningFeedbackMaxLength }) =>\n planningFeedback\n ? [\n truncatePlanningFeedback(\n planningFeedback,\n planningFeedbackMaxLength,\n ),\n ]\n : [],\n );\n return feedbackMessages.length > 0\n ? feedbackMessages.join('\\n\\n')\n : undefined;\n }\n\n /**\n * Get a readable time string. When device time is enabled, use the\n * device-formatted wall-clock time directly so host timezone formatting does\n * not reinterpret a device timestamp.\n * @param format - Optional format string\n * @returns A formatted time string\n */\n private async getTimeString(format?: string): Promise<string> {\n if (this.useDeviceTime) {\n if (this.interface.getDeviceLocalTimeString) {\n try {\n return await this.interface.getDeviceLocalTimeString(format);\n } catch (error) {\n warnLog(\n `Failed to get device time string, falling back to runtime time: ${error}`,\n );\n }\n } else {\n warnLog(\n 'useDeviceTime is enabled but getDeviceLocalTimeString is not implemented, falling back to runtime time.',\n );\n }\n }\n\n return getReadableTimeString(format);\n }\n\n public async convertPlanToExecutable(\n plans: PlanningAction[],\n planningModel: ModelRuntime,\n locateModel: ModelRuntime,\n options?: {\n cacheable?: boolean;\n multimodalPrompt?: TMultimodalPrompt;\n deepLocate?: boolean;\n abortSignal?: AbortSignal;\n },\n ) {\n return this.taskBuilder.build(plans, planningModel, locateModel, options);\n }\n\n async loadYamlFlowAsPlanning(\n userInstruction: TUserPrompt,\n yamlString: string,\n reportOptions?: ActionReportOptions,\n ) {\n const session = this.createExecutionSession(\n taskTitleStr(\n reportOptions?.type || 'Act',\n reportOptions?.prompt || userPromptToString(userInstruction),\n ),\n {\n referenceImages: userPromptToMultimodalPrompt(userInstruction)?.images,\n },\n );\n\n const task: ExecutionTaskPlanningApply = {\n type: 'Planning',\n subType: 'LoadYaml',\n param: {\n userInstruction,\n ...(reportOptions?.prompt\n ? { userInstructionDisplay: reportOptions.prompt }\n : {}),\n },\n executor: async (executorContext) => {\n const { uiContext } = executorContext;\n assert(uiContext, 'uiContext is required for Planning task');\n return {\n output: {\n actions: [],\n shouldContinuePlanning: false,\n log: '',\n yamlString,\n },\n cache: {\n hit: true,\n },\n hitBy: {\n from: 'Cache',\n context: {\n yamlString,\n },\n },\n };\n },\n };\n const runner = session.getRunner();\n await session.appendAndRun(task);\n\n return {\n runner,\n };\n }\n\n async sleep(ms: number, abortSignal?: AbortSignal): Promise<void> {\n abortSignal ??= this.getAbortSignal?.();\n const session = this.createExecutionSession('Sleep', { abortSignal });\n const action = defineActionSleep(abortSignal);\n await session.appendAndRun({\n type: 'Action Space',\n subType: action.name,\n param: { timeMs: ms },\n executor: async ({ task }) => {\n assert(\n Number.isFinite(ms) && ms > 0,\n `ms for sleep must be a finite number greater than 0, but got ${ms}`,\n );\n setTimingFieldOnce(task.timing, 'callActionStart');\n try {\n await action.call({ timeMs: ms });\n } finally {\n setTimingFieldOnce(task.timing, 'callActionEnd');\n }\n },\n });\n }\n\n async runPlans(\n title: string,\n plans: PlanningAction[],\n planningModel: ModelRuntime,\n locateModel: ModelRuntime,\n options?: { uiContext?: UIContext; abortSignal?: AbortSignal },\n ): Promise<ExecutionResult> {\n const abortSignal = options?.abortSignal ?? this.getAbortSignal?.();\n const session = this.createExecutionSession(title, {\n ...options,\n abortSignal,\n });\n const runner = session.getRunner();\n const executionPlanningModel = { ...planningModel, executionId: runner.id };\n const executionLocateModel = { ...locateModel, executionId: runner.id };\n const { tasks } = await this.convertPlanToExecutable(\n plans,\n executionPlanningModel,\n executionLocateModel,\n { abortSignal },\n );\n const result = await session.appendAndRun(tasks);\n const { output } = result ?? {};\n return {\n output,\n runner,\n };\n }\n\n async action(\n userPrompt: TUserPrompt,\n planningModel: ModelRuntime,\n locateModel: ModelRuntime,\n aiActContext?: string,\n cacheable?: boolean,\n replanningCycleLimitOverride?: number,\n effort: AiActEffort = 'balance',\n fileChooserAccept?: string[],\n deepLocate?: boolean,\n abortSignal?: AbortSignal,\n reportOptions?: ActionReportOptions,\n ): Promise<\n ExecutionResult<\n | {\n yamlFlow?: MidsceneYamlFlowItem[]; // for cache use\n output?: string;\n }\n | undefined\n >\n > {\n abortSignal?.throwIfAborted();\n return withFileChooser(this.interface, fileChooserAccept, async () => {\n return this.runAction(\n userPrompt,\n planningModel,\n locateModel,\n aiActContext,\n cacheable,\n replanningCycleLimitOverride,\n effort,\n deepLocate,\n abortSignal,\n reportOptions,\n );\n });\n }\n\n /**\n * Called when the task is about to replan. Marks every cache-hit locate task\n * in the just-run batch (tasks at index >= fromIndex) as stale: that batch\n * did not finish the task, so the element each cache hit produced is suspect.\n * The upcoming re-locate of the same prompt then replaces the bad entry in\n * place instead of appending a duplicate that would re-poison the cache on the\n * next run (#2529).\n *\n * Marking a locate that was actually fine is harmless: the step is only ever\n * replaced if the same prompt is located again (i.e. the step is redone),\n * which does not happen for a locate that already succeeded.\n */\n private invalidateFailedCacheHitLocates(\n runner: TaskRunner,\n fromIndex: number,\n ) {\n if (!this.taskCache) {\n return;\n }\n for (let i = fromIndex; i < runner.tasks.length; i++) {\n const task = runner.tasks[i];\n if (\n task.type === 'Planning' &&\n task.subType === 'Locate' &&\n task.hitBy?.from === 'Cache'\n ) {\n const prompt = (task.param as DetailedLocateParam | undefined)?.prompt;\n if (prompt) {\n this.taskCache.markLocateCacheStale(prompt);\n }\n }\n }\n }\n\n private async runAction(\n userPrompt: TUserPrompt,\n planningModel: ModelRuntime,\n locateModel: ModelRuntime,\n aiActContext?: string,\n cacheable?: boolean,\n replanningCycleLimitOverride?: number,\n effort: AiActEffort = 'balance',\n deepLocate?: boolean,\n abortSignal?: AbortSignal,\n reportOptions?: ActionReportOptions,\n ): Promise<\n ExecutionResult<\n | {\n yamlFlow?: MidsceneYamlFlowItem[]; // for cache use\n output?: string;\n }\n | undefined\n >\n > {\n abortSignal ??= this.getAbortSignal?.();\n const conversationHistory = new ConversationHistory();\n const promptDisplay =\n reportOptions?.prompt || userPromptToString(userPrompt);\n\n // Per-call reporter that maps the runner's native task events to aiAct\n // action progress for the action batch currently running. Kept local (not\n // on the instance) so concurrent aiAct() calls on the same executor stay\n // isolated; it is set while a planned batch runs and cleared afterwards.\n let activeActionReporter:\n | ((event: TaskRunnerEvent) => Promise<void>)\n | undefined;\n\n const session = this.createExecutionSession(\n taskTitleStr(reportOptions?.type || 'Act', promptDisplay),\n {\n abortSignal,\n referenceImages: userPromptToMultimodalPrompt(userPrompt)?.images,\n onTaskEvent: async (event) => {\n await activeActionReporter?.(event);\n },\n },\n );\n const runner = session.getRunner();\n planningModel = { ...planningModel, executionId: runner.id };\n locateModel = { ...locateModel, executionId: runner.id };\n\n const noIndividualLocateModel =\n planningModel.config.slot === 'default' &&\n locateModel.config.slot === 'default';\n const planningConfig = planningModel.config;\n const locateConfig = locateModel.config;\n const sameSystemOneModel =\n planningModel.adapter.modelType === 'system-one' &&\n locateModel.adapter.modelType === 'system-one' &&\n planningConfig.modelName === locateConfig.modelName &&\n planningConfig.openaiBaseURL === locateConfig.openaiBaseURL;\n const bothJev =\n planningConfig.modelFamily === 'jev' &&\n locateConfig.modelFamily === 'jev';\n const includeLocateInPlanning =\n effort !== 'deepThink' &&\n (noIndividualLocateModel || (sameSystemOneModel && bothJev));\n const imagesIncludeCount = effort === 'deepThink' ? 2 : 1;\n\n debug('setting includeLocateInPlanning to', includeLocateInPlanning, {\n effort,\n noIndividualLocateModel,\n });\n\n let replanCount = 0;\n const yamlFlow: MidsceneYamlFlowItem[] = [];\n const replanningCycleLimit =\n replanningCycleLimitOverride ?? this.replanningCycleLimit;\n if (replanningCycleLimit === undefined) {\n throw new Error(\n 'replanningCycleLimit is required for TaskExecutor.action',\n );\n }\n\n await this.emitAiActProgress('start', {\n prompt: promptDisplay,\n planLimit: replanningCycleLimit,\n });\n\n const appendFailedPlan = async (\n errorMsg: string,\n planIndex?: number,\n ): Promise<{\n output: undefined;\n runner: TaskRunner;\n }> => {\n await this.emitAiActProgress('failed', {\n ...(planIndex ? { planIndex } : {}),\n planLimit: replanningCycleLimit,\n error: errorMsg,\n });\n return session.appendErrorPlan(errorMsg);\n };\n\n let errorCountInOnePlanningLoop = 0; // count the number of errors in one planning loop\n let outputString: string | undefined;\n let latestPlanResult: PlanningAIResponse | undefined;\n let latestPlanIndex = 0;\n\n if (abortSignal?.aborted) {\n return appendFailedPlan(\n `Task aborted: ${abortSignal.reason || 'abort signal received'}`,\n );\n }\n const getPreparedUserPrompt = (() => {\n let promise: ReturnType<typeof prepareUserPrompt> | undefined;\n\n return () => {\n promise ??= prepareUserPrompt(userPrompt);\n return promise;\n };\n })();\n\n // Main planning loop - unified plan/replan logic\n while (true) {\n const delegation = latestPlanResult?.delegation;\n const planIndex = replanCount + 1;\n latestPlanIndex = planIndex;\n\n // Check abort signal before each planning cycle\n if (abortSignal?.aborted) {\n return appendFailedPlan(\n `Task aborted: ${abortSignal.reason || 'abort signal received'}`,\n planIndex,\n );\n }\n\n // Get sub-goal status text if available\n const subGoalStatus = conversationHistory.subGoalsToText() || undefined;\n\n // Get memories text if available\n const memoriesStatus = conversationHistory.memoriesToText() || undefined;\n\n const result = await session.appendAndRun(\n {\n type: 'Planning',\n subType: 'Plan',\n param: {\n userInstruction: userPrompt,\n ...(reportOptions?.prompt\n ? { userInstructionDisplay: reportOptions.prompt }\n : {}),\n replanningCycleLimit,\n aiActContext,\n imagesIncludeCount,\n effort,\n ...(subGoalStatus ? { subGoalStatus } : {}),\n ...(memoriesStatus ? { memoriesStatus } : {}),\n },\n executor: async (executorContext) => {\n const { uiContext } = executorContext;\n assert(uiContext, 'uiContext is required for Planning task');\n const planningUiContext = uiContext as UIContext;\n const timing = executorContext.task.timing;\n await this.emitAiActProgress('plan_thinking', {\n planIndex,\n planLimit: replanningCycleLimit,\n screenshot: planningUiContext.screenshot,\n });\n\n const actionSpace = this.getActionSpace();\n debug(\n 'actionSpace for this interface is:',\n actionSpace.map((action) => action.name).join(', '),\n );\n assert(Array.isArray(actionSpace), 'actionSpace must be an array');\n if (actionSpace.length === 0) {\n console.warn(\n `ActionSpace for ${this.interface.interfaceType} is empty. This may lead to unexpected behavior.`,\n );\n }\n\n const modelRuntime: ModelRuntime = (() => {\n if (!delegation) {\n return planningModel;\n }\n // For delegated planning, build a default-model runtime for this cycle.\n const base = this.getDefaultModelRuntime();\n assert(\n base.config.modelFamily !== 'jev',\n 'The default planner cannot use the Jev model family',\n );\n return {\n ...base,\n config: { ...base.config, intent: 'planning' },\n executionId: planningModel.executionId,\n onUsage: base.onUsage\n ? (usage) => base.onUsage?.({ ...usage, intent: 'planning' })\n : undefined,\n modelFallback: {\n requestedModel: planningModel.config.modelName,\n requestedSlot: planningModel.config.slot,\n taskType: 'planning',\n reason: delegation.reason,\n },\n };\n })();\n const suggestedAction = delegation?.suggestedAction;\n const planningAdvice = suggestedAction\n ? `The preceding planner suggested that the next step may require action ${JSON.stringify(suggestedAction)}. This suggestion has NOT been executed and is advisory only. Independently determine the next step from the original goal, current screenshot, history and execution feedback. You may choose a different action or finish the task.`\n : undefined;\n const planImpl =\n modelRuntime.adapter.planning.kind === 'custom'\n ? modelRuntime.adapter.planning.planFn\n : standardPlan;\n\n let planResult: Awaited<ReturnType<typeof planImpl>>;\n try {\n const preparedUserPrompt = await getPreparedUserPrompt();\n\n setTimingFieldOnce(timing, 'callAiStart');\n planResult = await planImpl(preparedUserPrompt, {\n context: planningUiContext,\n actionContext: renderAIContext(aiActContext),\n actionSpace,\n modelRuntime,\n planningAdvice,\n getDefaultModelRuntime: this.getDefaultModelRuntime,\n conversationHistory,\n includeLocateInPlanning: !delegation && includeLocateInPlanning,\n imagesIncludeCount,\n effort,\n abortSignal,\n });\n } catch (planError) {\n if (planError instanceof AIResponseParseError) {\n // Record usage and rawResponse even when parsing fails\n executorContext.task.usage = withUsageIntent(\n planError.usage,\n 'planning',\n );\n executorContext.task.log = {\n ...(executorContext.task.log || {}),\n rawResponse: planError.rawResponse,\n rawAssistantOutput: planError.rawAssistantOutput,\n };\n }\n await this.emitAiActProgress('plan_failed', {\n planIndex,\n planLimit: replanningCycleLimit,\n error: errorMessageForAiAct(planError),\n });\n throw planError;\n } finally {\n setTimingFieldOnce(timing, 'callAiEnd');\n }\n debug('planResult', JSON.stringify(planResult, null, 2));\n\n const {\n actions,\n thought,\n log,\n memory,\n error,\n usage,\n rawResponse,\n rawAssistantOutput,\n reasoning_content,\n finalizeSuccess,\n finalizeMessage,\n updateSubGoals,\n markFinishedIndexes,\n } = planResult;\n outputString = finalizeMessage;\n\n executorContext.task.log = {\n ...(executorContext.task.log || {}),\n rawResponse,\n rawAssistantOutput,\n };\n executorContext.task.usage = withUsageIntent(usage, 'planning');\n executorContext.task.reasoning_content = reasoning_content;\n executorContext.task.output = {\n actions: actions || [],\n delegation: planResult.delegation,\n log,\n thought,\n memory,\n yamlFlow: planResult.yamlFlow,\n output: finalizeMessage,\n shouldContinuePlanning: planResult.shouldContinuePlanning,\n updateSubGoals,\n markFinishedIndexes,\n };\n executorContext.uiContext = planningUiContext;\n\n // Forward the raw in-progress reasoning the model produced; the\n // consumer decides which field to surface and how to format it.\n // `finalizeMessage` is intentionally left for the `complete` event.\n if (log || thought) {\n await this.emitAiActProgress('plan_planned', {\n planIndex,\n planLimit: replanningCycleLimit,\n ...(log ? { log } : {}),\n ...(thought ? { thought } : {}),\n });\n }\n\n if (error) {\n const errorMessage = `Failed to continue: ${error}\\n${log || ''}`;\n await this.emitAiActProgress('plan_failed', {\n planIndex,\n planLimit: replanningCycleLimit,\n error: errorMessage,\n });\n }\n\n assert(!error, `Failed to continue: ${error}\\n${log || ''}`);\n\n // Check if task was finalized with failure\n if (finalizeSuccess === false) {\n const errorMessage = `Task failed: ${finalizeMessage || 'No error message provided'}\\n${log || ''}`;\n await this.emitAiActProgress('plan_failed', {\n planIndex,\n planLimit: replanningCycleLimit,\n error: errorMessage,\n });\n assert(false, errorMessage);\n }\n\n return {\n cache: {\n hit: false,\n },\n } as any;\n },\n },\n {\n allowWhenError: true,\n },\n );\n\n const planResult = result?.output as PlanningAIResponse | undefined;\n latestPlanResult = planResult;\n\n if (!planResult?.delegation) {\n // Execute planned actions\n const plans = planResult?.actions || [];\n yamlFlow.push(...(planResult?.yamlFlow || []));\n\n let executables: Awaited<\n ReturnType<typeof this.convertPlanToExecutable>\n >;\n try {\n executables = await this.convertPlanToExecutable(\n plans,\n planningModel,\n locateModel,\n {\n cacheable,\n multimodalPrompt: userPromptToMultimodalPrompt(userPrompt),\n deepLocate,\n abortSignal,\n },\n );\n } catch (error) {\n return appendFailedPlan(\n `Error converting plans to executable tasks: ${errorMessageForAiAct(error)}, plans: ${JSON.stringify(\n plans,\n )}`,\n planIndex,\n );\n }\n if (conversationHistory.pendingFeedbackMessage) {\n console.warn(\n 'unconsumed pending feedback message detected, this may lead to unexpected planning result:',\n conversationHistory.pendingFeedbackMessage,\n );\n }\n\n // Capture the time context for the next planning call before running.\n const initialTimeString = await this.getTimeString();\n\n const taskCountBeforeRun = runner.tasks.length;\n // Scope a reporter to this replanning round so native task events from the\n // runner are mapped to aiAct progress with the right plan context; cleared\n // in `finally` so events fired between batches are ignored.\n activeActionReporter = createAiActActionReporter(\n planIndex,\n replanningCycleLimit,\n (phase, data) => this.emitAiActProgress(phase, data),\n );\n try {\n await session.appendAndRun(executables.tasks);\n this.setPendingFeedbackMessage(\n conversationHistory,\n initialTimeString,\n this.collectPlanningFeedback(\n runner.tasks.slice(taskCountBeforeRun),\n ),\n );\n } catch (error: any) {\n // A completed action must not be replayed because readiness failed.\n if (isActionReadinessError(error)) throw error;\n // errorFlag = true;\n errorCountInOnePlanningLoop++;\n const timeString = await this.getTimeString();\n this.setPendingFeedbackMessage(\n conversationHistory,\n timeString,\n `Error executing running tasks: ${error?.message || String(error)}`,\n );\n debug(\n 'error when executing running tasks, but continue to run if it is not too many errors:',\n error instanceof Error ? error.message : String(error),\n 'current error count in one planning loop:',\n errorCountInOnePlanningLoop,\n );\n } finally {\n activeActionReporter = undefined;\n }\n\n if (\n errorCountInOnePlanningLoop > maxErrorCountAllowedInOnePlanningLoop\n ) {\n return appendFailedPlan(\n 'Too many errors in one planning loop',\n planIndex,\n );\n }\n\n // Check abort signal after executing actions\n if (abortSignal?.aborted) {\n return appendFailedPlan(\n `Task aborted: ${abortSignal.reason || 'abort signal received'}`,\n planIndex,\n );\n }\n\n // // Check if task is complete\n if (!planResult?.shouldContinuePlanning) {\n break;\n }\n\n // We are about to replan, which means the batch we just ran did not finish\n // the task. Any locate task in that batch that was served from cache\n // produced an element that failed to complete the step (the action threw,\n // or it clicked the wrong element and the goal was not reached). Mark those\n // cache entries stale so the re-locate of the same prompt replaces them in\n // place instead of appending a poisoning duplicate that would be matched\n // first on the next run (#2529).\n this.invalidateFailedCacheHitLocates(runner, taskCountBeforeRun);\n }\n\n // Increment replan count for next iteration\n ++replanCount;\n\n if (replanCount > replanningCycleLimit) {\n const errorMsg = `Task stopped: the planning cycle limit (${replanningCycleLimit}) has been reached. This limit prevents the model from getting stuck in an endless planning loop. If your task requires more planning cycles, increase replanningCycleLimit or set the environment variable MIDSCENE_REPLANNING_CYCLE_LIMIT to a higher value. See https://midscenejs.com/zh/reference/#common for details.`;\n return appendFailedPlan(errorMsg, planIndex);\n }\n\n if (\n !planResult?.delegation &&\n !conversationHistory.pendingFeedbackMessage\n ) {\n const timeString = await this.getTimeString();\n conversationHistory.pendingFeedbackMessage = `Time: ${timeString}, I have finished the action previously planned.`;\n }\n }\n\n // Carry the raw final text; the consumer formats it. `outputString` is the\n // model's finalize message, with the latest plan's log/thought as fallback\n // context for consumers that want to show why the run completed.\n await this.emitAiActProgress('complete', {\n planIndex: latestPlanIndex,\n planLimit: replanningCycleLimit,\n ...((outputString ?? latestPlanResult?.output)\n ? { output: outputString ?? latestPlanResult?.output }\n : {}),\n ...(latestPlanResult?.log ? { log: latestPlanResult.log } : {}),\n ...(latestPlanResult?.thought\n ? { thought: latestPlanResult.thought }\n : {}),\n });\n\n return {\n output: {\n yamlFlow,\n output: outputString,\n },\n runner,\n };\n }\n\n private createTypeQueryTask(\n type: 'Query' | 'Boolean' | 'Number' | 'String' | 'Assert' | 'WaitFor',\n demand: ServiceExtractParam,\n modelRuntime: ModelRuntime,\n opt?: ServiceExtractOption,\n multimodalPrompt?: TMultimodalPrompt,\n executionOptions?: {\n abortSignal?: AbortSignal;\n },\n ) {\n const queryTask: ExecutionTaskInsightQueryApply = {\n type: 'Insight',\n subType: type,\n param: {\n domIncluded: opt?.domIncluded,\n ...(opt?.context !== undefined ? { context: opt.context } : {}),\n dataDemand: multimodalPrompt\n ? ({\n demand,\n multimodalPrompt,\n } as never)\n : demand, // for user param presentation in report right sidebar\n },\n executor: async (taskContext) => {\n const { task } = taskContext;\n let queryDump: ServiceDump | undefined;\n const applyDump = (dump: ServiceDump) => {\n queryDump = dump;\n task.log = {\n dump,\n rawResponse: dump.taskInfo?.rawResponse,\n rawAssistantOutput: dump.taskInfo?.rawAssistantOutput,\n searchAreaRawChoiceMessage:\n dump.taskInfo?.searchAreaRawChoiceMessage,\n };\n task.usage = withUsageIntent(dump.taskInfo?.usage, 'insight');\n if (dump.taskInfo?.reasoning_content) {\n task.reasoning_content = dump.taskInfo.reasoning_content;\n }\n };\n\n // Get context for query operations\n const uiContext = taskContext.uiContext;\n assert(uiContext, 'uiContext is required for Query task');\n\n const ifTypeRestricted = type !== 'Query';\n let demandInput = demand;\n let keyOfResult = 'result';\n if (ifTypeRestricted && (type === 'Assert' || type === 'WaitFor')) {\n keyOfResult = 'StatementIsTruthy';\n demandInput = {\n [keyOfResult]: buildTypeQueryDemandValue(type, demand),\n };\n } else if (ifTypeRestricted) {\n keyOfResult = type;\n demandInput = {\n [keyOfResult]: buildTypeQueryDemandValue(type, demand),\n };\n }\n\n let extractResult;\n\n let extraPageDescription = '';\n if (opt?.domIncluded && this.interface.getElementsNodeTree) {\n debug('appending tree info for page');\n const tree = await this.interface.getElementsNodeTree();\n extraPageDescription = await descriptionOfTree(\n tree,\n 200,\n false,\n opt?.domIncluded === 'visible-only',\n );\n }\n\n try {\n extractResult = await this.service.extract<any>(\n demandInput,\n modelRuntime,\n type === 'Boolean' || type === 'Assert' || type === 'WaitFor'\n ? 'boolean'\n : 'extract',\n opt,\n extraPageDescription,\n multimodalPrompt,\n uiContext,\n {\n ...executionOptions,\n abortSignal: executionOptions?.abortSignal ?? taskContext.signal,\n },\n );\n } catch (error) {\n if (error instanceof ServiceError) {\n applyDump(error.dump);\n }\n throw error;\n } finally {\n // Surface the captured screenshot sequence in the report, then release\n // it from the UIContext so its base64 is not retained twice.\n recordAndReleaseScreenshotSequence(task, uiContext);\n }\n\n const { data, thought, dump } = extractResult;\n applyDump(dump);\n\n let outputResult = data;\n if (ifTypeRestricted) {\n // If AI returned a plain string instead of structured format, use it directly\n if (typeof data === 'string') {\n outputResult = data;\n } else if (type === 'WaitFor') {\n if (data === null || data === undefined) {\n outputResult = false;\n } else {\n outputResult = (data as any)[keyOfResult];\n }\n } else if (data === null || data === undefined) {\n outputResult = null;\n } else {\n // AI model may return {result: ...} instead of {[keyOfResult]: ...}\n if (data?.[keyOfResult] !== undefined) {\n outputResult = (data as any)[keyOfResult];\n } else if (data?.result !== undefined) {\n outputResult = (data as any).result;\n } else {\n assert(false, 'No result in query data');\n }\n }\n }\n\n // Keep assertion failures in the task result so TaskRunner can persist\n // the model dump before aiAssert turns the result into a thrown error.\n if (type === 'Assert') {\n outputResult = Boolean(outputResult);\n }\n\n return {\n output: outputResult,\n log: queryDump,\n thought,\n };\n },\n };\n\n return queryTask;\n }\n async createTypeQueryExecution<T>(\n type: 'Query' | 'Boolean' | 'Number' | 'String' | 'Assert',\n demand: ServiceExtractParam,\n modelRuntime: ModelRuntime,\n opt?: ServiceExtractOption,\n multimodalPrompt?: TMultimodalPrompt,\n executionOptions?: {\n abortSignal?: AbortSignal;\n uiContext?: UIContext;\n },\n ): Promise<ExecutionResult<T>> {\n const abortSignal =\n executionOptions?.abortSignal ?? this.getAbortSignal?.();\n abortSignal?.throwIfAborted();\n const session = this.createExecutionSession(\n taskTitleStr(\n type,\n typeof demand === 'string' ? demand : JSON.stringify(demand),\n ),\n {\n ...(executionOptions?.uiContext\n ? { uiContext: executionOptions.uiContext }\n : {}),\n referenceImages: multimodalPrompt?.images,\n abortSignal,\n },\n );\n\n const runner = session.getRunner();\n const executionModelRuntime = { ...modelRuntime, executionId: runner.id };\n const queryTask = await this.createTypeQueryTask(\n type,\n demand,\n executionModelRuntime,\n opt,\n multimodalPrompt,\n { ...executionOptions, abortSignal },\n );\n\n const result = await session.appendAndRun(queryTask);\n\n if (!result) {\n throw new Error(\n 'result of taskExecutor.flush() is undefined in function createTypeQueryTask',\n );\n }\n\n const { output, thought } = result;\n\n return {\n output,\n thought,\n runner,\n };\n }\n\n async waitFor(\n assertion: TUserPrompt,\n opt: PlanningActionParamWaitFor,\n modelRuntime: ModelRuntime,\n ): Promise<ExecutionResult<void>> {\n const abortSignal = this.getAbortSignal?.();\n const { textPrompt, multimodalPrompt } = parsePrompt(assertion);\n\n const description = `waitFor: ${textPrompt}`;\n const session = this.createExecutionSession(\n taskTitleStr('WaitFor', description),\n { referenceImages: multimodalPrompt?.images, abortSignal },\n );\n const runner = session.getRunner();\n const executionModelRuntime = { ...modelRuntime, executionId: runner.id };\n const {\n timeoutMs,\n checkIntervalMs,\n domIncluded,\n screenshotIncluded,\n ...restOpt\n } = opt;\n const serviceExtractOpt: ServiceExtractOption = {\n domIncluded,\n screenshotIncluded,\n ...restOpt,\n };\n\n assert(assertion, 'No assertion for waitFor');\n assert(timeoutMs, 'No timeoutMs for waitFor');\n assert(checkIntervalMs, 'No checkIntervalMs for waitFor');\n\n assert(\n checkIntervalMs <= timeoutMs,\n `wrong config for waitFor: checkIntervalMs must be less than timeoutMs, config: {checkIntervalMs: ${checkIntervalMs}, timeoutMs: ${timeoutMs}}`,\n );\n\n const overallStartTime = Date.now();\n let lastCheckStart = overallStartTime;\n let errorThought = '';\n // Continue checking as long as the previous iteration began within the timeout window.\n while (lastCheckStart - overallStartTime <= timeoutMs) {\n const currentCheckStart = Date.now();\n lastCheckStart = currentCheckStart;\n abortSignal?.throwIfAborted();\n const queryTask = await this.createTypeQueryTask(\n 'WaitFor',\n textPrompt,\n executionModelRuntime,\n serviceExtractOpt,\n multimodalPrompt,\n { abortSignal },\n );\n\n const result = (await session.appendAndRun(queryTask)) as\n | {\n output: boolean;\n thought?: string;\n }\n | undefined;\n\n if (result?.output) {\n return {\n output: undefined,\n runner,\n };\n }\n\n errorThought =\n result?.thought ||\n (!result && `No result from assertion: ${textPrompt}`) ||\n `unknown error when waiting for assertion: ${textPrompt}`;\n const now = Date.now();\n if (now - currentCheckStart < checkIntervalMs) {\n const elapsed = now - currentCheckStart;\n const timeRemaining = checkIntervalMs - elapsed;\n const thought = `Check interval is ${checkIntervalMs}ms, ${elapsed}ms elapsed since last check, sleeping for ${timeRemaining}ms`;\n const { tasks: sleepTasks } = await this.convertPlanToExecutable(\n [{ type: 'Sleep', param: { timeMs: timeRemaining }, thought }],\n modelRuntime,\n modelRuntime,\n { abortSignal },\n );\n if (sleepTasks[0]) {\n await session.appendAndRun(sleepTasks[0]);\n }\n }\n }\n\n return session.appendErrorPlan(`waitFor timeout: ${errorThought}`);\n }\n}\n/**\n * Surface a captured screenshot sequence in the report timeline, then release\n * it from the UIContext.\n *\n * When a UIObservation insight runs, the observed frames live on\n * `uiContext.screenshotSequence` only as a transient model input. This attaches\n * them to the task recorder so the report renders the full sequence the model\n * saw (the report timeline builds one screenshot per recorder item), then drops\n * the field from the UIContext so its base64 is not retained twice for the\n * lifetime of the dump.\n *\n * The last frame is the representative `uiContext.screenshot`, already shown in\n * the report, so only the earlier frames are recorded to avoid duplication.\n * Observed frames are PREPENDED to `task.recorder` (rather than appended) so\n * array order matches chronological order — they were captured before the\n * assertion's before/after screenshots.\n */\nexport function recordAndReleaseScreenshotSequence(\n task: ExecutionTask,\n uiContext: UIContext | undefined,\n): void {\n const frames = uiContext?.screenshotSequence;\n if (frames && frames.length > 1) {\n const recorderItems: ExecutionRecorderItem[] = [];\n for (let i = 0; i < frames.length - 1; i++) {\n const frame = frames[i];\n recorderItems.push({\n type: 'screenshot',\n ts: frame.capturedAt,\n screenshot: frame,\n description: `Observed frame ${i + 1}/${frames.length}`,\n timing: 'observed-frame',\n });\n }\n // Prepend observed frames so they appear before the task's own\n // before/after screenshots in array order. Observed frames have earlier\n // timestamps than the assertion task itself, so this keeps array order\n // aligned with chronological order for consumers that iterate in-place.\n task.recorder = task.recorder\n ? [...recorderItems, ...task.recorder]\n : recorderItems;\n }\n if (uiContext?.screenshotSequence) {\n uiContext.screenshotSequence = undefined;\n }\n}\n"],"names":["debug","getDebug","warnLog","maxErrorCountAllowedInOnePlanningLoop","maxPlanningFeedbackLength","truncatePlanningFeedback","feedback","requestedLimit","limit","Number","Math","TaskExecutor","title","options","session","ExecutionSession","signal","Promise","runner","error","scope","phase","data","aiActProgressScope","conversationHistory","timeString","body","tasks","feedbackMessages","planningFeedback","planningFeedbackMaxLength","undefined","format","getReadableTimeString","plans","planningModel","locateModel","userInstruction","yamlString","reportOptions","taskTitleStr","userPromptToString","userPromptToMultimodalPrompt","task","executorContext","uiContext","assert","ms","abortSignal","action","defineActionSleep","setTimingFieldOnce","executionPlanningModel","executionLocateModel","result","output","userPrompt","aiActContext","cacheable","replanningCycleLimitOverride","effort","fileChooserAccept","deepLocate","withFileChooser","fromIndex","i","prompt","ConversationHistory","promptDisplay","activeActionReporter","event","noIndividualLocateModel","planningConfig","locateConfig","sameSystemOneModel","bothJev","includeLocateInPlanning","imagesIncludeCount","replanCount","yamlFlow","replanningCycleLimit","Error","appendFailedPlan","errorMsg","planIndex","errorCountInOnePlanningLoop","outputString","latestPlanResult","latestPlanIndex","getPreparedUserPrompt","promise","prepareUserPrompt","delegation","subGoalStatus","memoriesStatus","planningUiContext","timing","actionSpace","Array","console","modelRuntime","base","usage","suggestedAction","planningAdvice","JSON","planImpl","standardPlan","planResult","preparedUserPrompt","renderAIContext","planError","AIResponseParseError","withUsageIntent","errorMessageForAiAct","actions","thought","log","memory","rawResponse","rawAssistantOutput","reasoning_content","finalizeSuccess","finalizeMessage","updateSubGoals","markFinishedIndexes","errorMessage","executables","initialTimeString","taskCountBeforeRun","createAiActActionReporter","isActionReadinessError","String","type","demand","opt","multimodalPrompt","executionOptions","queryTask","taskContext","queryDump","applyDump","dump","ifTypeRestricted","demandInput","keyOfResult","buildTypeQueryDemandValue","extractResult","extraPageDescription","tree","descriptionOfTree","ServiceError","recordAndReleaseScreenshotSequence","outputResult","Boolean","executionModelRuntime","assertion","textPrompt","parsePrompt","description","timeoutMs","checkIntervalMs","domIncluded","screenshotIncluded","restOpt","serviceExtractOpt","overallStartTime","Date","lastCheckStart","errorThought","currentCheckStart","now","elapsed","timeRemaining","sleepTasks","interfaceInstance","service","opts","TaskBuilder","frames","recorderItems","frame"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuFA,MAAMA,QAAQC,SAAS;AACvB,MAAMC,UAAUD,SAAS,wBAAwB;IAAE,SAAS;AAAK;AACjE,MAAME,wCAAwC;AAK9C,MAAMC,4BAA4B;AAElC,SAASC,yBACPC,QAAgB,EAChBC,cAAqC;IAErC,IAAIA,AAAmB,gBAAnBA,gBACF,OAAOD;IAET,MAAME,QACJD,kBAAkBE,OAAO,QAAQ,CAACF,mBAAmBA,iBAAiB,IAClEG,KAAK,KAAK,CAACH,kBACXH;IACN,IAAIE,SAAS,MAAM,IAAIE,OACrB,OAAOF;IAGT,OAAO,GAAGA,SAAS,KAAK,CAAC,GAAGE,OAAO;eACtB,EAAEF,SAAS,MAAM,GAAGE,MAAM,iBAAiB,CAAC;AAC3D;AAKO,MAAMG;IAwBX,IAAI,OAAO;QACT,OAAO,IAAI,CAAC,SAAS;IACvB;IA0CQ,uBACNC,KAAa,EACbC,OAUC,EACD;QACA,MAAMC,UAAU,IAAIC,iBAClBH,OACA,CAACI,SACCH,SAAS,YACLI,QAAQ,OAAO,CAACJ,QAAQ,SAAS,IACjCI,QAAQ,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,kBAAkB,CAACD,UACtD;YACE,aAAaH,SAAS,eAAe,IAAI,CAAC,cAAc;YACxD,aAAa,IAAI,CAAC,mBAAmB;YACrC,OAAOA,SAAS;YAChB,iBAAiBA,SAAS;YAC1B,kBAAkB,OAAOK,QAAQC;gBAC/B,MAAM,IAAI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G,IAAIC,YAAY;YACjC,wBAAwBD,KAAK,sBAAsB;YACnDF;YACAC;YACA,WAAWC,KAAK,SAAS;YACzB,aAAa,IAAI,CAAC,cAAc;YAChC,iBAAiBA,KAAK,eAAe;YACrC,iBAAiBA,KAAK,eAAe;YACrC,mBAAmBA,KAAK,iBAAiB;QAC3C;IACF;AAolCF;AAkBO,SAASzB,mCACd7G,IAAmB,EACnBE,SAAgC;IAEhC,MAAMsI,SAAStI,WAAW;IAC1B,IAAIsI,UAAUA,OAAO,MAAM,GAAG,GAAG;QAC/B,MAAMC,gBAAyC,EAAE;QACjD,IAAK,IAAInH,IAAI,GAAGA,IAAIkH,OAAO,MAAM,GAAG,GAAGlH,IAAK;YAC1C,MAAMoH,QAAQF,MAAM,CAAClH,EAAE;YACvBmH,cAAc,IAAI,CAAC;gBACjB,MAAM;gBACN,IAAIC,MAAM,UAAU;gBACpB,YAAYA;gBACZ,aAAa,CAAC,eAAe,EAAEpH,IAAI,EAAE,CAAC,EAAEkH,OAAO,MAAM,EAAE;gBACvD,QAAQ;YACV;QACF;QAKAxI,KAAK,QAAQ,GAAGA,KAAK,QAAQ,GACzB;eAAIyI;eAAkBzI,KAAK,QAAQ;SAAC,GACpCyI;IACN;IACA,IAAIvI,WAAW,oBACbA,UAAU,kBAAkB,GAAGd;AAEnC"}
1
+ {"version":3,"file":"agent/tasks.mjs","sources":["../../../src/agent/tasks.ts"],"sourcesContent":["import { AIResponseParseError, ConversationHistory } from '@/ai-model';\nimport type { ModelRuntime } from '@/ai-model/models';\nimport { buildTypeQueryDemandValue } from '@/ai-model/prompt/insight';\nimport { prepareUserPrompt } from '@/ai-model/shared/multimodal-prompt';\nimport { standardPlan } from '@/ai-model/workflows/planning';\nimport {\n type TMultimodalPrompt,\n type TUserPrompt,\n getReadableTimeString,\n userPromptToMultimodalPrompt,\n userPromptToString,\n} from '@/common';\nimport { type AbstractInterface, defineActionSleep } from '@/device';\nimport type Service from '@/service';\nimport type {\n ExecutionReferenceImage,\n TaskRunner,\n TaskRunnerEvent,\n} from '@/task-runner';\nimport { TaskExecutionError } from '@/task-runner';\nimport type {\n AiActEffort,\n AiActProgressData,\n AiActProgressPhase,\n DetailedLocateParam,\n DeviceAction,\n ExecutionRecorderItem,\n ExecutionTask,\n ExecutionTaskApply,\n ExecutionTaskInsightQueryApply,\n ExecutionTaskPlanningApply,\n ExecutionTaskProgressOptions,\n MidsceneYamlFlowItem,\n PlanningAIResponse,\n PlanningAction,\n PlanningActionParamWaitFor,\n ServiceDump,\n ServiceExtractOption,\n ServiceExtractParam,\n UIContext,\n} from '@/types';\nimport { ServiceError, aiActProgressScope } from '@/types';\nimport { getDebug } from '@midscene/shared/logger';\nimport { assert } from '@midscene/shared/utils';\nimport { resolveSystemOneEndpoint } from '../ai-model/service-caller/system-one';\nimport {\n type ActionReadiness,\n isActionReadinessError,\n} from './action-readiness';\nimport { ExecutionSession } from './execution-session';\nimport { withFileChooser } from './file-chooser';\nimport {\n type AgentProgressPublisher,\n createAiActActionReporter,\n errorMessageForAiAct,\n} from './progress';\nimport { renderAIContext } from './prompt-context';\nimport { TaskBuilder } from './task-builder';\nimport type { TaskCache } from './task-cache';\nexport { locatePlanForLocate } from './task-builder';\nimport { setTimingFieldOnce } from '@/task-timing';\nimport { descriptionOfTree } from '@midscene/shared/extractor';\nimport { type TaskTitleType, taskTitleStr } from './ui-utils';\nimport { withUsageIntent } from './usage-intent';\nimport { parsePrompt } from './utils';\n\ninterface ExecutionResult<OutputType = any> {\n output: OutputType;\n thought?: string;\n runner: TaskRunner;\n}\n\ninterface TaskExecutorHooks {\n onExecutionCreated?: (runner: TaskRunner) => void;\n onSnapshotChange?: (\n runner: TaskRunner,\n error?: TaskExecutionError,\n ) => Promise<void> | void;\n // Publish onto the agent's progress bus. The bus owns sequencing, so the\n // executor is a pure producer: it names the scope/phase and hands over data.\n onProgress?: AgentProgressPublisher;\n}\n\nexport type ActionReportOptions = {\n type?: TaskTitleType;\n prompt?: string;\n};\n\nconst debug = getDebug('device-task-executor');\nconst warnLog = getDebug('device-task-executor', { console: true });\nconst maxErrorCountAllowedInOnePlanningLoop = 5;\n\n// Cap planning feedback by default so a large action output (e.g. a long adb\n// shell stdout) cannot blow up the next planning request's context. Actions\n// that require lossless structured feedback can explicitly choose their limit.\nconst maxPlanningFeedbackLength = 500;\n\nfunction truncatePlanningFeedback(\n feedback: string,\n requestedLimit?: number | 'unlimited',\n): string {\n if (requestedLimit === 'unlimited') {\n return feedback;\n }\n const limit =\n requestedLimit && Number.isFinite(requestedLimit) && requestedLimit > 0\n ? Math.floor(requestedLimit)\n : maxPlanningFeedbackLength;\n if (feedback.length <= limit) {\n return feedback;\n }\n\n return `${feedback.slice(0, limit)}\n...[truncated, ${feedback.length - limit} more characters]`;\n}\n\nexport { TaskExecutionError };\nexport { withFileChooser } from './file-chooser';\n\nexport class TaskExecutor {\n interface: AbstractInterface;\n\n service: Service;\n\n taskCache?: TaskCache;\n\n private readonly getDefaultModelRuntime: () => ModelRuntime;\n private readonly providedActionSpace: DeviceAction[];\n\n private readonly taskBuilder: TaskBuilder;\n\n onTaskStartCallback?: ExecutionTaskProgressOptions['onTaskStart'];\n\n private readonly hooks?: TaskExecutorHooks;\n private readonly getAbortSignal?: () => AbortSignal | undefined;\n\n replanningCycleLimit?: number;\n\n waitAfterAction?: number;\n\n useDeviceTime?: boolean;\n\n // @deprecated use .interface instead\n get page() {\n return this.interface;\n }\n\n constructor(\n interfaceInstance: AbstractInterface,\n service: Service,\n opts: {\n taskCache?: TaskCache;\n getDefaultModelRuntime: () => ModelRuntime;\n onTaskStart?: ExecutionTaskProgressOptions['onTaskStart'];\n replanningCycleLimit?: number;\n waitAfterAction?: number;\n actionReadiness?: ActionReadiness;\n useDeviceTime?: boolean;\n hooks?: TaskExecutorHooks;\n getAbortSignal?: () => AbortSignal | undefined;\n operationResource?: object;\n actionSpace: DeviceAction[];\n },\n ) {\n this.getDefaultModelRuntime = opts.getDefaultModelRuntime;\n this.interface = interfaceInstance;\n this.service = service;\n this.taskCache = opts.taskCache;\n this.onTaskStartCallback = opts?.onTaskStart;\n this.replanningCycleLimit = opts.replanningCycleLimit;\n this.waitAfterAction = opts.waitAfterAction;\n this.useDeviceTime = opts.useDeviceTime;\n this.hooks = opts.hooks;\n this.getAbortSignal = opts.getAbortSignal;\n this.providedActionSpace = opts.actionSpace;\n this.taskBuilder = new TaskBuilder({\n getDefaultModelRuntime: opts.getDefaultModelRuntime,\n interfaceInstance,\n service,\n taskCache: opts.taskCache,\n actionSpace: this.getActionSpace(),\n waitAfterAction: opts.waitAfterAction,\n actionReadiness: opts.actionReadiness,\n operationResource: opts.operationResource,\n });\n }\n\n private createExecutionSession(\n title: string,\n options?: {\n tasks?: ExecutionTaskApply[];\n abortSignal?: AbortSignal;\n uiContext?: UIContext;\n referenceImages?: readonly ExecutionReferenceImage[];\n onSnapshotChange?: (\n runner: TaskRunner,\n error?: TaskExecutionError,\n ) => Promise<void> | void;\n onTaskEvent?: (event: TaskRunnerEvent) => Promise<void> | void;\n },\n ) {\n const session = new ExecutionSession(\n title,\n (signal) =>\n options?.uiContext\n ? Promise.resolve(options.uiContext)\n : Promise.resolve(this.service.contextRetrieverFn(signal)),\n {\n abortSignal: options?.abortSignal ?? this.getAbortSignal?.(),\n onTaskStart: this.onTaskStartCallback,\n tasks: options?.tasks,\n referenceImages: options?.referenceImages,\n onSnapshotChange: async (runner, error) => {\n await this.hooks?.onSnapshotChange?.(runner, error);\n await options?.onSnapshotChange?.(runner, error);\n },\n ...(options?.onTaskEvent ? { onTaskEvent: options.onTaskEvent } : {}),\n },\n );\n this.hooks?.onExecutionCreated?.(session.getRunner());\n return session;\n }\n\n private getActionSpace(): DeviceAction[] {\n return this.providedActionSpace;\n }\n\n /**\n * Publish one event onto the agent's progress bus. The task layer is a pure\n * producer here: it names the scope/phase and forwards the structured\n * payload; the bus stamps the sequence and isolates listener errors. It has\n * no knowledge of how the event is rendered or consumed.\n */\n private async emitProgress(\n scope: string,\n phase: string,\n data: unknown,\n ): Promise<void> {\n await this.hooks?.onProgress?.(scope, phase, data);\n }\n\n /**\n * aiAct-flavored convenience over {@link emitProgress}: aiAct is the first\n * producer (\"pilot\") on the generic bus, so its events are simply tagged with\n * the `aiAct` scope.\n */\n private emitAiActProgress(\n phase: AiActProgressPhase,\n data: AiActProgressData,\n ): Promise<void> {\n return this.emitProgress(aiActProgressScope, phase, data);\n }\n\n /**\n * Set the pending feedback message consumed by the next planning round.\n * The message is always prefixed with the current time. When a body is\n * provided it is appended after the timestamp; otherwise only the time\n * context is recorded. This is the single entry point for writing\n * `pendingFeedbackMessage` so the time prefix stays consistent.\n */\n private setPendingFeedbackMessage(\n conversationHistory: ConversationHistory,\n timeString: string,\n body?: string,\n ) {\n conversationHistory.pendingFeedbackMessage = body\n ? `Time: ${timeString}, ${body}`\n : `Current time: ${timeString}`;\n }\n\n /**\n * Collect feedback produced by executed tasks for the next planning round.\n * Returns undefined when no task reported feedback.\n */\n private collectPlanningFeedback(tasks: ExecutionTask[]): string | undefined {\n const feedbackMessages = tasks.flatMap(\n ({ planningFeedback, planningFeedbackMaxLength }) =>\n planningFeedback\n ? [\n truncatePlanningFeedback(\n planningFeedback,\n planningFeedbackMaxLength,\n ),\n ]\n : [],\n );\n return feedbackMessages.length > 0\n ? feedbackMessages.join('\\n\\n')\n : undefined;\n }\n\n /**\n * Get a readable time string. When device time is enabled, use the\n * device-formatted wall-clock time directly so host timezone formatting does\n * not reinterpret a device timestamp.\n * @param format - Optional format string\n * @returns A formatted time string\n */\n private async getTimeString(format?: string): Promise<string> {\n if (this.useDeviceTime) {\n if (this.interface.getDeviceLocalTimeString) {\n try {\n return await this.interface.getDeviceLocalTimeString(format);\n } catch (error) {\n warnLog(\n `Failed to get device time string, falling back to runtime time: ${error}`,\n );\n }\n } else {\n warnLog(\n 'useDeviceTime is enabled but getDeviceLocalTimeString is not implemented, falling back to runtime time.',\n );\n }\n }\n\n return getReadableTimeString(format);\n }\n\n public async convertPlanToExecutable(\n plans: PlanningAction[],\n planningModel: ModelRuntime,\n locateModel: ModelRuntime,\n options?: {\n cacheable?: boolean;\n multimodalPrompt?: TMultimodalPrompt;\n deepLocate?: boolean;\n abortSignal?: AbortSignal;\n },\n ) {\n return this.taskBuilder.build(plans, planningModel, locateModel, options);\n }\n\n async loadYamlFlowAsPlanning(\n userInstruction: TUserPrompt,\n yamlString: string,\n reportOptions?: ActionReportOptions,\n ) {\n const session = this.createExecutionSession(\n taskTitleStr(\n reportOptions?.type || 'Act',\n reportOptions?.prompt || userPromptToString(userInstruction),\n ),\n {\n referenceImages: userPromptToMultimodalPrompt(userInstruction)?.images,\n },\n );\n\n const task: ExecutionTaskPlanningApply = {\n type: 'Planning',\n subType: 'LoadYaml',\n param: {\n userInstruction,\n ...(reportOptions?.prompt\n ? { userInstructionDisplay: reportOptions.prompt }\n : {}),\n },\n executor: async (executorContext) => {\n const { uiContext } = executorContext;\n assert(uiContext, 'uiContext is required for Planning task');\n return {\n output: {\n actions: [],\n shouldContinuePlanning: false,\n log: '',\n yamlString,\n },\n cache: {\n hit: true,\n },\n hitBy: {\n from: 'Cache',\n context: {\n yamlString,\n },\n },\n };\n },\n };\n const runner = session.getRunner();\n await session.appendAndRun(task);\n\n return {\n runner,\n };\n }\n\n async sleep(ms: number, abortSignal?: AbortSignal): Promise<void> {\n abortSignal ??= this.getAbortSignal?.();\n const session = this.createExecutionSession('Sleep', { abortSignal });\n const action = defineActionSleep(abortSignal);\n await session.appendAndRun({\n type: 'Action Space',\n subType: action.name,\n param: { timeMs: ms },\n executor: async ({ task }) => {\n assert(\n Number.isFinite(ms) && ms > 0,\n `ms for sleep must be a finite number greater than 0, but got ${ms}`,\n );\n setTimingFieldOnce(task.timing, 'callActionStart');\n try {\n await action.call({ timeMs: ms });\n } finally {\n setTimingFieldOnce(task.timing, 'callActionEnd');\n }\n },\n });\n }\n\n async runPlans(\n title: string,\n plans: PlanningAction[],\n planningModel: ModelRuntime,\n locateModel: ModelRuntime,\n options?: { uiContext?: UIContext; abortSignal?: AbortSignal },\n ): Promise<ExecutionResult> {\n const abortSignal = options?.abortSignal ?? this.getAbortSignal?.();\n const session = this.createExecutionSession(title, {\n ...options,\n abortSignal,\n });\n const runner = session.getRunner();\n const executionPlanningModel = { ...planningModel, executionId: runner.id };\n const executionLocateModel = { ...locateModel, executionId: runner.id };\n const { tasks } = await this.convertPlanToExecutable(\n plans,\n executionPlanningModel,\n executionLocateModel,\n { abortSignal },\n );\n const result = await session.appendAndRun(tasks);\n const { output } = result ?? {};\n return {\n output,\n runner,\n };\n }\n\n async action(\n userPrompt: TUserPrompt,\n planningModel: ModelRuntime,\n locateModel: ModelRuntime,\n aiActContext?: string,\n cacheable?: boolean,\n replanningCycleLimitOverride?: number,\n effort: AiActEffort = 'balance',\n fileChooserAccept?: string[],\n deepLocate?: boolean,\n abortSignal?: AbortSignal,\n reportOptions?: ActionReportOptions,\n ): Promise<\n ExecutionResult<\n | {\n yamlFlow?: MidsceneYamlFlowItem[]; // for cache use\n output?: string;\n }\n | undefined\n >\n > {\n abortSignal?.throwIfAborted();\n return withFileChooser(this.interface, fileChooserAccept, async () => {\n return this.runAction(\n userPrompt,\n planningModel,\n locateModel,\n aiActContext,\n cacheable,\n replanningCycleLimitOverride,\n effort,\n deepLocate,\n abortSignal,\n reportOptions,\n );\n });\n }\n\n /**\n * Called when the task is about to replan. Marks every cache-hit locate task\n * in the just-run batch (tasks at index >= fromIndex) as stale: that batch\n * did not finish the task, so the element each cache hit produced is suspect.\n * The upcoming re-locate of the same prompt then replaces the bad entry in\n * place instead of appending a duplicate that would re-poison the cache on the\n * next run (#2529).\n *\n * Marking a locate that was actually fine is harmless: the step is only ever\n * replaced if the same prompt is located again (i.e. the step is redone),\n * which does not happen for a locate that already succeeded.\n */\n private invalidateFailedCacheHitLocates(\n runner: TaskRunner,\n fromIndex: number,\n ) {\n if (!this.taskCache) {\n return;\n }\n for (let i = fromIndex; i < runner.tasks.length; i++) {\n const task = runner.tasks[i];\n if (\n task.type === 'Planning' &&\n task.subType === 'Locate' &&\n task.hitBy?.from === 'Cache'\n ) {\n const prompt = (task.param as DetailedLocateParam | undefined)?.prompt;\n if (prompt) {\n this.taskCache.markLocateCacheStale(prompt);\n }\n }\n }\n }\n\n private async runAction(\n userPrompt: TUserPrompt,\n planningModel: ModelRuntime,\n locateModel: ModelRuntime,\n aiActContext?: string,\n cacheable?: boolean,\n replanningCycleLimitOverride?: number,\n effort: AiActEffort = 'balance',\n deepLocate?: boolean,\n abortSignal?: AbortSignal,\n reportOptions?: ActionReportOptions,\n ): Promise<\n ExecutionResult<\n | {\n yamlFlow?: MidsceneYamlFlowItem[]; // for cache use\n output?: string;\n }\n | undefined\n >\n > {\n abortSignal ??= this.getAbortSignal?.();\n const conversationHistory = new ConversationHistory();\n const promptDisplay =\n reportOptions?.prompt || userPromptToString(userPrompt);\n\n // Per-call reporter that maps the runner's native task events to aiAct\n // action progress for the action batch currently running. Kept local (not\n // on the instance) so concurrent aiAct() calls on the same executor stay\n // isolated; it is set while a planned batch runs and cleared afterwards.\n let activeActionReporter:\n | ((event: TaskRunnerEvent) => Promise<void>)\n | undefined;\n\n const session = this.createExecutionSession(\n taskTitleStr(reportOptions?.type || 'Act', promptDisplay),\n {\n abortSignal,\n referenceImages: userPromptToMultimodalPrompt(userPrompt)?.images,\n onTaskEvent: async (event) => {\n await activeActionReporter?.(event);\n },\n },\n );\n const runner = session.getRunner();\n planningModel = { ...planningModel, executionId: runner.id };\n locateModel = { ...locateModel, executionId: runner.id };\n\n const noIndividualLocateModel =\n planningModel.config.slot === 'default' &&\n locateModel.config.slot === 'default';\n const planningConfig = planningModel.config;\n const locateConfig = locateModel.config;\n const sameSystemOneModel =\n planningModel.adapter.modelType === 'system-one' &&\n locateModel.adapter.modelType === 'system-one' &&\n planningConfig.modelName === locateConfig.modelName &&\n resolveSystemOneEndpoint(planningConfig) ===\n resolveSystemOneEndpoint(locateConfig);\n const bothJev =\n planningConfig.modelFamily === 'jev' &&\n locateConfig.modelFamily === 'jev';\n const includeLocateInPlanning =\n effort !== 'deepThink' &&\n (noIndividualLocateModel || (sameSystemOneModel && bothJev));\n const imagesIncludeCount = effort === 'deepThink' ? 2 : 1;\n\n debug('setting includeLocateInPlanning to', includeLocateInPlanning, {\n effort,\n noIndividualLocateModel,\n });\n\n let replanCount = 0;\n const yamlFlow: MidsceneYamlFlowItem[] = [];\n const replanningCycleLimit =\n replanningCycleLimitOverride ?? this.replanningCycleLimit;\n if (replanningCycleLimit === undefined) {\n throw new Error(\n 'replanningCycleLimit is required for TaskExecutor.action',\n );\n }\n\n await this.emitAiActProgress('start', {\n prompt: promptDisplay,\n planLimit: replanningCycleLimit,\n });\n\n const appendFailedPlan = async (\n errorMsg: string,\n planIndex?: number,\n ): Promise<{\n output: undefined;\n runner: TaskRunner;\n }> => {\n await this.emitAiActProgress('failed', {\n ...(planIndex ? { planIndex } : {}),\n planLimit: replanningCycleLimit,\n error: errorMsg,\n });\n return session.appendErrorPlan(errorMsg);\n };\n\n let errorCountInOnePlanningLoop = 0; // count the number of errors in one planning loop\n let outputString: string | undefined;\n let latestPlanResult: PlanningAIResponse | undefined;\n let latestPlanIndex = 0;\n\n if (abortSignal?.aborted) {\n return appendFailedPlan(\n `Task aborted: ${abortSignal.reason || 'abort signal received'}`,\n );\n }\n const getPreparedUserPrompt = (() => {\n let promise: ReturnType<typeof prepareUserPrompt> | undefined;\n\n return () => {\n promise ??= prepareUserPrompt(userPrompt);\n return promise;\n };\n })();\n\n // Main planning loop - unified plan/replan logic\n while (true) {\n const delegation = latestPlanResult?.delegation;\n const planIndex = replanCount + 1;\n latestPlanIndex = planIndex;\n\n // Check abort signal before each planning cycle\n if (abortSignal?.aborted) {\n return appendFailedPlan(\n `Task aborted: ${abortSignal.reason || 'abort signal received'}`,\n planIndex,\n );\n }\n\n // Get sub-goal status text if available\n const subGoalStatus = conversationHistory.subGoalsToText() || undefined;\n\n // Get memories text if available\n const memoriesStatus = conversationHistory.memoriesToText() || undefined;\n\n const result = await session.appendAndRun(\n {\n type: 'Planning',\n subType: 'Plan',\n param: {\n userInstruction: userPrompt,\n ...(reportOptions?.prompt\n ? { userInstructionDisplay: reportOptions.prompt }\n : {}),\n replanningCycleLimit,\n aiActContext,\n imagesIncludeCount,\n effort,\n ...(subGoalStatus ? { subGoalStatus } : {}),\n ...(memoriesStatus ? { memoriesStatus } : {}),\n },\n executor: async (executorContext) => {\n const { uiContext } = executorContext;\n assert(uiContext, 'uiContext is required for Planning task');\n const planningUiContext = uiContext as UIContext;\n const timing = executorContext.task.timing;\n await this.emitAiActProgress('plan_thinking', {\n planIndex,\n planLimit: replanningCycleLimit,\n screenshot: planningUiContext.screenshot,\n });\n\n const actionSpace = this.getActionSpace();\n debug(\n 'actionSpace for this interface is:',\n actionSpace.map((action) => action.name).join(', '),\n );\n assert(Array.isArray(actionSpace), 'actionSpace must be an array');\n if (actionSpace.length === 0) {\n console.warn(\n `ActionSpace for ${this.interface.interfaceType} is empty. This may lead to unexpected behavior.`,\n );\n }\n\n const modelRuntime: ModelRuntime = (() => {\n if (!delegation) {\n return planningModel;\n }\n // For delegated planning, build a default-model runtime for this cycle.\n const base = this.getDefaultModelRuntime();\n assert(\n base.config.modelFamily !== 'jev',\n 'The default planner cannot use the Jev model family',\n );\n return {\n ...base,\n config: { ...base.config, intent: 'planning' },\n executionId: planningModel.executionId,\n onUsage: base.onUsage\n ? (usage) => base.onUsage?.({ ...usage, intent: 'planning' })\n : undefined,\n modelFallback: {\n requestedModel: planningModel.config.modelName,\n requestedSlot: planningModel.config.slot,\n taskType: 'planning',\n reason: delegation.reason,\n },\n };\n })();\n const suggestedAction = delegation?.suggestedAction;\n const planningAdvice = suggestedAction\n ? `The preceding planner suggested that the next step may require action ${JSON.stringify(suggestedAction)}. This suggestion has NOT been executed and is advisory only. Independently determine the next step from the original goal, current screenshot, history and execution feedback. You may choose a different action or finish the task.`\n : undefined;\n const planImpl =\n modelRuntime.adapter.planning.kind === 'custom'\n ? modelRuntime.adapter.planning.planFn\n : standardPlan;\n\n let planResult: Awaited<ReturnType<typeof planImpl>>;\n try {\n const preparedUserPrompt = await getPreparedUserPrompt();\n\n setTimingFieldOnce(timing, 'callAiStart');\n planResult = await planImpl(preparedUserPrompt, {\n context: planningUiContext,\n actionContext: renderAIContext(aiActContext),\n actionSpace,\n modelRuntime,\n planningAdvice,\n getDefaultModelRuntime: this.getDefaultModelRuntime,\n conversationHistory,\n includeLocateInPlanning: !delegation && includeLocateInPlanning,\n imagesIncludeCount,\n effort,\n abortSignal,\n });\n } catch (planError) {\n if (planError instanceof AIResponseParseError) {\n // Record usage and rawResponse even when parsing fails\n executorContext.task.usage = withUsageIntent(\n planError.usage,\n 'planning',\n );\n executorContext.task.log = {\n ...(executorContext.task.log || {}),\n rawResponse: planError.rawResponse,\n rawAssistantOutput: planError.rawAssistantOutput,\n };\n }\n await this.emitAiActProgress('plan_failed', {\n planIndex,\n planLimit: replanningCycleLimit,\n error: errorMessageForAiAct(planError),\n });\n throw planError;\n } finally {\n setTimingFieldOnce(timing, 'callAiEnd');\n }\n debug('planResult', JSON.stringify(planResult, null, 2));\n\n const {\n actions,\n thought,\n log,\n memory,\n error,\n usage,\n rawResponse,\n rawAssistantOutput,\n reasoning_content,\n finalizeSuccess,\n finalizeMessage,\n updateSubGoals,\n markFinishedIndexes,\n } = planResult;\n outputString = finalizeMessage;\n\n executorContext.task.log = {\n ...(executorContext.task.log || {}),\n rawResponse,\n rawAssistantOutput,\n };\n executorContext.task.usage = withUsageIntent(usage, 'planning');\n executorContext.task.reasoning_content = reasoning_content;\n executorContext.task.output = {\n actions: actions || [],\n delegation: planResult.delegation,\n log,\n thought,\n memory,\n yamlFlow: planResult.yamlFlow,\n output: finalizeMessage,\n shouldContinuePlanning: planResult.shouldContinuePlanning,\n updateSubGoals,\n markFinishedIndexes,\n };\n executorContext.uiContext = planningUiContext;\n\n // Forward the raw in-progress reasoning the model produced; the\n // consumer decides which field to surface and how to format it.\n // `finalizeMessage` is intentionally left for the `complete` event.\n if (log || thought) {\n await this.emitAiActProgress('plan_planned', {\n planIndex,\n planLimit: replanningCycleLimit,\n ...(log ? { log } : {}),\n ...(thought ? { thought } : {}),\n });\n }\n\n if (error) {\n const errorMessage = `Failed to continue: ${error}\\n${log || ''}`;\n await this.emitAiActProgress('plan_failed', {\n planIndex,\n planLimit: replanningCycleLimit,\n error: errorMessage,\n });\n }\n\n assert(!error, `Failed to continue: ${error}\\n${log || ''}`);\n\n // Check if task was finalized with failure\n if (finalizeSuccess === false) {\n const errorMessage = `Task failed: ${finalizeMessage || 'No error message provided'}\\n${log || ''}`;\n await this.emitAiActProgress('plan_failed', {\n planIndex,\n planLimit: replanningCycleLimit,\n error: errorMessage,\n });\n assert(false, errorMessage);\n }\n\n return {\n cache: {\n hit: false,\n },\n } as any;\n },\n },\n {\n allowWhenError: true,\n },\n );\n\n const planResult = result?.output as PlanningAIResponse | undefined;\n latestPlanResult = planResult;\n\n if (!planResult?.delegation) {\n // Execute planned actions\n const plans = planResult?.actions || [];\n yamlFlow.push(...(planResult?.yamlFlow || []));\n\n let executables: Awaited<\n ReturnType<typeof this.convertPlanToExecutable>\n >;\n try {\n executables = await this.convertPlanToExecutable(\n plans,\n planningModel,\n locateModel,\n {\n cacheable,\n multimodalPrompt: userPromptToMultimodalPrompt(userPrompt),\n deepLocate,\n abortSignal,\n },\n );\n } catch (error) {\n return appendFailedPlan(\n `Error converting plans to executable tasks: ${errorMessageForAiAct(error)}, plans: ${JSON.stringify(\n plans,\n )}`,\n planIndex,\n );\n }\n if (conversationHistory.pendingFeedbackMessage) {\n console.warn(\n 'unconsumed pending feedback message detected, this may lead to unexpected planning result:',\n conversationHistory.pendingFeedbackMessage,\n );\n }\n\n // Capture the time context for the next planning call before running.\n const initialTimeString = await this.getTimeString();\n\n const taskCountBeforeRun = runner.tasks.length;\n // Scope a reporter to this replanning round so native task events from the\n // runner are mapped to aiAct progress with the right plan context; cleared\n // in `finally` so events fired between batches are ignored.\n activeActionReporter = createAiActActionReporter(\n planIndex,\n replanningCycleLimit,\n (phase, data) => this.emitAiActProgress(phase, data),\n );\n try {\n await session.appendAndRun(executables.tasks);\n this.setPendingFeedbackMessage(\n conversationHistory,\n initialTimeString,\n this.collectPlanningFeedback(\n runner.tasks.slice(taskCountBeforeRun),\n ),\n );\n } catch (error: any) {\n // A completed action must not be replayed because readiness failed.\n if (isActionReadinessError(error)) throw error;\n // errorFlag = true;\n errorCountInOnePlanningLoop++;\n const timeString = await this.getTimeString();\n this.setPendingFeedbackMessage(\n conversationHistory,\n timeString,\n `Error executing running tasks: ${error?.message || String(error)}`,\n );\n debug(\n 'error when executing running tasks, but continue to run if it is not too many errors:',\n error instanceof Error ? error.message : String(error),\n 'current error count in one planning loop:',\n errorCountInOnePlanningLoop,\n );\n } finally {\n activeActionReporter = undefined;\n }\n\n if (\n errorCountInOnePlanningLoop > maxErrorCountAllowedInOnePlanningLoop\n ) {\n return appendFailedPlan(\n 'Too many errors in one planning loop',\n planIndex,\n );\n }\n\n // Check abort signal after executing actions\n if (abortSignal?.aborted) {\n return appendFailedPlan(\n `Task aborted: ${abortSignal.reason || 'abort signal received'}`,\n planIndex,\n );\n }\n\n // // Check if task is complete\n if (!planResult?.shouldContinuePlanning) {\n break;\n }\n\n // We are about to replan, which means the batch we just ran did not finish\n // the task. Any locate task in that batch that was served from cache\n // produced an element that failed to complete the step (the action threw,\n // or it clicked the wrong element and the goal was not reached). Mark those\n // cache entries stale so the re-locate of the same prompt replaces them in\n // place instead of appending a poisoning duplicate that would be matched\n // first on the next run (#2529).\n this.invalidateFailedCacheHitLocates(runner, taskCountBeforeRun);\n }\n\n // Increment replan count for next iteration\n ++replanCount;\n\n if (replanCount > replanningCycleLimit) {\n const errorMsg = `Task stopped: the planning cycle limit (${replanningCycleLimit}) has been reached. This limit prevents the model from getting stuck in an endless planning loop. If your task requires more planning cycles, increase replanningCycleLimit or set the environment variable MIDSCENE_REPLANNING_CYCLE_LIMIT to a higher value. See https://midscenejs.com/zh/reference/#common for details.`;\n return appendFailedPlan(errorMsg, planIndex);\n }\n\n if (\n !planResult?.delegation &&\n !conversationHistory.pendingFeedbackMessage\n ) {\n const timeString = await this.getTimeString();\n conversationHistory.pendingFeedbackMessage = `Time: ${timeString}, I have finished the action previously planned.`;\n }\n }\n\n // Carry the raw final text; the consumer formats it. `outputString` is the\n // model's finalize message, with the latest plan's log/thought as fallback\n // context for consumers that want to show why the run completed.\n await this.emitAiActProgress('complete', {\n planIndex: latestPlanIndex,\n planLimit: replanningCycleLimit,\n ...((outputString ?? latestPlanResult?.output)\n ? { output: outputString ?? latestPlanResult?.output }\n : {}),\n ...(latestPlanResult?.log ? { log: latestPlanResult.log } : {}),\n ...(latestPlanResult?.thought\n ? { thought: latestPlanResult.thought }\n : {}),\n });\n\n return {\n output: {\n yamlFlow,\n output: outputString,\n },\n runner,\n };\n }\n\n private createTypeQueryTask(\n type: 'Query' | 'Boolean' | 'Number' | 'String' | 'Assert' | 'WaitFor',\n demand: ServiceExtractParam,\n modelRuntime: ModelRuntime,\n opt?: ServiceExtractOption,\n multimodalPrompt?: TMultimodalPrompt,\n executionOptions?: {\n abortSignal?: AbortSignal;\n },\n ) {\n const queryTask: ExecutionTaskInsightQueryApply = {\n type: 'Insight',\n subType: type,\n param: {\n domIncluded: opt?.domIncluded,\n ...(opt?.context !== undefined ? { context: opt.context } : {}),\n dataDemand: multimodalPrompt\n ? ({\n demand,\n multimodalPrompt,\n } as never)\n : demand, // for user param presentation in report right sidebar\n },\n executor: async (taskContext) => {\n const { task } = taskContext;\n let queryDump: ServiceDump | undefined;\n const applyDump = (dump: ServiceDump) => {\n queryDump = dump;\n task.log = {\n dump,\n rawResponse: dump.taskInfo?.rawResponse,\n rawAssistantOutput: dump.taskInfo?.rawAssistantOutput,\n searchAreaRawChoiceMessage:\n dump.taskInfo?.searchAreaRawChoiceMessage,\n };\n task.usage = withUsageIntent(dump.taskInfo?.usage, 'insight');\n if (dump.taskInfo?.reasoning_content) {\n task.reasoning_content = dump.taskInfo.reasoning_content;\n }\n };\n\n // Get context for query operations\n const uiContext = taskContext.uiContext;\n assert(uiContext, 'uiContext is required for Query task');\n\n const ifTypeRestricted = type !== 'Query';\n let demandInput = demand;\n let keyOfResult = 'result';\n if (ifTypeRestricted && (type === 'Assert' || type === 'WaitFor')) {\n keyOfResult = 'StatementIsTruthy';\n demandInput = {\n [keyOfResult]: buildTypeQueryDemandValue(type, demand),\n };\n } else if (ifTypeRestricted) {\n keyOfResult = type;\n demandInput = {\n [keyOfResult]: buildTypeQueryDemandValue(type, demand),\n };\n }\n\n let extractResult;\n\n let extraPageDescription = '';\n if (opt?.domIncluded && this.interface.getElementsNodeTree) {\n debug('appending tree info for page');\n const tree = await this.interface.getElementsNodeTree();\n extraPageDescription = await descriptionOfTree(\n tree,\n 200,\n false,\n opt?.domIncluded === 'visible-only',\n );\n }\n\n try {\n extractResult = await this.service.extract<any>(\n demandInput,\n modelRuntime,\n type === 'Boolean' || type === 'Assert' || type === 'WaitFor'\n ? 'boolean'\n : 'extract',\n opt,\n extraPageDescription,\n multimodalPrompt,\n uiContext,\n {\n ...executionOptions,\n abortSignal: executionOptions?.abortSignal ?? taskContext.signal,\n },\n );\n } catch (error) {\n if (error instanceof ServiceError) {\n applyDump(error.dump);\n }\n throw error;\n } finally {\n // Surface the captured screenshot sequence in the report, then release\n // it from the UIContext so its base64 is not retained twice.\n recordAndReleaseScreenshotSequence(task, uiContext);\n }\n\n const { data, thought, dump } = extractResult;\n applyDump(dump);\n\n let outputResult = data;\n if (ifTypeRestricted) {\n // If AI returned a plain string instead of structured format, use it directly\n if (typeof data === 'string') {\n outputResult = data;\n } else if (type === 'WaitFor') {\n if (data === null || data === undefined) {\n outputResult = false;\n } else {\n outputResult = (data as any)[keyOfResult];\n }\n } else if (data === null || data === undefined) {\n outputResult = null;\n } else {\n // AI model may return {result: ...} instead of {[keyOfResult]: ...}\n if (data?.[keyOfResult] !== undefined) {\n outputResult = (data as any)[keyOfResult];\n } else if (data?.result !== undefined) {\n outputResult = (data as any).result;\n } else {\n assert(false, 'No result in query data');\n }\n }\n }\n\n // Keep assertion failures in the task result so TaskRunner can persist\n // the model dump before aiAssert turns the result into a thrown error.\n if (type === 'Assert') {\n outputResult = Boolean(outputResult);\n }\n\n return {\n output: outputResult,\n log: queryDump,\n thought,\n };\n },\n };\n\n return queryTask;\n }\n async createTypeQueryExecution<T>(\n type: 'Query' | 'Boolean' | 'Number' | 'String' | 'Assert',\n demand: ServiceExtractParam,\n modelRuntime: ModelRuntime,\n opt?: ServiceExtractOption,\n multimodalPrompt?: TMultimodalPrompt,\n executionOptions?: {\n abortSignal?: AbortSignal;\n uiContext?: UIContext;\n },\n ): Promise<ExecutionResult<T>> {\n const abortSignal =\n executionOptions?.abortSignal ?? this.getAbortSignal?.();\n abortSignal?.throwIfAborted();\n const session = this.createExecutionSession(\n taskTitleStr(\n type,\n typeof demand === 'string' ? demand : JSON.stringify(demand),\n ),\n {\n ...(executionOptions?.uiContext\n ? { uiContext: executionOptions.uiContext }\n : {}),\n referenceImages: multimodalPrompt?.images,\n abortSignal,\n },\n );\n\n const runner = session.getRunner();\n const executionModelRuntime = { ...modelRuntime, executionId: runner.id };\n const queryTask = await this.createTypeQueryTask(\n type,\n demand,\n executionModelRuntime,\n opt,\n multimodalPrompt,\n { ...executionOptions, abortSignal },\n );\n\n const result = await session.appendAndRun(queryTask);\n\n if (!result) {\n throw new Error(\n 'result of taskExecutor.flush() is undefined in function createTypeQueryTask',\n );\n }\n\n const { output, thought } = result;\n\n return {\n output,\n thought,\n runner,\n };\n }\n\n async waitFor(\n assertion: TUserPrompt,\n opt: PlanningActionParamWaitFor,\n modelRuntime: ModelRuntime,\n ): Promise<ExecutionResult<void>> {\n const abortSignal = this.getAbortSignal?.();\n const { textPrompt, multimodalPrompt } = parsePrompt(assertion);\n\n const description = `waitFor: ${textPrompt}`;\n const session = this.createExecutionSession(\n taskTitleStr('WaitFor', description),\n { referenceImages: multimodalPrompt?.images, abortSignal },\n );\n const runner = session.getRunner();\n const executionModelRuntime = { ...modelRuntime, executionId: runner.id };\n const {\n timeoutMs,\n checkIntervalMs,\n domIncluded,\n screenshotIncluded,\n ...restOpt\n } = opt;\n const serviceExtractOpt: ServiceExtractOption = {\n domIncluded,\n screenshotIncluded,\n ...restOpt,\n };\n\n assert(assertion, 'No assertion for waitFor');\n assert(timeoutMs, 'No timeoutMs for waitFor');\n assert(checkIntervalMs, 'No checkIntervalMs for waitFor');\n\n assert(\n checkIntervalMs <= timeoutMs,\n `wrong config for waitFor: checkIntervalMs must be less than timeoutMs, config: {checkIntervalMs: ${checkIntervalMs}, timeoutMs: ${timeoutMs}}`,\n );\n\n const overallStartTime = Date.now();\n let lastCheckStart = overallStartTime;\n let errorThought = '';\n // Continue checking as long as the previous iteration began within the timeout window.\n while (lastCheckStart - overallStartTime <= timeoutMs) {\n const currentCheckStart = Date.now();\n lastCheckStart = currentCheckStart;\n abortSignal?.throwIfAborted();\n const queryTask = await this.createTypeQueryTask(\n 'WaitFor',\n textPrompt,\n executionModelRuntime,\n serviceExtractOpt,\n multimodalPrompt,\n { abortSignal },\n );\n\n const result = (await session.appendAndRun(queryTask)) as\n | {\n output: boolean;\n thought?: string;\n }\n | undefined;\n\n if (result?.output) {\n return {\n output: undefined,\n runner,\n };\n }\n\n errorThought =\n result?.thought ||\n (!result && `No result from assertion: ${textPrompt}`) ||\n `unknown error when waiting for assertion: ${textPrompt}`;\n const now = Date.now();\n if (now - currentCheckStart < checkIntervalMs) {\n const elapsed = now - currentCheckStart;\n const timeRemaining = checkIntervalMs - elapsed;\n const thought = `Check interval is ${checkIntervalMs}ms, ${elapsed}ms elapsed since last check, sleeping for ${timeRemaining}ms`;\n const { tasks: sleepTasks } = await this.convertPlanToExecutable(\n [{ type: 'Sleep', param: { timeMs: timeRemaining }, thought }],\n modelRuntime,\n modelRuntime,\n { abortSignal },\n );\n if (sleepTasks[0]) {\n await session.appendAndRun(sleepTasks[0]);\n }\n }\n }\n\n return session.appendErrorPlan(`waitFor timeout: ${errorThought}`);\n }\n}\n/**\n * Surface a captured screenshot sequence in the report timeline, then release\n * it from the UIContext.\n *\n * When a UIObservation insight runs, the observed frames live on\n * `uiContext.screenshotSequence` only as a transient model input. This attaches\n * them to the task recorder so the report renders the full sequence the model\n * saw (the report timeline builds one screenshot per recorder item), then drops\n * the field from the UIContext so its base64 is not retained twice for the\n * lifetime of the dump.\n *\n * The last frame is the representative `uiContext.screenshot`, already shown in\n * the report, so only the earlier frames are recorded to avoid duplication.\n * Observed frames are PREPENDED to `task.recorder` (rather than appended) so\n * array order matches chronological order — they were captured before the\n * assertion's before/after screenshots.\n */\nexport function recordAndReleaseScreenshotSequence(\n task: ExecutionTask,\n uiContext: UIContext | undefined,\n): void {\n const frames = uiContext?.screenshotSequence;\n if (frames && frames.length > 1) {\n const recorderItems: ExecutionRecorderItem[] = [];\n for (let i = 0; i < frames.length - 1; i++) {\n const frame = frames[i];\n recorderItems.push({\n type: 'screenshot',\n ts: frame.capturedAt,\n screenshot: frame,\n description: `Observed frame ${i + 1}/${frames.length}`,\n timing: 'observed-frame',\n });\n }\n // Prepend observed frames so they appear before the task's own\n // before/after screenshots in array order. Observed frames have earlier\n // timestamps than the assertion task itself, so this keeps array order\n // aligned with chronological order for consumers that iterate in-place.\n task.recorder = task.recorder\n ? [...recorderItems, ...task.recorder]\n : recorderItems;\n }\n if (uiContext?.screenshotSequence) {\n uiContext.screenshotSequence = undefined;\n }\n}\n"],"names":["debug","getDebug","warnLog","maxErrorCountAllowedInOnePlanningLoop","maxPlanningFeedbackLength","truncatePlanningFeedback","feedback","requestedLimit","limit","Number","Math","TaskExecutor","title","options","session","ExecutionSession","signal","Promise","runner","error","scope","phase","data","aiActProgressScope","conversationHistory","timeString","body","tasks","feedbackMessages","planningFeedback","planningFeedbackMaxLength","undefined","format","getReadableTimeString","plans","planningModel","locateModel","userInstruction","yamlString","reportOptions","taskTitleStr","userPromptToString","userPromptToMultimodalPrompt","task","executorContext","uiContext","assert","ms","abortSignal","action","defineActionSleep","setTimingFieldOnce","executionPlanningModel","executionLocateModel","result","output","userPrompt","aiActContext","cacheable","replanningCycleLimitOverride","effort","fileChooserAccept","deepLocate","withFileChooser","fromIndex","i","prompt","ConversationHistory","promptDisplay","activeActionReporter","event","noIndividualLocateModel","planningConfig","locateConfig","sameSystemOneModel","resolveSystemOneEndpoint","bothJev","includeLocateInPlanning","imagesIncludeCount","replanCount","yamlFlow","replanningCycleLimit","Error","appendFailedPlan","errorMsg","planIndex","errorCountInOnePlanningLoop","outputString","latestPlanResult","latestPlanIndex","getPreparedUserPrompt","promise","prepareUserPrompt","delegation","subGoalStatus","memoriesStatus","planningUiContext","timing","actionSpace","Array","console","modelRuntime","base","usage","suggestedAction","planningAdvice","JSON","planImpl","standardPlan","planResult","preparedUserPrompt","renderAIContext","planError","AIResponseParseError","withUsageIntent","errorMessageForAiAct","actions","thought","log","memory","rawResponse","rawAssistantOutput","reasoning_content","finalizeSuccess","finalizeMessage","updateSubGoals","markFinishedIndexes","errorMessage","executables","initialTimeString","taskCountBeforeRun","createAiActActionReporter","isActionReadinessError","String","type","demand","opt","multimodalPrompt","executionOptions","queryTask","taskContext","queryDump","applyDump","dump","ifTypeRestricted","demandInput","keyOfResult","buildTypeQueryDemandValue","extractResult","extraPageDescription","tree","descriptionOfTree","ServiceError","recordAndReleaseScreenshotSequence","outputResult","Boolean","executionModelRuntime","assertion","textPrompt","parsePrompt","description","timeoutMs","checkIntervalMs","domIncluded","screenshotIncluded","restOpt","serviceExtractOpt","overallStartTime","Date","lastCheckStart","errorThought","currentCheckStart","now","elapsed","timeRemaining","sleepTasks","interfaceInstance","service","opts","TaskBuilder","frames","recorderItems","frame"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwFA,MAAMA,QAAQC,SAAS;AACvB,MAAMC,UAAUD,SAAS,wBAAwB;IAAE,SAAS;AAAK;AACjE,MAAME,wCAAwC;AAK9C,MAAMC,4BAA4B;AAElC,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F,MAAM,CAACnH,EAAE;YACvBoH,cAAc,IAAI,CAAC;gBACjB,MAAM;gBACN,IAAIC,MAAM,UAAU;gBACpB,YAAYA;gBACZ,aAAa,CAAC,eAAe,EAAErH,IAAI,EAAE,CAAC,EAAEmH,OAAO,MAAM,EAAE;gBACvD,QAAQ;YACV;QACF;QAKAzI,KAAK,QAAQ,GAAGA,KAAK,QAAQ,GACzB;eAAI0I;eAAkB1I,KAAK,QAAQ;SAAC,GACpC0I;IACN;IACA,IAAIxI,WAAW,oBACbA,UAAU,kBAAkB,GAAGd;AAEnC"}
@@ -153,7 +153,7 @@ async function matchElementFromCache(context, cacheEntry, cachePrompt, cacheable
153
153
  return;
154
154
  }
155
155
  }
156
- const getMidsceneVersion = ()=>"1.17.2-beta-20261027033907.0";
156
+ const getMidsceneVersion = ()=>"1.17.2";
157
157
  const parsePrompt = (prompt)=>{
158
158
  if ('string' == typeof prompt) return {
159
159
  textPrompt: prompt,
@@ -8,7 +8,7 @@ const buildGeminiChatCompletionParams = (input)=>{
8
8
  google: {
9
9
  thinking_config: {
10
10
  include_thoughts: true,
11
- thinking_level: reasoningEnabled ? reasoningEffort ?? 'medium' : 'minimal'
11
+ thinking_level: reasoningEnabled ? reasoningEffort ?? 'medium' : 'low'
12
12
  }
13
13
  }
14
14
  };
@@ -21,45 +21,18 @@ const buildGeminiChatCompletionParams = (input)=>{
21
21
  };
22
22
  };
23
23
  const extractInlineThought = (content)=>{
24
- const match = content.match(/<thought>([\s\S]*?)<\/thought>/i);
24
+ const match = content.match(/^<thought>([\s\S]*?)<\/thought>/i);
25
25
  return match?.[1]?.trim() || void 0;
26
26
  };
27
- function isRecord(value) {
28
- return !!value && 'object' == typeof value && !Array.isArray(value);
29
- }
30
- const formatReasoningContent = ({ geminiReasoningContent, providerReasoningContent })=>{
31
- if (geminiReasoningContent && providerReasoningContent) return `thoughtParts:${geminiReasoningContent}; reasoning_content:${providerReasoningContent}`;
27
+ function formatReasoningContent({ geminiReasoningContent, providerReasoningContent }) {
28
+ if (geminiReasoningContent && providerReasoningContent) return `inlineThought:${geminiReasoningContent}; reasoning_content:${providerReasoningContent}`;
32
29
  return geminiReasoningContent || providerReasoningContent || '';
33
- };
34
- const extractGeminiThoughtParts = (content)=>{
35
- const contentParts = [];
36
- const reasoningParts = [];
37
- for (const part of content){
38
- if (!isRecord(part)) continue;
39
- const text = 'string' == typeof part.text ? part.text : void 0;
40
- if (text) if (true === part.thought) reasoningParts.push(text);
41
- else contentParts.push(text);
42
- }
43
- return {
44
- content: contentParts.join(''),
45
- geminiReasoningContent: reasoningParts.join('')
46
- };
47
- };
30
+ }
48
31
  const extractGeminiContentAndReasoning = (message)=>{
49
32
  if (!message) return {
50
33
  content: '',
51
34
  reasoning_content: ''
52
35
  };
53
- if (Array.isArray(message.content)) {
54
- const extracted = extractGeminiThoughtParts(message.content);
55
- return {
56
- content: extracted.content,
57
- reasoning_content: formatReasoningContent({
58
- geminiReasoningContent: extracted.geminiReasoningContent,
59
- providerReasoningContent: 'string' == typeof message.reasoning_content ? message.reasoning_content : ''
60
- })
61
- };
62
- }
63
36
  const content = 'string' == typeof message.content ? message.content : '';
64
37
  const geminiReasoningContent = extractInlineThought(content) || '';
65
38
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"ai-model/models/gemini.mjs","sources":["../../../../src/ai-model/models/gemini.ts"],"sourcesContent":["import type { TModelFamily } from '@midscene/shared/env';\nimport type OpenAI from 'openai';\nimport type {\n ChatCompletionCallContext,\n ChatCompletionContentSource,\n ChatCompletionParamsResult,\n ContentAndReasoning,\n ModelAdapterDefinition,\n} from '../model-adapter/types';\n\ntype GeminiContentPart = Record<string, unknown> & {\n text?: string;\n thought?: boolean;\n};\n\ntype GeminiContentExtension = {\n content: string | null | GeminiContentPart[];\n reasoning_content?: string;\n extra_content?: unknown;\n};\n\ntype GeminiContentSource =\n | ChatCompletionContentSource\n | (Omit<OpenAI.Chat.Completions.ChatCompletionMessage, 'content'> &\n GeminiContentExtension)\n | (Omit<OpenAI.Chat.Completions.ChatCompletionChunk.Choice.Delta, 'content'> &\n GeminiContentExtension);\n\nconst buildGeminiChatCompletionParams = (\n input: ChatCompletionCallContext,\n): ChatCompletionParamsResult => {\n const { midsceneDefaults, userConfig } = input;\n const { reasoningEnabled, reasoningEffort } = userConfig;\n const commonOverrideConfig: Record<string, unknown> = {};\n\n if (userConfig.temperature !== undefined) {\n commonOverrideConfig.temperature = userConfig.temperature;\n }\n\n const modelSpecificConfig: {\n extra_body?: {\n google?: {\n thinking_config: {\n include_thoughts: true;\n thinking_level: string;\n };\n };\n };\n } = {};\n\n if (reasoningEnabled !== 'default') {\n // Gemini cannot fully disable native thinking, so \"disabled\" maps to the\n // lowest thinking level. `include_thoughts` only controls whether Gemini\n // returns thought summaries; it does not enable thinking, and thought token\n // usage is based on the full thoughts Gemini generates regardless of\n // whether summaries are included.\n modelSpecificConfig.extra_body = {\n google: {\n thinking_config: {\n include_thoughts: true,\n thinking_level: reasoningEnabled\n ? (reasoningEffort ?? 'medium')\n : 'minimal',\n },\n },\n };\n }\n\n return {\n config: {\n ...midsceneDefaults,\n ...commonOverrideConfig,\n ...modelSpecificConfig,\n },\n };\n};\n\nconst extractInlineThought = (content: string): string | undefined => {\n const match = content.match(/<thought>([\\s\\S]*?)<\\/thought>/i);\n return match?.[1]?.trim() || undefined;\n};\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value);\n}\n\ntype GeminiExtractedContent = {\n content: string;\n geminiReasoningContent: string;\n};\n\nconst formatReasoningContent = ({\n geminiReasoningContent,\n providerReasoningContent,\n}: {\n geminiReasoningContent: string;\n providerReasoningContent: string;\n}): string => {\n if (geminiReasoningContent && providerReasoningContent) {\n return `thoughtParts:${geminiReasoningContent}; reasoning_content:${providerReasoningContent}`;\n }\n\n return geminiReasoningContent || providerReasoningContent || '';\n};\n\nconst extractGeminiThoughtParts = (\n content: GeminiContentPart[],\n): GeminiExtractedContent => {\n const contentParts: string[] = [];\n const reasoningParts: string[] = [];\n\n for (const part of content) {\n if (!isRecord(part)) {\n continue;\n }\n\n const text = typeof part.text === 'string' ? part.text : undefined;\n if (!text) {\n continue;\n }\n\n if (part.thought === true) {\n reasoningParts.push(text);\n } else {\n contentParts.push(text);\n }\n }\n\n return {\n content: contentParts.join(''),\n geminiReasoningContent: reasoningParts.join(''),\n };\n};\n\nexport const extractGeminiContentAndReasoning = (\n message: GeminiContentSource | undefined,\n): ContentAndReasoning => {\n // Gemini native API exposes thought summaries in\n // `response.candidates[0].content.parts`, where each text part can carry\n // `thought: true`. Some OpenAI-compatible adapters may pass through a\n // native-like content-parts shape, even though the Gemini OpenAI\n // compatibility docs do not guarantee it.\n // Docs: https://ai.google.dev/gemini-api/docs/thinking#thought-summaries\n\n if (!message) {\n return {\n content: '',\n reasoning_content: '',\n };\n }\n\n if (Array.isArray(message.content)) {\n const extracted = extractGeminiThoughtParts(message.content);\n\n return {\n content: extracted.content,\n reasoning_content: formatReasoningContent({\n geminiReasoningContent: extracted.geminiReasoningContent,\n providerReasoningContent:\n typeof message.reasoning_content === 'string'\n ? message.reasoning_content\n : '',\n }),\n };\n }\n\n const content = typeof message.content === 'string' ? message.content : '';\n // In real Gemini OpenAI-compatible responses we observed that\n // `include_thoughts` can still return a plain string `message.content`,\n // with the thought summary prepended as `<thought>...</thought>` before the\n // visible answer. Keep content unchanged, but extract that leading thought\n // text for report display.\n const geminiReasoningContent = extractInlineThought(content) || '';\n\n return {\n content,\n reasoning_content: formatReasoningContent({\n geminiReasoningContent,\n providerReasoningContent:\n typeof message.reasoning_content === 'string'\n ? message.reasoning_content\n : '',\n }),\n };\n};\n\nexport const geminiAdapters = {\n gemini: {\n chatCompletion: {\n unsupportedUserConfig: ['reasoningBudget'],\n buildChatCompletionParams: buildGeminiChatCompletionParams,\n messageExtraction: {\n kind: 'custom',\n extractContentAndReasoning: extractGeminiContentAndReasoning,\n },\n },\n locate: {\n element: {\n resultFormat: {\n coordinates: { shape: 'bbox', order: 'yx', normalizedBy: 1000 },\n },\n },\n },\n },\n} satisfies Pick<Record<TModelFamily, ModelAdapterDefinition>, 'gemini'>;\n"],"names":["buildGeminiChatCompletionParams","input","midsceneDefaults","userConfig","reasoningEnabled","reasoningEffort","commonOverrideConfig","undefined","modelSpecificConfig","extractInlineThought","content","match","isRecord","value","Array","formatReasoningContent","geminiReasoningContent","providerReasoningContent","extractGeminiThoughtParts","contentParts","reasoningParts","part","text","extractGeminiContentAndReasoning","message","extracted","geminiAdapters"],"mappings":"AA4BA,MAAMA,kCAAkC,CACtCC;IAEA,MAAM,EAAEC,gBAAgB,EAAEC,UAAU,EAAE,GAAGF;IACzC,MAAM,EAAEG,gBAAgB,EAAEC,eAAe,EAAE,GAAGF;IAC9C,MAAMG,uBAAgD,CAAC;IAEvD,IAAIH,AAA2BI,WAA3BJ,WAAW,WAAW,EACxBG,qBAAqB,WAAW,GAAGH,WAAW,WAAW;IAG3D,MAAMK,sBASF,CAAC;IAEL,IAAIJ,AAAqB,cAArBA,kBAMFI,oBAAoB,UAAU,GAAG;QAC/B,QAAQ;YACN,iBAAiB;gBACf,kBAAkB;gBAClB,gBAAgBJ,mBACXC,mBAAmB,WACpB;YACN;QACF;IACF;IAGF,OAAO;QACL,QAAQ;YACN,GAAGH,gBAAgB;YACnB,GAAGI,oBAAoB;YACvB,GAAGE,mBAAmB;QACxB;IACF;AACF;AAEA,MAAMC,uBAAuB,CAACC;IAC5B,MAAMC,QAAQD,QAAQ,KAAK,CAAC;IAC5B,OAAOC,OAAO,CAAC,EAAE,EAAE,UAAUJ;AAC/B;AAEA,SAASK,SAASC,KAAc;IAC9B,OAAO,CAAC,CAACA,SAAS,AAAiB,YAAjB,OAAOA,SAAsB,CAACC,MAAM,OAAO,CAACD;AAChE;AAOA,MAAME,yBAAyB,CAAC,EAC9BC,sBAAsB,EACtBC,wBAAwB,EAIzB;IACC,IAAID,0BAA0BC,0BAC5B,OAAO,CAAC,aAAa,EAAED,uBAAuB,oBA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B,MAAM;gBACN,4BAA4BuB;YAC9B;QACF;QACA,QAAQ;YACN,SAAS;gBACP,cAAc;oBACZ,aAAa;wBAAE,OAAO;wBAAQ,OAAO;wBAAM,cAAc;oBAAK;gBAChE;YACF;QACF;IACF;AACF"}
1
+ {"version":3,"file":"ai-model/models/gemini.mjs","sources":["../../../../src/ai-model/models/gemini.ts"],"sourcesContent":["import type { TModelFamily } from '@midscene/shared/env';\nimport type {\n ChatCompletionCallContext,\n ChatCompletionContentSource,\n ChatCompletionParamsResult,\n ContentAndReasoning,\n ModelAdapterDefinition,\n} from '../model-adapter/types';\n\nconst buildGeminiChatCompletionParams = (\n input: ChatCompletionCallContext,\n): ChatCompletionParamsResult => {\n const { midsceneDefaults, userConfig } = input;\n const { reasoningEnabled, reasoningEffort } = userConfig;\n const commonOverrideConfig: Record<string, unknown> = {};\n\n if (userConfig.temperature !== undefined) {\n commonOverrideConfig.temperature = userConfig.temperature;\n }\n\n const modelSpecificConfig: {\n extra_body?: {\n google?: {\n thinking_config: {\n include_thoughts: true;\n thinking_level: string;\n };\n };\n };\n } = {};\n\n if (reasoningEnabled !== 'default') {\n // Google documents OpenAI reasoning_effort mapping, but live tests on Gemini 4\n // rejected minimal instead of mapping it to low, so we keep Google's native config.\n // Minimum thinking levels vary by model; low is supported by most Gemini 3/4 models.\n modelSpecificConfig.extra_body = {\n google: {\n thinking_config: {\n include_thoughts: true,\n thinking_level: reasoningEnabled\n ? (reasoningEffort ?? 'medium')\n : 'low',\n },\n },\n };\n }\n\n return {\n config: {\n ...midsceneDefaults,\n ...commonOverrideConfig,\n ...modelSpecificConfig,\n },\n };\n};\n\nconst extractInlineThought = (content: string): string | undefined => {\n const match = content.match(/^<thought>([\\s\\S]*?)<\\/thought>/i);\n return match?.[1]?.trim() || undefined;\n};\n\nfunction formatReasoningContent({\n geminiReasoningContent,\n providerReasoningContent,\n}: {\n geminiReasoningContent: string;\n providerReasoningContent: string;\n}): string {\n if (geminiReasoningContent && providerReasoningContent) {\n return `inlineThought:${geminiReasoningContent}; reasoning_content:${providerReasoningContent}`;\n }\n\n return geminiReasoningContent || providerReasoningContent || '';\n}\n\nexport const extractGeminiContentAndReasoning = (\n message: ChatCompletionContentSource | undefined,\n): ContentAndReasoning => {\n if (!message) {\n return {\n content: '',\n reasoning_content: '',\n };\n }\n\n const content = typeof message.content === 'string' ? message.content : '';\n // Live tests with `include_thoughts` showed Google's endpoint prepending\n // summaries as `<thought>...</thought>` in content, while some relays\n // returned no reasoning. Extract the prefix without changing content.\n const geminiReasoningContent = extractInlineThought(content) || '';\n\n return {\n content,\n reasoning_content: formatReasoningContent({\n geminiReasoningContent,\n providerReasoningContent:\n typeof message.reasoning_content === 'string'\n ? message.reasoning_content\n : '',\n }),\n };\n};\n\nexport const geminiAdapters = {\n gemini: {\n chatCompletion: {\n unsupportedUserConfig: ['reasoningBudget'],\n buildChatCompletionParams: buildGeminiChatCompletionParams,\n messageExtraction: {\n kind: 'custom',\n extractContentAndReasoning: extractGeminiContentAndReasoning,\n },\n },\n locate: {\n element: {\n resultFormat: {\n coordinates: { shape: 'bbox', order: 'yx', normalizedBy: 1000 },\n },\n },\n },\n },\n} satisfies Pick<Record<TModelFamily, ModelAdapterDefinition>, 'gemini'>;\n"],"names":["buildGeminiChatCompletionParams","input","midsceneDefaults","userConfig","reasoningEnabled","reasoningEffort","commonOverrideConfig","undefined","modelSpecificConfig","extractInlineThought","content","match","formatReasoningContent","geminiReasoningContent","providerReasoningContent","extractGeminiContentAndReasoning","message","geminiAdapters"],"mappings":"AASA,MAAMA,kCAAkC,CACtCC;IAEA,MAAM,EAAEC,gBAAgB,EAAEC,UAAU,EAAE,GAAGF;IACzC,MAAM,EAAEG,gBAAgB,EAAEC,eAAe,EAAE,GAAGF;IAC9C,MAAMG,uBAAgD,CAAC;IAEvD,IAAIH,AAA2BI,WAA3BJ,WAAW,WAAW,EACxBG,qBAAqB,WAAW,GAAGH,WAAW,WAAW;IAG3D,MAAMK,sBASF,CAAC;IAEL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system-one.mjs";
2
2
  import { prepareSystemOne } from "./prepare-system-one.mjs";
3
- export { callSystemOne, prepareSystemOne };
3
+ import { resolveSystemOneEndpoint } from "./resolve-endpoint.mjs";
4
+ export { callSystemOne, prepareSystemOne, resolveSystemOneEndpoint };
@@ -1,13 +1,13 @@
1
1
  import { assert } from "@midscene/shared/utils";
2
+ import { getVersion } from "../../../utils.mjs";
2
3
  import { createProxyAgentIfNeeded } from "../proxy/index.mjs";
4
+ import { resolveSystemOneEndpoint } from "./resolve-endpoint.mjs";
3
5
  import { encodeSystemOneImages } from "./utils.mjs";
4
6
  async function prepareSystemOne(config, request) {
5
- assert(config.openaiBaseURL, 'Jev requires MIDSCENE_*_MODEL_BASE_URL');
6
7
  assert(config.openaiApiKey, 'Jev requires MIDSCENE_*_MODEL_API_KEY');
7
8
  assert(!config.protocol || 'openai-chat' === config.protocol, 'Jev uses System One, not the Responses API');
8
- const base = config.openaiBaseURL.replace(/\/+$/, '');
9
- const url = `${base}/systemone`;
10
- const isOpenRouter = 'openrouter.ai' === new URL(base).hostname;
9
+ const url = resolveSystemOneEndpoint(config);
10
+ const isOpenRouter = 'openrouter.ai' === new URL(url).hostname;
11
11
  const { imageState, assets } = encodeSystemOneImages(request.images, isOpenRouter);
12
12
  const body = {
13
13
  ...config.extraBody,
@@ -31,7 +31,8 @@ async function prepareSystemOne(config, request) {
31
31
  ...config.openaiExtraConfig?.defaultHeaders,
32
32
  Authorization: `Bearer ${config.openaiApiKey}`,
33
33
  'Content-Type': 'application/json',
34
- 'TypeSafe-Danger-Zone-Images': 'true'
34
+ 'TypeSafe-Danger-Zone-Images': 'true',
35
+ 'x-midscene-version': getVersion()
35
36
  },
36
37
  dispatcher: await createProxyAgentIfNeeded({
37
38
  socksProxy: config.socksProxy,
@@ -1 +1 @@
1
- {"version":3,"file":"ai-model/service-caller/system-one/prepare-system-one.mjs","sources":["../../../../../src/ai-model/service-caller/system-one/prepare-system-one.ts"],"sourcesContent":["import type { IModelConfig } from '@midscene/shared/env';\nimport { assert } from '@midscene/shared/utils';\nimport { createProxyAgentIfNeeded } from '../proxy';\nimport type { SystemOneRequest } from './schema';\nimport { encodeSystemOneImages } from './utils';\n\nexport async function prepareSystemOne(\n config: IModelConfig,\n request: SystemOneRequest,\n) {\n assert(config.openaiBaseURL, 'Jev requires MIDSCENE_*_MODEL_BASE_URL');\n assert(config.openaiApiKey, 'Jev requires MIDSCENE_*_MODEL_API_KEY');\n assert(\n !config.protocol || config.protocol === 'openai-chat',\n 'Jev uses System One, not the Responses API',\n );\n const base = config.openaiBaseURL.replace(/\\/+$/, '');\n const url = `${base}/systemone`;\n const isOpenRouter = new URL(base).hostname === 'openrouter.ai';\n const { imageState, assets } = encodeSystemOneImages(\n request.images,\n isOpenRouter,\n );\n const body = {\n ...config.extraBody,\n model: config.modelName,\n state: { ...request.state, ...imageState },\n questions: request.questions,\n ...(!isOpenRouter && Object.keys(assets).length ? { assets } : {}),\n };\n const serializedBody = JSON.stringify(body);\n assert(\n new TextEncoder().encode(serializedBody).length <= 32 * 1024 * 1024,\n 'Jev request exceeds the 32 MiB body limit',\n );\n return {\n url,\n body: serializedBody,\n questions: request.questions,\n headers: {\n ...(config.openaiExtraConfig?.defaultHeaders as\n | Record<string, string>\n | undefined),\n Authorization: `Bearer ${config.openaiApiKey}`,\n 'Content-Type': 'application/json',\n 'TypeSafe-Danger-Zone-Images': 'true',\n },\n dispatcher: await createProxyAgentIfNeeded({\n socksProxy: config.socksProxy,\n httpProxy: config.httpProxy,\n }),\n };\n}\n"],"names":["prepareSystemOne","config","request","assert","base","url","isOpenRouter","URL","imageState","assets","encodeSystemOneImages","body","Object","serializedBody","JSON","TextEncoder","createProxyAgentIfNeeded"],"mappings":";;;AAMO,eAAeA,iBACpBC,MAAoB,EACpBC,OAAyB;IAEzBC,OAAOF,OAAO,aAAa,EAAE;IAC7BE,OAAOF,OAAO,YAAY,EAAE;IAC5BE,OACE,CAACF,OAAO,QAAQ,IAAIA,AAAoB,kBAApBA,OAAO,QAAQ,EACnC;IAEF,MAAMG,OAAOH,OAAO,aAAa,CAAC,OAAO,CAAC,QAAQ;IAClD,MAAMI,MAAM,GAAGD,KAAK,UAAU,CAAC;IAC/B,MAAME,eAAe,AAA2B,oBAA3B,IAAIC,IAAIH,MAAM,QAAQ;IAC3C,MAAM,EAAEI,UAAU,EAAEC,MAAM,EAAE,GAAGC,sBAC7BR,QAAQ,MAAM,EACdI;IAEF,MAAMK,OAAO;QACX,GAAGV,OAAO,SAAS;QACnB,OAAOA,OAAO,SAAS;QACvB,OAAO;YAAE,GAAGC,QAAQ,KAAK;YAAE,GAAGM,UAAU;QAAC;QACzC,WAAWN,QAAQ,SAAS;QAC5B,GAAI,CAACI,gBAAgBM,OAAO,IAAI,CAACH,QAAQ,MAAM,GAAG;YAAEA;QAAO,IAAI,CAAC,CAAC;IACnE;IACA,MAAMI,iBAAiBC,KAAK,SAAS,CAACH;IACtCR,OACE,IAAIY,cAAc,MAAM,CAACF,gBAAgB,MAAM,IAAI,UACnD;IAEF,OAAO;QACLR;QACA,MAAMQ;QACN,WAAWX,QAAQ,SAAS;QAC5B,SAAS;YACP,GAAID,OAAO,iBAAiB,EAAE,cAAc;YAG5C,eAAe,CAAC,OAAO,EAAEA,OAAO,YAAY,EAAE;YAC9C,gBAAgB;YAChB,+BAA+B;QACjC;QACA,YAAY,MAAMe,yBAAyB;YACzC,YAAYf,OAAO,UAAU;YAC7B,WAAWA,OAAO,SAAS;QAC7B;IACF;AACF"}
1
+ {"version":3,"file":"ai-model/service-caller/system-one/prepare-system-one.mjs","sources":["../../../../../src/ai-model/service-caller/system-one/prepare-system-one.ts"],"sourcesContent":["import type { IModelConfig } from '@midscene/shared/env';\nimport { assert } from '@midscene/shared/utils';\nimport { getVersion } from '../../../utils';\nimport { createProxyAgentIfNeeded } from '../proxy';\nimport { resolveSystemOneEndpoint } from './resolve-endpoint';\nimport type { SystemOneRequest } from './schema';\nimport { encodeSystemOneImages } from './utils';\n\nexport async function prepareSystemOne(\n config: IModelConfig,\n request: SystemOneRequest,\n) {\n assert(config.openaiApiKey, 'Jev requires MIDSCENE_*_MODEL_API_KEY');\n assert(\n !config.protocol || config.protocol === 'openai-chat',\n 'Jev uses System One, not the Responses API',\n );\n const url = resolveSystemOneEndpoint(config);\n const isOpenRouter = new URL(url).hostname === 'openrouter.ai';\n const { imageState, assets } = encodeSystemOneImages(\n request.images,\n isOpenRouter,\n );\n const body = {\n ...config.extraBody,\n model: config.modelName,\n state: { ...request.state, ...imageState },\n questions: request.questions,\n ...(!isOpenRouter && Object.keys(assets).length ? { assets } : {}),\n };\n const serializedBody = JSON.stringify(body);\n assert(\n new TextEncoder().encode(serializedBody).length <= 32 * 1024 * 1024,\n 'Jev request exceeds the 32 MiB body limit',\n );\n return {\n url,\n body: serializedBody,\n questions: request.questions,\n headers: {\n ...(config.openaiExtraConfig?.defaultHeaders as\n | Record<string, string>\n | undefined),\n Authorization: `Bearer ${config.openaiApiKey}`,\n 'Content-Type': 'application/json',\n 'TypeSafe-Danger-Zone-Images': 'true',\n 'x-midscene-version': getVersion(),\n },\n dispatcher: await createProxyAgentIfNeeded({\n socksProxy: config.socksProxy,\n httpProxy: config.httpProxy,\n }),\n };\n}\n"],"names":["prepareSystemOne","config","request","assert","url","resolveSystemOneEndpoint","isOpenRouter","URL","imageState","assets","encodeSystemOneImages","body","Object","serializedBody","JSON","TextEncoder","getVersion","createProxyAgentIfNeeded"],"mappings":";;;;;AAQO,eAAeA,iBACpBC,MAAoB,EACpBC,OAAyB;IAEzBC,OAAOF,OAAO,YAAY,EAAE;IAC5BE,OACE,CAACF,OAAO,QAAQ,IAAIA,AAAoB,kBAApBA,OAAO,QAAQ,EACnC;IAEF,MAAMG,MAAMC,yBAAyBJ;IACrC,MAAMK,eAAe,AAA0B,oBAA1B,IAAIC,IAAIH,KAAK,QAAQ;IAC1C,MAAM,EAAEI,UAAU,EAAEC,MAAM,EAAE,GAAGC,sBAC7BR,QAAQ,MAAM,EACdI;IAEF,MAAMK,OAAO;QACX,GAAGV,OAAO,SAAS;QACnB,OAAOA,OAAO,SAAS;QACvB,OAAO;YAAE,GAAGC,QAAQ,KAAK;YAAE,GAAGM,UAAU;QAAC;QACzC,WAAWN,QAAQ,SAAS;QAC5B,GAAI,CAACI,gBAAgBM,OAAO,IAAI,CAACH,QAAQ,MAAM,GAAG;YAAEA;QAAO,IAAI,CAAC,CAAC;IACnE;IACA,MAAMI,iBAAiBC,KAAK,SAAS,CAACH;IACtCR,OACE,IAAIY,cAAc,MAAM,CAACF,gBAAgB,MAAM,IAAI,UACnD;IAEF,OAAO;QACLT;QACA,MAAMS;QACN,WAAWX,QAAQ,SAAS;QAC5B,SAAS;YACP,GAAID,OAAO,iBAAiB,EAAE,cAAc;YAG5C,eAAe,CAAC,OAAO,EAAEA,OAAO,YAAY,EAAE;YAC9C,gBAAgB;YAChB,+BAA+B;YAC/B,sBAAsBe;QACxB;QACA,YAAY,MAAMC,yBAAyB;YACzC,YAAYhB,OAAO,UAAU;YAC7B,WAAWA,OAAO,SAAS;QAC7B;IACF;AACF"}
@@ -0,0 +1,9 @@
1
+ import { assert } from "@midscene/shared/utils";
2
+ function resolveSystemOneEndpoint(config) {
3
+ if (config.endpoint) return config.endpoint;
4
+ assert(config.openaiBaseURL, 'When using the System One API, you must provide MIDSCENE_*_MODEL_ENDPOINT or MIDSCENE_*_MODEL_BASE_URL.');
5
+ return `${config.openaiBaseURL.replace(/\/+$/, '')}/systemone`;
6
+ }
7
+ export { resolveSystemOneEndpoint };
8
+
9
+ //# sourceMappingURL=resolve-endpoint.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ai-model/service-caller/system-one/resolve-endpoint.mjs","sources":["../../../../../src/ai-model/service-caller/system-one/resolve-endpoint.ts"],"sourcesContent":["import type { IModelConfig } from '@midscene/shared/env';\nimport { assert } from '@midscene/shared/utils';\n\nexport function resolveSystemOneEndpoint(config: IModelConfig): string {\n if (config.endpoint) {\n return config.endpoint;\n }\n assert(\n config.openaiBaseURL,\n 'When using the System One API, you must provide MIDSCENE_*_MODEL_ENDPOINT or MIDSCENE_*_MODEL_BASE_URL.',\n );\n return `${config.openaiBaseURL.replace(/\\/+$/, '')}/systemone`;\n}\n"],"names":["resolveSystemOneEndpoint","config","assert"],"mappings":";AAGO,SAASA,yBAAyBC,MAAoB;IAC3D,IAAIA,OAAO,QAAQ,EACjB,OAAOA,OAAO,QAAQ;IAExBC,OACED,OAAO,aAAa,EACpB;IAEF,OAAO,GAAGA,OAAO,aAAa,CAAC,OAAO,CAAC,QAAQ,IAAI,UAAU,CAAC;AAChE"}
@@ -1 +1 @@
1
- {"version":3,"file":"ai-model/service-caller/system-one/utils.mjs","sources":["../../../../../src/ai-model/service-caller/system-one/utils.ts"],"sourcesContent":["import { assert, uuid } from '@midscene/shared/utils';\nimport type { SystemOneRequest } from './schema';\n\nexport function encodeSystemOneImages(\n images: SystemOneRequest['images'],\n isOpenRouter: boolean,\n) {\n const assets: Record<string, unknown> = {};\n const imageState = Object.fromEntries(\n Object.entries(images ?? {}).map(([name, dataURL]) => {\n if (isOpenRouter) {\n return [name, { type: 'image_url', image_url: { url: dataURL } }];\n }\n const reference = uuid();\n const match = /^data:image\\/(png|jpe?g);base64,(.+)$/.exec(dataURL);\n assert(match, 'System One images must be prepared PNG or JPEG data URLs');\n assets[reference] = {\n type: 'image',\n format: match[1] === 'png' ? 'png' : 'jpg',\n data_base64: match[2],\n };\n return [name, reference];\n }),\n );\n return { imageState, assets };\n}\n"],"names":["encodeSystemOneImages","images","isOpenRouter","assets","imageState","Object","name","dataURL","reference","uuid","match","assert"],"mappings":";AAGO,SAASA,sBACdC,MAAkC,EAClCC,YAAqB;IAErB,MAAMC,SAAkC,CAAC;IACzC,MAAMC,aAAaC,OAAO,WAAW,CACnCA,OAAO,OAAO,CAACJ,UAAU,CAAC,GAAG,GAAG,CAAC,CAAC,CAACK,MAAMC,QAAQ;QAC/C,IAAIL,cACF,OAAO;YAACI;YAAM;gBAAE,MAAM;gBAAa,WAAW;oBAAE,KAAKC;gBAAQ;YAAE;SAAE;QAEnE,MAAMC,YAAYC;QAClB,MAAMC,QAAQ,wCAAwC,IAAI,CAACH;QAC3DI,OAAOD,OAAO;QACdP,MAAM,CAACK,UAAU,GAAG;YAClB,MAAM;YACN,QAAQE,AAAa,UAAbA,KAAK,CAAC,EAAE,GAAa,QAAQ;YACrC,aAAaA,KAAK,CAAC,EAAE;QACvB;QACA,OAAO;YAACJ;YAAME;SAAU;IAC1B;IAEF,OAAO;QAAEJ;QAAYD;IAAO;AAC9B"}
1
+ {"version":3,"file":"ai-model/service-caller/system-one/utils.mjs","sources":["../../../../../src/ai-model/service-caller/system-one/utils.ts"],"sourcesContent":["import { assert, uuid } from '@midscene/shared/utils';\nimport type { SystemOneRequest } from './schema';\n\nexport function encodeSystemOneImages(\n images: SystemOneRequest['images'],\n isOpenRouter: boolean,\n) {\n const assets: Record<string, unknown> = {};\n const imageState = Object.fromEntries(\n Object.entries(images ?? {}).map(([name, dataURL]) => {\n if (isOpenRouter) {\n // OpenRouter currently silently ignores TypeSafe's top-level assets map,\n // so a successful request may leave Jev unable to see the images.\n // Send inline image_url parts instead of asset references.\n // https://openrouter.ai/docs/guides/community/multimodal-decisions#image-part-format\n return [name, { type: 'image_url', image_url: { url: dataURL } }];\n }\n const reference = uuid();\n const match = /^data:image\\/(png|jpe?g);base64,(.+)$/.exec(dataURL);\n assert(match, 'System One images must be prepared PNG or JPEG data URLs');\n assets[reference] = {\n type: 'image',\n format: match[1] === 'png' ? 'png' : 'jpg',\n data_base64: match[2],\n };\n return [name, reference];\n }),\n );\n return { imageState, assets };\n}\n"],"names":["encodeSystemOneImages","images","isOpenRouter","assets","imageState","Object","name","dataURL","reference","uuid","match","assert"],"mappings":";AAGO,SAASA,sBACdC,MAAkC,EAClCC,YAAqB;IAErB,MAAMC,SAAkC,CAAC;IACzC,MAAMC,aAAaC,OAAO,WAAW,CACnCA,OAAO,OAAO,CAACJ,UAAU,CAAC,GAAG,GAAG,CAAC,CAAC,CAACK,MAAMC,QAAQ;QAC/C,IAAIL,cAKF,OAAO;YAACI;YAAM;gBAAE,MAAM;gBAAa,WAAW;oBAAE,KAAKC;gBAAQ;YAAE;SAAE;QAEnE,MAAMC,YAAYC;QAClB,MAAMC,QAAQ,wCAAwC,IAAI,CAACH;QAC3DI,OAAOD,OAAO;QACdP,MAAM,CAACK,UAAU,GAAG;YAClB,MAAM;YACN,QAAQE,AAAa,UAAbA,KAAK,CAAC,EAAE,GAAa,QAAQ;YACrC,aAAaA,KAAK,CAAC,EAAE;QACvB;QACA,OAAO;YAACJ;YAAME;SAAU;IAC1B;IAEF,OAAO;QAAEJ;QAAYD;IAAO;AAC9B"}