@midscene/core 1.17.4 → 1.17.5-beta-20261102094111.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/es/agent/agent.mjs +20 -4
- package/dist/es/agent/agent.mjs.map +1 -1
- package/dist/es/agent/plan-freshness.mjs +39 -0
- package/dist/es/agent/plan-freshness.mjs.map +1 -0
- package/dist/es/agent/planned-wait.mjs +62 -0
- package/dist/es/agent/planned-wait.mjs.map +1 -0
- package/dist/es/agent/tasks.mjs +103 -57
- package/dist/es/agent/tasks.mjs.map +1 -1
- package/dist/es/agent/utils.mjs +1 -1
- package/dist/es/ai-model/workflows/planning/custom-planning.mjs +1 -1
- package/dist/es/ai-model/workflows/planning/custom-planning.mjs.map +1 -1
- package/dist/es/ai-model/workflows/planning/standard-planning.mjs +1 -1
- package/dist/es/ai-model/workflows/planning/standard-planning.mjs.map +1 -1
- package/dist/es/report-html-template.mjs +1 -1
- package/dist/es/task-runner.mjs +16 -1
- package/dist/es/task-runner.mjs.map +1 -1
- package/dist/es/types.mjs.map +1 -1
- package/dist/es/utils.mjs +1 -1
- package/dist/lib/agent/agent.js +20 -4
- package/dist/lib/agent/agent.js.map +1 -1
- package/dist/lib/agent/plan-freshness.js +76 -0
- package/dist/lib/agent/plan-freshness.js.map +1 -0
- package/dist/lib/agent/planned-wait.js +105 -0
- package/dist/lib/agent/planned-wait.js.map +1 -0
- package/dist/lib/agent/tasks.js +102 -56
- package/dist/lib/agent/tasks.js.map +1 -1
- package/dist/lib/agent/utils.js +1 -1
- package/dist/lib/ai-model/workflows/planning/custom-planning.js +1 -1
- package/dist/lib/ai-model/workflows/planning/custom-planning.js.map +1 -1
- package/dist/lib/ai-model/workflows/planning/standard-planning.js +1 -1
- package/dist/lib/ai-model/workflows/planning/standard-planning.js.map +1 -1
- package/dist/lib/report-html-template.js +1 -1
- package/dist/lib/task-runner.js +15 -0
- package/dist/lib/task-runner.js.map +1 -1
- package/dist/lib/types.js.map +1 -1
- package/dist/lib/utils.js +1 -1
- package/dist/types/agent/agent.d.ts +9 -0
- package/dist/types/agent/agent.d.ts.map +1 -1
- package/dist/types/agent/plan-freshness.d.ts +15 -0
- package/dist/types/agent/plan-freshness.d.ts.map +1 -0
- package/dist/types/agent/planned-wait.d.ts +11 -0
- package/dist/types/agent/planned-wait.d.ts.map +1 -0
- package/dist/types/agent/tasks.d.ts +3 -1
- package/dist/types/agent/tasks.d.ts.map +1 -1
- package/dist/types/task-runner.d.ts +1 -0
- package/dist/types/task-runner.d.ts.map +1 -1
- package/dist/types/types.d.ts +10 -0
- package/dist/types/types.d.ts.map +1 -1
- package/package.json +2 -2
package/dist/es/task-runner.mjs
CHANGED
|
@@ -2,7 +2,7 @@ import { setTimingFieldOnce } from "./task-timing.mjs";
|
|
|
2
2
|
import { ExecutionDump } from "./types.mjs";
|
|
3
3
|
import { serializeError, truncateSerializedErrorString } from "@midscene/shared/agent-tools/error-formatter";
|
|
4
4
|
import { getDebug } from "@midscene/shared/logger";
|
|
5
|
-
import { assert, uuid } from "@midscene/shared/utils";
|
|
5
|
+
import { assert, sha256Hex, uuid } from "@midscene/shared/utils";
|
|
6
6
|
function _define_property(obj, key, value) {
|
|
7
7
|
if (key in obj) Object.defineProperty(obj, key, {
|
|
8
8
|
value: value,
|
|
@@ -81,8 +81,22 @@ class TaskRunner {
|
|
|
81
81
|
console.error('error while capturing screenshot', error);
|
|
82
82
|
}
|
|
83
83
|
}
|
|
84
|
+
logScreenshot(task, screenshot, phase) {
|
|
85
|
+
if (!screenshot) return;
|
|
86
|
+
debug('task screenshot %o', {
|
|
87
|
+
executionId: this.id,
|
|
88
|
+
taskId: task.taskId,
|
|
89
|
+
taskType: task.subType,
|
|
90
|
+
phase,
|
|
91
|
+
screenshotId: screenshot.id,
|
|
92
|
+
capturedAt: screenshot.capturedAt,
|
|
93
|
+
observedAt: Date.now(),
|
|
94
|
+
screenshotHash: sha256Hex(screenshot.base64).slice(0, 16)
|
|
95
|
+
});
|
|
96
|
+
}
|
|
84
97
|
attachRecorderItem(task, screenshot, phase) {
|
|
85
98
|
if (!phase || !screenshot) return;
|
|
99
|
+
this.logScreenshot(task, screenshot, phase);
|
|
86
100
|
const recorderItem = {
|
|
87
101
|
type: 'screenshot',
|
|
88
102
|
ts: Date.now(),
|
|
@@ -172,6 +186,7 @@ class TaskRunner {
|
|
|
172
186
|
setTimingFieldOnce(task.timing, 'getUiContextEnd');
|
|
173
187
|
this.abortSignal?.throwIfAborted();
|
|
174
188
|
task.uiContext = uiContext;
|
|
189
|
+
this.logScreenshot(task, uiContext?.screenshot, 'before-calling');
|
|
175
190
|
const executorContext = {
|
|
176
191
|
task,
|
|
177
192
|
element: previousFindOutput?.element,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"task-runner.mjs","sources":["../../src/task-runner.ts"],"sourcesContent":["import type { ScreenshotItem } from '@/screenshot-item';\nimport { setTimingFieldOnce } from '@/task-timing';\nimport {\n ExecutionDump,\n type ExecutionRecorderItem,\n type ExecutionTask,\n type ExecutionTaskActionApply,\n type ExecutionTaskApply,\n type ExecutionTaskPlanningLocateOutput,\n type ExecutionTaskProgressOptions,\n type ExecutionTaskReturn,\n type ExecutorContext,\n type PlanningActionParamError,\n type UIContext,\n} from '@/types';\nimport {\n type SerializedError,\n serializeError,\n truncateSerializedErrorString,\n} from '@midscene/shared/agent-tools/error-formatter';\nimport { getDebug } from '@midscene/shared/logger';\nimport { assert, uuid } from '@midscene/shared/utils';\n\nconst debug = getDebug('task-runner');\nconst UI_CONTEXT_CACHE_TTL_MS = 300;\n\n/**\n * A native, per-task lifecycle notification. The runner is the single source\n * of truth for when a task actually transitions, so it reports each transition\n * exactly once with the task that changed. Consumers no longer have to re-scan\n * the task list and diff it against remembered keys to reconstruct this stream.\n */\nexport type TaskRunnerEventKind =\n | 'append'\n | 'start'\n | 'finish'\n | 'error'\n | 'cancel';\n\nexport interface TaskRunnerEvent {\n kind: TaskRunnerEventKind;\n task: ExecutionTask;\n runner: TaskRunner;\n}\n\nexport interface SerializedErrorTask {\n taskId: string;\n type: ExecutionTask['type'];\n subType?: string;\n status: ExecutionTask['status'];\n thought?: string;\n errorMessage?: string;\n}\n\nexport interface SerializedTaskExecutionError extends SerializedError {\n code: 'TASK_EXECUTION_FAILED';\n cause: SerializedError;\n task?: SerializedErrorTask;\n}\n\nfunction serializeErrorTask(\n task: ExecutionTask | null,\n): SerializedErrorTask | undefined {\n if (!task) {\n return undefined;\n }\n\n return {\n taskId: truncateSerializedErrorString(task.taskId),\n type: task.type,\n ...(task.subType === undefined\n ? {}\n : { subType: truncateSerializedErrorString(task.subType) }),\n status: task.status,\n ...(task.thought === undefined\n ? {}\n : { thought: truncateSerializedErrorString(task.thought) }),\n ...(task.errorMessage === undefined\n ? {}\n : {\n errorMessage: truncateSerializedErrorString(task.errorMessage),\n }),\n };\n}\n\nexport type TaskRunnerEventListener = (\n event: TaskRunnerEvent,\n) => Promise<void> | void;\n\n/** Minimal prompt-image shape retained as report asset metadata. */\nexport interface ExecutionReferenceImage {\n readonly url: string;\n}\n\ntype TaskRunnerInitOptions = ExecutionTaskProgressOptions & {\n tasks?: ExecutionTaskApply[];\n abortSignal?: AbortSignal;\n referenceImages?: readonly ExecutionReferenceImage[];\n /**\n * Coarse \"the execution snapshot changed\" signal. Fires on any state change\n * (append, status flips, completion) with the whole runner, so consumers can\n * re-dump/re-render the current snapshot. Deliberately batch-granular, unlike\n * the per-task {@link onTaskEvent} stream.\n */\n onSnapshotChange?: (\n runner: TaskRunner,\n error?: TaskExecutionError,\n ) => Promise<void> | void;\n onTaskEvent?: TaskRunnerEventListener;\n};\n\ntype TaskRunnerOperationOptions = {\n allowWhenError?: boolean;\n};\n\nexport class TaskRunner {\n readonly id: string;\n name: string;\n\n tasks: ExecutionTask[];\n\n // status of runner\n status: 'init' | 'pending' | 'running' | 'completed' | 'error';\n\n onTaskStart?: ExecutionTaskProgressOptions['onTaskStart'];\n\n private readonly uiContextBuilder: (\n signal?: AbortSignal,\n ) => Promise<UIContext>;\n private readonly abortSignal?: AbortSignal;\n\n private readonly onSnapshotChange?:\n | ((runner: TaskRunner, error?: TaskExecutionError) => Promise<void> | void)\n | undefined;\n\n private readonly onTaskEvent?: TaskRunnerEventListener | undefined;\n\n private readonly executionLogTime: number;\n\n private readonly referenceImageUrls = new Set<string>();\n\n constructor(\n name: string,\n uiContextBuilder: (signal?: AbortSignal) => Promise<UIContext>,\n options?: TaskRunnerInitOptions,\n ) {\n this.id = uuid();\n this.status =\n options?.tasks && options.tasks.length > 0 ? 'pending' : 'init';\n this.name = name;\n this.tasks = (options?.tasks || []).map((item) =>\n this.markTaskAsPending(item),\n );\n this.onTaskStart = options?.onTaskStart;\n this.uiContextBuilder = uiContextBuilder;\n this.abortSignal = options?.abortSignal;\n this.onSnapshotChange = options?.onSnapshotChange;\n this.onTaskEvent = options?.onTaskEvent;\n this.executionLogTime = Date.now();\n for (const image of options?.referenceImages ?? []) {\n this.referenceImageUrls.add(image.url);\n }\n }\n\n private async emitSnapshotChange(error?: TaskExecutionError): Promise<void> {\n if (!this.onSnapshotChange) {\n return;\n }\n await this.onSnapshotChange(this, error);\n }\n\n private async emitTaskEvent(\n kind: TaskRunnerEventKind,\n task: ExecutionTask,\n ): Promise<void> {\n if (!this.onTaskEvent) {\n return;\n }\n try {\n await this.onTaskEvent({ kind, task, runner: this });\n } catch (error) {\n console.error('Error in onTaskEvent listener', error);\n }\n }\n\n private lastUiContext?: {\n context: UIContext;\n capturedAt: number;\n };\n\n private async getUiContext(options?: { forceRefresh?: boolean }): Promise<\n UIContext | undefined\n > {\n this.abortSignal?.throwIfAborted();\n const now = Date.now();\n const shouldReuse =\n !options?.forceRefresh &&\n this.lastUiContext &&\n now - this.lastUiContext.capturedAt <= UI_CONTEXT_CACHE_TTL_MS;\n\n if (shouldReuse && this.lastUiContext?.context) {\n debug(\n `reuse cached uiContext captured ${now - this.lastUiContext.capturedAt}ms ago`,\n );\n return this.lastUiContext?.context;\n }\n\n try {\n const uiContext = await this.uiContextBuilder(this.abortSignal);\n this.abortSignal?.throwIfAborted();\n if (uiContext) {\n this.lastUiContext = {\n context: uiContext,\n capturedAt: Date.now(),\n };\n } else {\n this.lastUiContext = undefined;\n }\n return uiContext;\n } catch (error) {\n this.lastUiContext = undefined;\n throw error;\n }\n }\n\n private async captureScreenshot(): Promise<ScreenshotItem | undefined> {\n try {\n const uiContext = await this.getUiContext({ forceRefresh: true });\n return uiContext?.screenshot;\n } catch (error) {\n console.error('error while capturing screenshot', error);\n }\n return undefined;\n }\n\n private attachRecorderItem(\n task: ExecutionTask,\n screenshot: ScreenshotItem | undefined,\n phase: 'after-calling',\n ): void {\n if (!phase || !screenshot) {\n return;\n }\n\n const recorderItem: ExecutionRecorderItem = {\n type: 'screenshot',\n ts: Date.now(),\n screenshot,\n timing: phase,\n };\n\n if (!task.recorder) {\n task.recorder = [recorderItem];\n return;\n }\n task.recorder.push(recorderItem);\n }\n\n private markTaskAsPending(task: ExecutionTaskApply): ExecutionTask {\n return {\n taskId: uuid(),\n status: 'pending',\n ...task,\n };\n }\n\n private normalizeStatusFromError(\n options?: TaskRunnerOperationOptions,\n errorMessage?: string,\n ): void {\n if (this.status !== 'error') {\n return;\n }\n assert(\n options?.allowWhenError,\n errorMessage ||\n `task runner is in error state, cannot proceed\\nerror=${this.latestErrorTask()?.errorMessage}\\n${this.latestErrorTask()?.errorStack}`,\n );\n // reset runner state so new tasks can run\n this.status = this.tasks.length > 0 ? 'pending' : 'init';\n }\n\n async append(\n task: ExecutionTaskApply[] | ExecutionTaskApply,\n options?: TaskRunnerOperationOptions,\n ): Promise<void> {\n this.abortSignal?.throwIfAborted();\n this.normalizeStatusFromError(\n options,\n `task runner is in error state, cannot append task\\nerror=${this.latestErrorTask()?.errorMessage}\\n${this.latestErrorTask()?.errorStack}`,\n );\n const appended: ExecutionTask[] = [];\n if (Array.isArray(task)) {\n appended.push(...task.map((item) => this.markTaskAsPending(item)));\n } else {\n appended.push(this.markTaskAsPending(task));\n }\n this.tasks.push(...appended);\n if (this.status !== 'running') {\n this.status = 'pending';\n }\n await this.emitSnapshotChange();\n for (const appendedTask of appended) {\n await this.emitTaskEvent('append', appendedTask);\n }\n }\n\n async appendAndFlush(\n task: ExecutionTaskApply[] | ExecutionTaskApply,\n options?: TaskRunnerOperationOptions,\n ): Promise<{ output: any; thought?: string } | undefined> {\n await this.append(task, options);\n return this.flush(options);\n }\n\n async flush(\n options?: TaskRunnerOperationOptions,\n ): Promise<{ output: any; thought?: string } | undefined> {\n if (this.status === 'init' && this.tasks.length > 0) {\n console.warn(\n 'illegal state for task runner, status is init but tasks are not empty',\n );\n }\n\n this.normalizeStatusFromError(options, 'task runner is in error state');\n assert(this.status !== 'running', 'task runner is already running');\n assert(this.status !== 'completed', 'task runner is already completed');\n\n const nextPendingIndex = this.tasks.findIndex(\n (task) => task.status === 'pending',\n );\n if (nextPendingIndex < 0) {\n // all tasks are completed\n return;\n }\n\n this.status = 'running';\n await this.emitSnapshotChange();\n let taskIndex = nextPendingIndex;\n let successfullyCompleted = true;\n\n let previousFindOutput: ExecutionTaskPlanningLocateOutput | undefined;\n\n while (taskIndex < this.tasks.length) {\n const task = this.tasks[taskIndex];\n assert(\n task.status === 'pending',\n `task status should be pending, but got: ${task.status}`,\n );\n let taskStarted = false;\n try {\n this.abortSignal?.throwIfAborted();\n taskStarted = true;\n task.timing = { start: Date.now() };\n task.status = 'running';\n await this.emitSnapshotChange();\n await this.emitTaskEvent('start', task);\n this.abortSignal?.throwIfAborted();\n try {\n if (this.onTaskStart) {\n await this.onTaskStart(task, this.abortSignal);\n }\n } catch (e) {\n console.error('error in onTaskStart', e);\n }\n this.abortSignal?.throwIfAborted();\n assert(\n ['Insight', 'Action Space', 'Planning'].indexOf(task.type) >= 0,\n `unsupported task type: ${task.type}`,\n );\n\n const { executor } = task;\n assert(executor, `executor is required for task type: ${task.type}`);\n\n let returnValue;\n // For Insight tasks (Query/Assert/WaitFor), always get fresh context\n // to ensure we have the latest UI state after any preceding actions\n const forceRefresh = task.type === 'Insight';\n setTimingFieldOnce(task.timing, 'getUiContextStart');\n const uiContext = await this.getUiContext({ forceRefresh });\n setTimingFieldOnce(task.timing, 'getUiContextEnd');\n this.abortSignal?.throwIfAborted();\n\n task.uiContext = uiContext;\n const executorContext: ExecutorContext = {\n task,\n element: previousFindOutput?.element,\n uiContext,\n signal: this.abortSignal,\n };\n\n if (task.type === 'Insight') {\n assert(\n task.subType === 'Query' ||\n task.subType === 'Assert' ||\n task.subType === 'WaitFor' ||\n task.subType === 'Boolean' ||\n task.subType === 'Number' ||\n task.subType === 'String',\n `unsupported service subType: ${task.subType}`,\n );\n returnValue = await task.executor(executorContext);\n } else if (task.type === 'Planning') {\n returnValue = await task.executor(executorContext);\n if (task.subType === 'Locate') {\n previousFindOutput = (\n returnValue as ExecutionTaskReturn<ExecutionTaskPlanningLocateOutput>\n )?.output;\n }\n } else if (task.type === 'Action Space') {\n try {\n returnValue = await task.executor(executorContext);\n } finally {\n // The short TTL still lets planning and the action itself share one\n // context. Once an action settles, time alone can no longer prove\n // that the cached context represents the current UI.\n this.lastUiContext = undefined;\n }\n } else {\n console.warn(\n `unsupported task type: ${task.type}, will try to execute it directly`,\n );\n returnValue = await task.executor(executorContext);\n }\n\n this.abortSignal?.throwIfAborted();\n const isLastTask = taskIndex === this.tasks.length - 1;\n\n if (isLastTask) {\n setTimingFieldOnce(task.timing, 'captureAfterCallingSnapshotStart');\n const screenshot = await this.captureScreenshot();\n this.abortSignal?.throwIfAborted();\n this.attachRecorderItem(task, screenshot, 'after-calling');\n setTimingFieldOnce(task.timing, 'captureAfterCallingSnapshotEnd');\n }\n // Cancellation may arrive during the report screenshot, after planning\n // has returned but before the next batch of actions is built.\n this.abortSignal?.throwIfAborted();\n\n Object.assign(task, returnValue);\n task.status = 'finished';\n task.timing.end = Date.now();\n task.timing.cost = task.timing.end - task.timing.start;\n await this.emitSnapshotChange();\n await this.emitTaskEvent('finish', task);\n taskIndex++;\n } catch (error) {\n successfullyCompleted = false;\n const serializedError = serializeError(error);\n task.error = serializedError;\n task.errorMessage = serializedError.message;\n task.errorStack = serializedError.stack;\n\n task.status = taskStarted ? 'failed' : 'cancelled';\n if (taskStarted && task.timing) {\n task.timing.end = Date.now();\n task.timing.cost = task.timing.end - task.timing.start;\n }\n await this.emitSnapshotChange();\n await this.emitTaskEvent(taskStarted ? 'error' : 'cancel', task);\n break;\n }\n }\n\n // set all remaining tasks as cancelled\n const cancelledTasks: ExecutionTask[] = [];\n for (let i = taskIndex + 1; i < this.tasks.length; i++) {\n this.tasks[i].status = 'cancelled';\n cancelledTasks.push(this.tasks[i]);\n }\n if (cancelledTasks.length > 0) {\n await this.emitSnapshotChange();\n for (const cancelledTask of cancelledTasks) {\n await this.emitTaskEvent('cancel', cancelledTask);\n }\n }\n\n let finalizeError: TaskExecutionError | undefined;\n if (!successfullyCompleted) {\n this.status = 'error';\n const errorTask = this.latestErrorTask();\n const error =\n errorTask?.error ??\n (this.abortSignal?.aborted\n ? serializeError(this.abortSignal.reason)\n : {\n name: 'Error',\n message: 'Task execution failed',\n });\n finalizeError = new TaskExecutionError(\n error,\n serializeErrorTask(errorTask),\n );\n await this.emitSnapshotChange(finalizeError);\n } else {\n this.status = 'completed';\n await this.emitSnapshotChange();\n }\n\n if (finalizeError) {\n throw finalizeError;\n }\n\n if (this.tasks.length) {\n // return the last output\n const outputIndex = Math.min(taskIndex, this.tasks.length - 1);\n const { thought, output } = this.tasks[outputIndex];\n return {\n thought,\n output,\n };\n }\n }\n\n isInErrorState(): boolean {\n return this.status === 'error';\n }\n\n latestErrorTask(): ExecutionTask | null {\n if (this.status !== 'error') {\n return null;\n }\n // Find the LAST failed task (not the first one)\n // This is important when using allowWhenError to continue after errors\n for (let i = this.tasks.length - 1; i >= 0; i--) {\n if (this.tasks[i].status === 'failed') {\n return this.tasks[i];\n }\n }\n return null;\n }\n\n dump(): ExecutionDump {\n return new ExecutionDump(\n {\n id: this.id,\n logTime: this.executionLogTime,\n name: this.name,\n tasks: this.tasks,\n },\n { referenceImageUrls: [...this.referenceImageUrls] },\n );\n }\n\n async appendErrorPlan(errorMsg: string): Promise<{\n output: undefined;\n runner: TaskRunner;\n }> {\n const errorTask: ExecutionTaskActionApply<PlanningActionParamError> = {\n type: 'Action Space',\n subType: 'Error',\n param: {\n thought: errorMsg,\n },\n thought: errorMsg,\n executor: async () => {\n throw new Error(errorMsg || 'error without thought');\n },\n };\n await this.appendAndFlush(errorTask);\n\n return {\n output: undefined,\n runner: this,\n };\n }\n}\n\nexport class TaskExecutionError extends Error {\n readonly code = 'TASK_EXECUTION_FAILED' as const;\n\n override readonly cause: SerializedError;\n\n readonly task?: SerializedErrorTask;\n\n constructor(error: SerializedError, task?: SerializedErrorTask) {\n super(error.message, { cause: error });\n this.name = 'TaskExecutionError';\n this.cause = error;\n this.task = task;\n if (this.stack) {\n this.stack = truncateSerializedErrorString(this.stack);\n }\n }\n\n /**\n * Return the same bounded fields already stored on the live error. The\n * wrapper stack identifies where TaskExecutionError was created; cause.stack\n * preserves the executor's original stack.\n */\n toJSON(): SerializedTaskExecutionError {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n ...(this.stack === undefined ? {} : { stack: this.stack }),\n cause: this.cause,\n ...(this.task === undefined ? {} : { task: this.task }),\n };\n }\n}\n"],"names":["debug","getDebug","UI_CONTEXT_CACHE_TTL_MS","serializeErrorTask","task","truncateSerializedErrorString","undefined","TaskRunner","error","kind","console","options","now","Date","shouldReuse","uiContext","screenshot","phase","recorderItem","uuid","errorMessage","assert","appended","Array","item","appendedTask","nextPendingIndex","taskIndex","successfullyCompleted","previousFindOutput","taskStarted","e","executor","returnValue","forceRefresh","setTimingFieldOnce","executorContext","isLastTask","Object","serializedError","serializeError","cancelledTasks","i","cancelledTask","finalizeError","errorTask","TaskExecutionError","outputIndex","Math","thought","output","ExecutionDump","errorMsg","Error","name","uiContextBuilder","Set","image"],"mappings":";;;;;;;;;;;;;;;AAuBA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AAmB,EAAE,CAChD,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC8C,MAAM,GAAG;IAEzC;AAoZF;AAEO,MAAMX,2BAA2BO;IAsBtC,SAAuC;QACrC,OAAO;YACL,MAAM,IAAI,CAAC,IAAI;YACf,MAAM,IAAI,CAAC,IAAI;YACf,SAAS,IAAI,CAAC,OAAO;YACrB,GAAI,AAAe/C,WAAf,IAAI,CAAC,KAAK,GAAiB,CAAC,IAAI;gBAAE,OAAO,IAAI,CAAC,KAAK;YAAC,CAAC;YACzD,OAAO,IAAI,CAAC,KAAK;YACjB,GAAI,AAAcA,WAAd,IAAI,CAAC,IAAI,GAAiB,CAAC,IAAI;gBAAE,MAAM,IAAI,CAAC,IAAI;YAAC,CAAC;QACxD;IACF;IAxBA,YAAYE,KAAsB,EAAEJ,IAA0B,CAAE;QAC9D,KAAK,CAACI,MAAM,OAAO,EAAE;YAAE,OAAOA;QAAM,IAPtC,uBAAS,QAAO,0BAEhB,uBAAkB,SAAlB,SAEA,uBAAS,QAAT;QAIE,IAAI,CAAC,IAAI,GAAG;QACZ,IAAI,CAAC,KAAK,GAAGA;QACb,IAAI,CAAC,IAAI,GAAGJ;QACZ,IAAI,IAAI,CAAC,KAAK,EACZ,IAAI,CAAC,KAAK,GAAGC,8BAA8B,IAAI,CAAC,KAAK;IAEzD;AAiBF"}
|
|
1
|
+
{"version":3,"file":"task-runner.mjs","sources":["../../src/task-runner.ts"],"sourcesContent":["import type { ScreenshotItem } from '@/screenshot-item';\nimport { setTimingFieldOnce } from '@/task-timing';\nimport {\n ExecutionDump,\n type ExecutionRecorderItem,\n type ExecutionTask,\n type ExecutionTaskActionApply,\n type ExecutionTaskApply,\n type ExecutionTaskPlanningLocateOutput,\n type ExecutionTaskProgressOptions,\n type ExecutionTaskReturn,\n type ExecutorContext,\n type PlanningActionParamError,\n type UIContext,\n} from '@/types';\nimport {\n type SerializedError,\n serializeError,\n truncateSerializedErrorString,\n} from '@midscene/shared/agent-tools/error-formatter';\nimport { getDebug } from '@midscene/shared/logger';\nimport { assert, sha256Hex, uuid } from '@midscene/shared/utils';\n\nconst debug = getDebug('task-runner');\nconst UI_CONTEXT_CACHE_TTL_MS = 300;\n\n/**\n * A native, per-task lifecycle notification. The runner is the single source\n * of truth for when a task actually transitions, so it reports each transition\n * exactly once with the task that changed. Consumers no longer have to re-scan\n * the task list and diff it against remembered keys to reconstruct this stream.\n */\nexport type TaskRunnerEventKind =\n | 'append'\n | 'start'\n | 'finish'\n | 'error'\n | 'cancel';\n\nexport interface TaskRunnerEvent {\n kind: TaskRunnerEventKind;\n task: ExecutionTask;\n runner: TaskRunner;\n}\n\nexport interface SerializedErrorTask {\n taskId: string;\n type: ExecutionTask['type'];\n subType?: string;\n status: ExecutionTask['status'];\n thought?: string;\n errorMessage?: string;\n}\n\nexport interface SerializedTaskExecutionError extends SerializedError {\n code: 'TASK_EXECUTION_FAILED';\n cause: SerializedError;\n task?: SerializedErrorTask;\n}\n\nfunction serializeErrorTask(\n task: ExecutionTask | null,\n): SerializedErrorTask | undefined {\n if (!task) {\n return undefined;\n }\n\n return {\n taskId: truncateSerializedErrorString(task.taskId),\n type: task.type,\n ...(task.subType === undefined\n ? {}\n : { subType: truncateSerializedErrorString(task.subType) }),\n status: task.status,\n ...(task.thought === undefined\n ? {}\n : { thought: truncateSerializedErrorString(task.thought) }),\n ...(task.errorMessage === undefined\n ? {}\n : {\n errorMessage: truncateSerializedErrorString(task.errorMessage),\n }),\n };\n}\n\nexport type TaskRunnerEventListener = (\n event: TaskRunnerEvent,\n) => Promise<void> | void;\n\n/** Minimal prompt-image shape retained as report asset metadata. */\nexport interface ExecutionReferenceImage {\n readonly url: string;\n}\n\ntype TaskRunnerInitOptions = ExecutionTaskProgressOptions & {\n tasks?: ExecutionTaskApply[];\n abortSignal?: AbortSignal;\n referenceImages?: readonly ExecutionReferenceImage[];\n /**\n * Coarse \"the execution snapshot changed\" signal. Fires on any state change\n * (append, status flips, completion) with the whole runner, so consumers can\n * re-dump/re-render the current snapshot. Deliberately batch-granular, unlike\n * the per-task {@link onTaskEvent} stream.\n */\n onSnapshotChange?: (\n runner: TaskRunner,\n error?: TaskExecutionError,\n ) => Promise<void> | void;\n onTaskEvent?: TaskRunnerEventListener;\n};\n\ntype TaskRunnerOperationOptions = {\n allowWhenError?: boolean;\n};\n\nexport class TaskRunner {\n readonly id: string;\n name: string;\n\n tasks: ExecutionTask[];\n\n // status of runner\n status: 'init' | 'pending' | 'running' | 'completed' | 'error';\n\n onTaskStart?: ExecutionTaskProgressOptions['onTaskStart'];\n\n private readonly uiContextBuilder: (\n signal?: AbortSignal,\n ) => Promise<UIContext>;\n private readonly abortSignal?: AbortSignal;\n\n private readonly onSnapshotChange?:\n | ((runner: TaskRunner, error?: TaskExecutionError) => Promise<void> | void)\n | undefined;\n\n private readonly onTaskEvent?: TaskRunnerEventListener | undefined;\n\n private readonly executionLogTime: number;\n\n private readonly referenceImageUrls = new Set<string>();\n\n constructor(\n name: string,\n uiContextBuilder: (signal?: AbortSignal) => Promise<UIContext>,\n options?: TaskRunnerInitOptions,\n ) {\n this.id = uuid();\n this.status =\n options?.tasks && options.tasks.length > 0 ? 'pending' : 'init';\n this.name = name;\n this.tasks = (options?.tasks || []).map((item) =>\n this.markTaskAsPending(item),\n );\n this.onTaskStart = options?.onTaskStart;\n this.uiContextBuilder = uiContextBuilder;\n this.abortSignal = options?.abortSignal;\n this.onSnapshotChange = options?.onSnapshotChange;\n this.onTaskEvent = options?.onTaskEvent;\n this.executionLogTime = Date.now();\n for (const image of options?.referenceImages ?? []) {\n this.referenceImageUrls.add(image.url);\n }\n }\n\n private async emitSnapshotChange(error?: TaskExecutionError): Promise<void> {\n if (!this.onSnapshotChange) {\n return;\n }\n await this.onSnapshotChange(this, error);\n }\n\n private async emitTaskEvent(\n kind: TaskRunnerEventKind,\n task: ExecutionTask,\n ): Promise<void> {\n if (!this.onTaskEvent) {\n return;\n }\n try {\n await this.onTaskEvent({ kind, task, runner: this });\n } catch (error) {\n console.error('Error in onTaskEvent listener', error);\n }\n }\n\n private lastUiContext?: {\n context: UIContext;\n capturedAt: number;\n };\n\n private async getUiContext(options?: { forceRefresh?: boolean }): Promise<\n UIContext | undefined\n > {\n this.abortSignal?.throwIfAborted();\n const now = Date.now();\n const shouldReuse =\n !options?.forceRefresh &&\n this.lastUiContext &&\n now - this.lastUiContext.capturedAt <= UI_CONTEXT_CACHE_TTL_MS;\n\n if (shouldReuse && this.lastUiContext?.context) {\n debug(\n `reuse cached uiContext captured ${now - this.lastUiContext.capturedAt}ms ago`,\n );\n return this.lastUiContext?.context;\n }\n\n try {\n const uiContext = await this.uiContextBuilder(this.abortSignal);\n this.abortSignal?.throwIfAborted();\n if (uiContext) {\n this.lastUiContext = {\n context: uiContext,\n capturedAt: Date.now(),\n };\n } else {\n this.lastUiContext = undefined;\n }\n return uiContext;\n } catch (error) {\n this.lastUiContext = undefined;\n throw error;\n }\n }\n\n private async captureScreenshot(): Promise<ScreenshotItem | undefined> {\n try {\n const uiContext = await this.getUiContext({ forceRefresh: true });\n return uiContext?.screenshot;\n } catch (error) {\n console.error('error while capturing screenshot', error);\n }\n return undefined;\n }\n\n private logScreenshot(\n task: ExecutionTask,\n screenshot: ScreenshotItem | undefined,\n phase: string,\n ) {\n if (!screenshot) return;\n debug('task screenshot %o', {\n executionId: this.id,\n taskId: task.taskId,\n taskType: task.subType,\n phase,\n screenshotId: screenshot.id,\n capturedAt: screenshot.capturedAt,\n observedAt: Date.now(),\n screenshotHash: sha256Hex(screenshot.base64).slice(0, 16),\n });\n }\n\n private attachRecorderItem(\n task: ExecutionTask,\n screenshot: ScreenshotItem | undefined,\n phase: 'after-calling',\n ): void {\n if (!phase || !screenshot) {\n return;\n }\n\n this.logScreenshot(task, screenshot, phase);\n const recorderItem: ExecutionRecorderItem = {\n type: 'screenshot',\n ts: Date.now(),\n screenshot,\n timing: phase,\n };\n\n if (!task.recorder) {\n task.recorder = [recorderItem];\n return;\n }\n task.recorder.push(recorderItem);\n }\n\n private markTaskAsPending(task: ExecutionTaskApply): ExecutionTask {\n return {\n taskId: uuid(),\n status: 'pending',\n ...task,\n };\n }\n\n private normalizeStatusFromError(\n options?: TaskRunnerOperationOptions,\n errorMessage?: string,\n ): void {\n if (this.status !== 'error') {\n return;\n }\n assert(\n options?.allowWhenError,\n errorMessage ||\n `task runner is in error state, cannot proceed\\nerror=${this.latestErrorTask()?.errorMessage}\\n${this.latestErrorTask()?.errorStack}`,\n );\n // reset runner state so new tasks can run\n this.status = this.tasks.length > 0 ? 'pending' : 'init';\n }\n\n async append(\n task: ExecutionTaskApply[] | ExecutionTaskApply,\n options?: TaskRunnerOperationOptions,\n ): Promise<void> {\n this.abortSignal?.throwIfAborted();\n this.normalizeStatusFromError(\n options,\n `task runner is in error state, cannot append task\\nerror=${this.latestErrorTask()?.errorMessage}\\n${this.latestErrorTask()?.errorStack}`,\n );\n const appended: ExecutionTask[] = [];\n if (Array.isArray(task)) {\n appended.push(...task.map((item) => this.markTaskAsPending(item)));\n } else {\n appended.push(this.markTaskAsPending(task));\n }\n this.tasks.push(...appended);\n if (this.status !== 'running') {\n this.status = 'pending';\n }\n await this.emitSnapshotChange();\n for (const appendedTask of appended) {\n await this.emitTaskEvent('append', appendedTask);\n }\n }\n\n async appendAndFlush(\n task: ExecutionTaskApply[] | ExecutionTaskApply,\n options?: TaskRunnerOperationOptions,\n ): Promise<{ output: any; thought?: string } | undefined> {\n await this.append(task, options);\n return this.flush(options);\n }\n\n async flush(\n options?: TaskRunnerOperationOptions,\n ): Promise<{ output: any; thought?: string } | undefined> {\n if (this.status === 'init' && this.tasks.length > 0) {\n console.warn(\n 'illegal state for task runner, status is init but tasks are not empty',\n );\n }\n\n this.normalizeStatusFromError(options, 'task runner is in error state');\n assert(this.status !== 'running', 'task runner is already running');\n assert(this.status !== 'completed', 'task runner is already completed');\n\n const nextPendingIndex = this.tasks.findIndex(\n (task) => task.status === 'pending',\n );\n if (nextPendingIndex < 0) {\n // all tasks are completed\n return;\n }\n\n this.status = 'running';\n await this.emitSnapshotChange();\n let taskIndex = nextPendingIndex;\n let successfullyCompleted = true;\n\n let previousFindOutput: ExecutionTaskPlanningLocateOutput | undefined;\n\n while (taskIndex < this.tasks.length) {\n const task = this.tasks[taskIndex];\n assert(\n task.status === 'pending',\n `task status should be pending, but got: ${task.status}`,\n );\n let taskStarted = false;\n try {\n this.abortSignal?.throwIfAborted();\n taskStarted = true;\n task.timing = { start: Date.now() };\n task.status = 'running';\n await this.emitSnapshotChange();\n await this.emitTaskEvent('start', task);\n this.abortSignal?.throwIfAborted();\n try {\n if (this.onTaskStart) {\n await this.onTaskStart(task, this.abortSignal);\n }\n } catch (e) {\n console.error('error in onTaskStart', e);\n }\n this.abortSignal?.throwIfAborted();\n assert(\n ['Insight', 'Action Space', 'Planning'].indexOf(task.type) >= 0,\n `unsupported task type: ${task.type}`,\n );\n\n const { executor } = task;\n assert(executor, `executor is required for task type: ${task.type}`);\n\n let returnValue;\n // For Insight tasks (Query/Assert/WaitFor), always get fresh context\n // to ensure we have the latest UI state after any preceding actions\n const forceRefresh = task.type === 'Insight';\n setTimingFieldOnce(task.timing, 'getUiContextStart');\n const uiContext = await this.getUiContext({ forceRefresh });\n setTimingFieldOnce(task.timing, 'getUiContextEnd');\n this.abortSignal?.throwIfAborted();\n\n task.uiContext = uiContext;\n this.logScreenshot(task, uiContext?.screenshot, 'before-calling');\n const executorContext: ExecutorContext = {\n task,\n element: previousFindOutput?.element,\n uiContext,\n signal: this.abortSignal,\n };\n\n if (task.type === 'Insight') {\n assert(\n task.subType === 'Query' ||\n task.subType === 'Assert' ||\n task.subType === 'WaitFor' ||\n task.subType === 'Boolean' ||\n task.subType === 'Number' ||\n task.subType === 'String',\n `unsupported service subType: ${task.subType}`,\n );\n returnValue = await task.executor(executorContext);\n } else if (task.type === 'Planning') {\n returnValue = await task.executor(executorContext);\n if (task.subType === 'Locate') {\n previousFindOutput = (\n returnValue as ExecutionTaskReturn<ExecutionTaskPlanningLocateOutput>\n )?.output;\n }\n } else if (task.type === 'Action Space') {\n try {\n returnValue = await task.executor(executorContext);\n } finally {\n // The short TTL still lets planning and the action itself share one\n // context. Once an action settles, time alone can no longer prove\n // that the cached context represents the current UI.\n this.lastUiContext = undefined;\n }\n } else {\n console.warn(\n `unsupported task type: ${task.type}, will try to execute it directly`,\n );\n returnValue = await task.executor(executorContext);\n }\n\n this.abortSignal?.throwIfAborted();\n const isLastTask = taskIndex === this.tasks.length - 1;\n\n if (isLastTask) {\n setTimingFieldOnce(task.timing, 'captureAfterCallingSnapshotStart');\n const screenshot = await this.captureScreenshot();\n this.abortSignal?.throwIfAborted();\n this.attachRecorderItem(task, screenshot, 'after-calling');\n setTimingFieldOnce(task.timing, 'captureAfterCallingSnapshotEnd');\n }\n // Cancellation may arrive during the report screenshot, after planning\n // has returned but before the next batch of actions is built.\n this.abortSignal?.throwIfAborted();\n\n Object.assign(task, returnValue);\n task.status = 'finished';\n task.timing.end = Date.now();\n task.timing.cost = task.timing.end - task.timing.start;\n await this.emitSnapshotChange();\n await this.emitTaskEvent('finish', task);\n taskIndex++;\n } catch (error) {\n successfullyCompleted = false;\n const serializedError = serializeError(error);\n task.error = serializedError;\n task.errorMessage = serializedError.message;\n task.errorStack = serializedError.stack;\n\n task.status = taskStarted ? 'failed' : 'cancelled';\n if (taskStarted && task.timing) {\n task.timing.end = Date.now();\n task.timing.cost = task.timing.end - task.timing.start;\n }\n await this.emitSnapshotChange();\n await this.emitTaskEvent(taskStarted ? 'error' : 'cancel', task);\n break;\n }\n }\n\n // set all remaining tasks as cancelled\n const cancelledTasks: ExecutionTask[] = [];\n for (let i = taskIndex + 1; i < this.tasks.length; i++) {\n this.tasks[i].status = 'cancelled';\n cancelledTasks.push(this.tasks[i]);\n }\n if (cancelledTasks.length > 0) {\n await this.emitSnapshotChange();\n for (const cancelledTask of cancelledTasks) {\n await this.emitTaskEvent('cancel', cancelledTask);\n }\n }\n\n let finalizeError: TaskExecutionError | undefined;\n if (!successfullyCompleted) {\n this.status = 'error';\n const errorTask = this.latestErrorTask();\n const error =\n errorTask?.error ??\n (this.abortSignal?.aborted\n ? serializeError(this.abortSignal.reason)\n : {\n name: 'Error',\n message: 'Task execution failed',\n });\n finalizeError = new TaskExecutionError(\n error,\n serializeErrorTask(errorTask),\n );\n await this.emitSnapshotChange(finalizeError);\n } else {\n this.status = 'completed';\n await this.emitSnapshotChange();\n }\n\n if (finalizeError) {\n throw finalizeError;\n }\n\n if (this.tasks.length) {\n // return the last output\n const outputIndex = Math.min(taskIndex, this.tasks.length - 1);\n const { thought, output } = this.tasks[outputIndex];\n return {\n thought,\n output,\n };\n }\n }\n\n isInErrorState(): boolean {\n return this.status === 'error';\n }\n\n latestErrorTask(): ExecutionTask | null {\n if (this.status !== 'error') {\n return null;\n }\n // Find the LAST failed task (not the first one)\n // This is important when using allowWhenError to continue after errors\n for (let i = this.tasks.length - 1; i >= 0; i--) {\n if (this.tasks[i].status === 'failed') {\n return this.tasks[i];\n }\n }\n return null;\n }\n\n dump(): ExecutionDump {\n return new ExecutionDump(\n {\n id: this.id,\n logTime: this.executionLogTime,\n name: this.name,\n tasks: this.tasks,\n },\n { referenceImageUrls: [...this.referenceImageUrls] },\n );\n }\n\n async appendErrorPlan(errorMsg: string): Promise<{\n output: undefined;\n runner: TaskRunner;\n }> {\n const errorTask: ExecutionTaskActionApply<PlanningActionParamError> = {\n type: 'Action Space',\n subType: 'Error',\n param: {\n thought: errorMsg,\n },\n thought: errorMsg,\n executor: async () => {\n throw new Error(errorMsg || 'error without thought');\n },\n };\n await this.appendAndFlush(errorTask);\n\n return {\n output: undefined,\n runner: this,\n };\n }\n}\n\nexport class TaskExecutionError extends Error {\n readonly code = 'TASK_EXECUTION_FAILED' as const;\n\n override readonly cause: SerializedError;\n\n readonly task?: SerializedErrorTask;\n\n constructor(error: SerializedError, task?: SerializedErrorTask) {\n super(error.message, { cause: error });\n this.name = 'TaskExecutionError';\n this.cause = error;\n this.task = task;\n if (this.stack) {\n this.stack = truncateSerializedErrorString(this.stack);\n }\n }\n\n /**\n * Return the same bounded fields already stored on the live error. The\n * wrapper stack identifies where TaskExecutionError was created; cause.stack\n * preserves the executor's original stack.\n */\n toJSON(): SerializedTaskExecutionError {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n ...(this.stack === undefined ? {} : { stack: this.stack }),\n cause: this.cause,\n ...(this.task === undefined ? {} : { task: this.task }),\n };\n }\n}\n"],"names":["debug","getDebug","UI_CONTEXT_CACHE_TTL_MS","serializeErrorTask","task","truncateSerializedErrorString","undefined","TaskRunner","error","kind","console","options","now","Date","shouldReuse","uiContext","screenshot","phase","sha256Hex","recorderItem","uuid","errorMessage","assert","appended","Array","item","appendedTask","nextPendingIndex","taskIndex","successfullyCompleted","previousFindOutput","taskStarted","e","executor","returnValue","forceRefresh","setTimingFieldOnce","executorContext","isLastTask","Object","serializedError","serializeError","cancelledTasks","i","cancelledTask","finalizeError","errorTask","TaskExecutionError","outputIndex","Math","thought","output","ExecutionDump","errorMsg","Error","name","uiContextBuilder","Set","image"],"mappings":";;;;;;;;;;;;;;;AAuBA,MAAMA,QAAQC,SAAS;AACvB,MAAMC,0BAA0B;AAoChC,SAASC,mBACPC,IAA0B;IAE1B,IAAI,CAACA,MACH;IAGF,OAAO;QACL,QAAQC,8BAA8BD,KAAK,MAAM;QACjD,MAAMA,KAAK,IAAI;QACf,GAAIA,AAAiBE,WAAjBF,KAAK,OAAO,GACZ,CAAC,IACD;YAAE,SAASC,8BAA8BD,KAAK,OAAO;QAAE,CAAC;QAC5D,QAAQA,KAAK,MAAM;QACnB,GAAIA,AAAiBE,WAAjBF,KAAK,OAAO,GACZ,CAAC,IACD;YAAE,SAASC,8BAA8BD,KAAK,OAAO;QAAE,CAAC;QAC5D,GAAIA,AAAsBE,WAAtBF,KAAK,YAAY,GACjB,CAAC,IACD;YACE,cAAcC,8BAA8BD,KAAK,YAAY;QAC/D,CAAC;IACP;AACF;AAgCO,MAAMG;IAiDX,MAAc,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C,SAAuC;QACrC,OAAO;YACL,MAAM,IAAI,CAAC,IAAI;YACf,MAAM,IAAI,CAAC,IAAI;YACf,SAAS,IAAI,CAAC,OAAO;YACrB,GAAI,AAAehD,WAAf,IAAI,CAAC,KAAK,GAAiB,CAAC,IAAI;gBAAE,OAAO,IAAI,CAAC,KAAK;YAAC,CAAC;YACzD,OAAO,IAAI,CAAC,KAAK;YACjB,GAAI,AAAcA,WAAd,IAAI,CAAC,IAAI,GAAiB,CAAC,IAAI;gBAAE,MAAM,IAAI,CAAC,IAAI;YAAC,CAAC;QACxD;IACF;IAxBA,YAAYE,KAAsB,EAAEJ,IAA0B,CAAE;QAC9D,KAAK,CAACI,MAAM,OAAO,EAAE;YAAE,OAAOA;QAAM,IAPtC,uBAAS,QAAO,0BAEhB,uBAAkB,SAAlB,SAEA,uBAAS,QAAT;QAIE,IAAI,CAAC,IAAI,GAAG;QACZ,IAAI,CAAC,KAAK,GAAGA;QACb,IAAI,CAAC,IAAI,GAAGJ;QACZ,IAAI,IAAI,CAAC,KAAK,EACZ,IAAI,CAAC,KAAK,GAAGC,8BAA8B,IAAI,CAAC,KAAK;IAEzD;AAiBF"}
|
package/dist/es/types.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.mjs","sources":["../../src/types.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { AgentAIContexts } from '@midscene/shared/agent-tools/agent-context';\nimport type { SerializedError } from '@midscene/shared/agent-tools/error-formatter';\nimport type { NodeType } from '@midscene/shared/constants';\nimport type { CreateOpenAIClientFn, TModelConfig } from '@midscene/shared/env';\nimport type {\n BaseElement,\n LocateResultElement,\n Rect,\n Size,\n} from '@midscene/shared/types';\nimport type OpenAI from 'openai';\nimport type { z } from 'zod';\nimport type { TUserPrompt } from './common';\nimport type { ScreenshotItem } from './screenshot-item';\nimport type {\n DetailedLocateParam,\n MidsceneYamlFlowItem,\n ServiceExtractOption,\n} from './yaml';\n\nexport type {\n ElementTreeNode,\n BaseElement,\n Rect,\n Size,\n Point,\n} from '@midscene/shared/types';\nexport type { SerializedError } from '@midscene/shared/agent-tools/error-formatter';\nexport type {\n AgentAIContextKey,\n AgentAIContexts,\n AiApiName,\n} from '@midscene/shared/agent-tools/agent-context';\nexport * from './yaml';\n\nexport { ServiceError } from './errors';\nexport {\n ExecutionDump,\n ReportActionDump,\n GroupedActionDump,\n} from './dump/report-action-dump';\n\nexport type RawAssistantOutput =\n | {\n type: 'chat-completion';\n rawValue: OpenAI.Chat.Completions.ChatCompletionMessage;\n }\n | {\n type: 'responses';\n rawValue: OpenAI.Responses.ResponseOutputItem[];\n };\n\nexport type AIUsageInfo = Record<string, any> & {\n prompt_tokens: number | undefined;\n completion_tokens: number | undefined;\n total_tokens: number | undefined;\n cached_input: number | undefined;\n /** Duration of the final successful request attempt, in milliseconds. */\n time_cost: number | undefined;\n /** Request duration including all attempts and retry waits, excluding preparation, in milliseconds. */\n total_time_cost?: number;\n /** Request retries performed within this call; excludes semantic parse retries. */\n retry_count?: number;\n /** Actual protocol used for the model call, resolved by Midscene. */\n request_kind?: 'chat-completion' | 'responses' | 'codex' | 'system-one';\n /** Why a task uses the default model instead of its configured specialist. */\n modelFallback?: {\n requestedModel: string;\n requestedSlot: string;\n taskType: string;\n reason: string;\n };\n /** Whether the model call used streaming, after resolving call options. */\n stream?: boolean;\n model_name: string | undefined;\n model_description: string | undefined;\n /**\n * Raw top-level `.model` value returned by the model service response.\n */\n response_model_name: string | undefined;\n /**\n * Semantic intent of the model call, such as default, planning, or insight.\n */\n intent: string | undefined;\n /**\n * Config slot where the model config was resolved from. For example, a\n * planning call may use the default slot when no planning model is configured.\n */\n slot: string | undefined;\n request_id: string | undefined;\n};\n\nexport type { LocateResultElement };\n\nexport type AISingleElementResponseByPosition = {\n position?: {\n x: number;\n y: number;\n };\n bbox?: [number, number, number, number];\n reason: string;\n text: string;\n};\n\nexport type LocateResultPoint = [number, number];\nexport type Bbox = [number, number, number, number];\nexport type LocateResultBbox = Bbox;\nexport type PixelBbox = Bbox;\n\nexport interface AIElementLocateResponse {\n bbox?: LocateResultBbox;\n point?: LocateResultPoint;\n error?: string;\n}\n\nexport interface AIDataExtractionResponse<DataDemand> {\n data: DataDemand;\n errors?: string[];\n thought?: string;\n}\n\nexport interface AISectionLocatorResponse {\n bbox?: LocateResultBbox;\n point?: LocateResultPoint;\n references_bbox?: LocateResultBbox[];\n references_point?: LocateResultPoint[];\n error?: string;\n}\n\nexport interface AIAssertionResponse {\n pass: boolean;\n thought: string;\n}\n\nexport interface AIDescribeElementResponse {\n description: string;\n error?: string;\n}\n\nexport interface LocatorValidatorOption {\n centerDistanceThreshold?: number;\n}\n\nexport interface LocateValidatorResult {\n pass: boolean;\n rect?: Rect;\n center: [number, number];\n centerDistance?: number;\n /** Whether the expected point is inside the located rect; absent for point-only results. */\n includedInRect?: boolean;\n}\n\nexport interface AgentDescribeElementAtPointResult {\n prompt: string;\n deepLocate: boolean;\n deepDescribe: boolean;\n verifyResult?: LocateValidatorResult;\n success: boolean;\n error?: string;\n failureStage?: 'describe' | 'verify';\n}\n\n/**\n * context\n */\n\nexport interface UiNode {\n type: string;\n attrs: Record<string, string | undefined>;\n bounds: Rect;\n children: UiNode[];\n}\n\nexport interface UITreeSnapshot {\n platform: 'android';\n capturedAt: number;\n root: UiNode;\n}\n\nexport abstract class UIContext {\n /**\n * screenshot of the current UI state. which size is shotSize(be shrunk by screenshotShrinkFactor),\n */\n abstract screenshot: ScreenshotItem;\n\n /**\n * Optional sequence of screenshots captured over a short time window, in\n * temporal order (earliest first, latest last). When present with more than\n * one frame, extract/assert flows submit all frames to the model so it can\n * observe transient UI (toasts, carousels, auto-hiding controls). The last\n * frame is the same state as {@link screenshot}.\n */\n abstract screenshotSequence?: ScreenshotItem[];\n\n /**\n * screenshot size after shrinking\n */\n abstract shotSize: Size;\n\n /**\n * The ratio for converting shrunk screenshot coordinates to logical coordinates.\n *\n * Example:\n * - Physical screen width: 3000px, dpr=6\n * - Logical width: 500px\n * - User-defined screenshotShrinkFactor: 2\n * - Actual shrunk screenshot width: 3000 / 2 = 1500px\n * - shrunkShotToLogicalRatio: dpr / screenshotShrinkFactor = 6 / 2 = 3\n * - To map back to logical coordinates: 1500 / shrunkShotToLogicalRatio = 500px\n */\n abstract shrunkShotToLogicalRatio: number;\n\n abstract _isFrozen?: boolean;\n\n // @deprecated - backward compatibility for aiLocate\n abstract deprecatedDpr?: number;\n}\n\nexport type EnsureObject<T> = { [K in keyof T]: any };\n\nexport type ServiceAction = 'locate' | 'extract' | 'assert' | 'describe';\n\nexport type ServiceExtractParam = string | Record<string, string>;\n\nexport type ElementCacheFeature = Record<string, unknown>;\n\nexport interface LocateResult {\n element: LocateResultElement | null;\n}\n\nexport type ThinkingLevel = 'off' | 'medium' | 'high';\n\nexport type AiActEffort = 'fast' | 'balance' | 'deepThink';\n\nexport type DeepThinkOption = 'unset' | true | false;\n\nexport interface ServiceTaskInfo {\n durationMs: number;\n formatResponse?: unknown;\n /**\n * Adapter-extracted content used by Midscene for parsing. This is not the\n * full provider response or choices[0].message.\n */\n rawResponse?: unknown;\n rawAssistantOutput?: RawAssistantOutput;\n usage?: AIUsageInfo;\n searchArea?: Rect;\n /**\n * Adapter-extracted content from the search-area model call. This is not the\n * full provider response or choices[0].message.\n */\n searchAreaRawResponse?: string;\n searchAreaRawChoiceMessage?: unknown;\n searchAreaUsage?: AIUsageInfo;\n reasoning_content?: string;\n}\n\nexport interface DumpMeta {\n logTime: number;\n}\n\nexport type ReportAttributes = Record<\n string,\n string | number | boolean | null | undefined\n>;\n\nexport interface ReportDumpWithAttributes {\n dumpString: string;\n attributes?: ReportAttributes;\n}\n\nexport interface ServiceDump extends DumpMeta {\n type: 'locate' | 'extract' | 'assert';\n logId: string;\n userQuery: {\n element?: TUserPrompt;\n dataDemand?: ServiceExtractParam;\n assertion?: TUserPrompt;\n };\n matchedElement?: LocateResultElement[];\n deepLocate?: boolean;\n data: any;\n assertionPass?: boolean;\n assertionThought?: string;\n taskInfo: ServiceTaskInfo;\n error?: string;\n output?: any;\n}\n\nexport type PartialServiceDumpFromSDK = Omit<\n ServiceDump,\n 'logTime' | 'logId' | 'model_name'\n>;\n\nexport interface ServiceResultBase {\n dump: ServiceDump;\n}\n\nexport type LocateResultWithDump = LocateResult & ServiceResultBase;\n\nexport interface ServiceExtractResult<T> extends ServiceResultBase {\n data: T;\n thought?: string;\n usage?: AIUsageInfo;\n reasoning_content?: string;\n}\n\n// intermediate variables to optimize the return value by AI\nexport interface LiteUISection {\n name: string;\n description: string;\n sectionCharacteristics: string;\n textIds: string[];\n}\n\nexport type ElementById = (id: string) => BaseElement | null;\n\nexport type ServiceAssertionResponse = AIAssertionResponse & {\n usage?: AIUsageInfo;\n};\n\n/**\n * agent\n */\n\nexport type OnTaskStartTip = (tip: string) => Promise<void> | void;\n\nexport interface AgentWaitForOpt extends ServiceExtractOption {\n checkIntervalMs?: number;\n timeoutMs?: number;\n}\n\nexport interface AgentAssertOpt {\n keepRawResponse?: boolean;\n /**\n * Additional facts, decision rules, constraints, or output requirements for\n * this assertion. It overrides `aiContexts.aiAssert` and\n * `aiContexts.default`;\n * `''` disables inherited user context for this call.\n */\n context?: string;\n abortSignal?: AbortSignal;\n}\n\nexport interface AgentAssertResult {\n pass: boolean;\n thought?: string;\n message?: string;\n}\n\nexport type QueryOptions = ServiceExtractOption;\nexport type AssertOptions = AgentAssertOpt & ServiceExtractOption;\n\n/** Options for fixed observations, which never read the live DOM. */\nexport type ObservationQueryOptions = Omit<QueryOptions, 'domIncluded'> & {\n domIncluded?: never;\n};\n\n/** Assertion options for fixed observations, which never read the live DOM. */\nexport type ObservationAssertOptions = Omit<AssertOptions, 'domIncluded'> & {\n domIncluded?: never;\n};\n\n/** Read-only AI operations supported by both live Agents and UI observations. */\nexport interface InsightAPI<\n QueryOpt extends QueryOptions = QueryOptions,\n AssertOpt extends AssertOptions = AssertOptions,\n> {\n aiQuery<ReturnType = any>(\n demand: ServiceExtractParam,\n options?: QueryOpt,\n ): Promise<ReturnType>;\n aiBoolean(prompt: TUserPrompt, options?: QueryOpt): Promise<boolean>;\n aiNumber(prompt: TUserPrompt, options?: QueryOpt): Promise<number>;\n aiString(prompt: TUserPrompt, options?: QueryOpt): Promise<string>;\n aiAsk(prompt: TUserPrompt, options?: QueryOpt): Promise<string>;\n aiAssert(\n assertion: TUserPrompt,\n message?: string,\n options?: AssertOpt,\n ): Promise<AgentAssertResult | undefined>;\n}\n\n/**\n * planning\n *\n */\n\ntype PlanningActionBase = {\n thought?: string;\n log?: string; // a brief preamble to the user explaining what you’re about to do\n type: string;\n};\n\nexport type PlanningAction<ParamType = undefined> = PlanningActionBase &\n ([ParamType] extends [undefined] ? { param?: any } : { param: ParamType });\n\nexport type SubGoalStatus = 'pending' | 'running' | 'finished';\n\nexport interface SubGoal {\n index: number;\n status: SubGoalStatus;\n description: string;\n logs?: string[];\n}\n\nexport interface RawResponsePlanningAIResponse {\n action: PlanningAction | null;\n thought?: string;\n log: string;\n memory?: string;\n error?: string;\n finalizeMessage?: string;\n finalizeSuccess?: boolean;\n updateSubGoals?: SubGoal[];\n markFinishedIndexes?: number[];\n}\n\nexport interface PlanningAIResponse\n extends Omit<RawResponsePlanningAIResponse, 'action'> {\n actions?: PlanningAction[];\n /** Request another planning cycle using the default model, without executing actions. */\n delegation?: {\n reason: string;\n suggestedAction?: string;\n };\n usage?: AIUsageInfo;\n /**\n * Adapter-extracted content used by Midscene for parsing. This is not the\n * full provider response or choices[0].message.\n */\n rawResponse?: string;\n rawAssistantOutput?: RawAssistantOutput;\n yamlFlow?: MidsceneYamlFlowItem[];\n yamlString?: string;\n error?: string;\n reasoning_content?: string;\n shouldContinuePlanning: boolean;\n output?: string; // Output message from <complete> tag (same as finalizeMessage)\n}\n\nexport interface PlanningActionParamSleep {\n timeMs: number;\n}\n\nexport interface PlanningActionParamError {\n thought: string;\n}\n\nexport type PlanningActionParamWaitFor = AgentWaitForOpt & {};\n\nexport interface LongPressParam {\n duration?: number;\n}\n\nexport interface PullParam {\n direction: 'up' | 'down';\n distance?: number;\n duration?: number;\n}\n/**\n * misc\n */\n\nexport interface Color {\n name: string;\n hex: string;\n}\n\nexport interface BaseAgentParserOpt {\n selector?: string;\n}\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface PuppeteerParserOpt extends BaseAgentParserOpt {}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface PlaywrightParserOpt extends BaseAgentParserOpt {}\n\n/*\naction\n*/\nexport interface ExecutionTaskProgressOptions {\n onTaskStart?: (\n task: ExecutionTask,\n signal?: AbortSignal,\n ) => Promise<void> | void;\n}\n\n/**\n * Generic agent progress bus.\n *\n * Progress notifications are a single, generic stream the agent broadcasts as\n * it works. Each event is a thin envelope: a `scope` naming the producer, a\n * `phase` within that producer's lifecycle, a monotonic `sequence`, and a\n * structured, presentation-free `data` payload. The bus knows nothing about any\n * particular producer's payload - consumers narrow by `scope`. `aiAct` is the\n * first producer (\"pilot\") on this bus; others (queries, waits, ...) can be\n * added without touching the bus, the listener API, or the renderer core.\n */\nexport interface AgentProgressEvent<\n TScope extends string = string,\n TData = unknown,\n TPhase extends string = string,\n> {\n scope: TScope;\n phase: TPhase;\n sequence: number;\n data: TData;\n}\n\nexport type AgentProgressListener<\n TScope extends string = string,\n TData = unknown,\n TPhase extends string = string,\n> = (event: AgentProgressEvent<TScope, TData, TPhase>) => Promise<void> | void;\n\n// --- aiAct: the first producer on the generic progress bus ---\n\nexport type AiActProgressPhase =\n | 'start'\n | 'plan_thinking'\n | 'plan_planned'\n | 'plan_action'\n | 'plan_failed'\n | 'action_running'\n | 'action_done'\n | 'action_failed'\n | 'complete'\n | 'failed';\n\nexport interface AiActProgressAction {\n name: string;\n target?: string;\n point?: [number, number];\n bbox?: [number, number, number, number];\n /**\n * Structured, compacted summary of the action params for actions that are\n * not described by a point/bbox (e.g. `Sleep` -> `{ timeMs }`). This is data,\n * never a pre-formatted display string; consumers decide how to render it.\n */\n param?: unknown;\n}\n\n/**\n * Structured payload carried by aiAct progress events. The producer only\n * reports *what happened* as data: the action involved, the raw text the model\n * produced, timings and errors. It never assembles human-readable log lines or\n * truncates strings for display - that belongs to whichever layer consumes the\n * stream (e.g. the CLI verbose renderer).\n */\nexport interface AiActProgressData {\n /** Original user instruction, present on the `start` phase. */\n prompt?: string;\n planIndex?: number;\n planLimit?: number;\n /** Latest screenshot, present on `plan_thinking`. */\n screenshot?: ScreenshotItem;\n /** Structured action descriptor, present on the `*action*` phases. */\n action?: AiActProgressAction;\n /**\n * Raw, untruncated semantic text produced by the model. Consumers choose\n * which field to surface and how to format/truncate it.\n */\n thought?: string;\n log?: string;\n output?: string;\n /** Wall-clock cost of an action, present on `action_done`/`action_failed`. */\n durationMs?: number;\n error?: string;\n}\n\nexport const aiActProgressScope = 'aiAct';\n\nexport interface ExecutionRecorderItem {\n type: 'screenshot';\n ts: number;\n screenshot?: ScreenshotItem;\n description?: string;\n timing?: string;\n}\n\nexport interface RecordToReportScreenshot {\n /**\n * PNG/JPEG data URI, or raw PNG base64 body.\n */\n base64: string;\n description?: string;\n}\n\nexport interface RecordToReportOptions {\n content?: string;\n /**\n * @deprecated Use `screenshots: [{ base64 }]` instead.\n */\n screenshotBase64?: string;\n /**\n * Custom screenshots to display under a single report entry.\n */\n screenshots?: RecordToReportScreenshot[];\n}\n\nexport type ExecutionTaskType = 'Planning' | 'Insight' | 'Action Space' | 'Log';\n\nexport interface ExecutorContext {\n /** Cancellation of this execution; adapters may forward it to cancellable I/O. */\n signal?: AbortSignal;\n task: ExecutionTask;\n element?: LocateResultElement | null;\n uiContext?: UIContext;\n /** Custom readiness owns optional post-action settling, not input/gesture timing. */\n skipDefaultWait?: boolean;\n}\n\nexport interface ExecutionTaskApply<\n Type extends ExecutionTaskType = any,\n TaskParam = any,\n TaskOutput = any,\n TaskLog = any,\n> {\n type: Type;\n subType?: string;\n param?: TaskParam;\n thought?: string;\n uiContext?: UIContext;\n /**\n * Maximum planning feedback length inherited from the action definition.\n * Set to 'unlimited' to disable truncation for this task.\n */\n planningFeedbackMaxLength?: number | 'unlimited';\n executor: (\n context: ExecutorContext,\n ) => // biome-ignore lint/suspicious/noConfusingVoidType: void is intentionally allowed as some executors may not return a value\n | Promise<ExecutionTaskReturn<TaskOutput, TaskLog> | undefined | void>\n | undefined\n | void;\n}\n\nexport interface ExecutionTaskHitBy {\n from: string;\n context: Record<string, any>;\n}\n\nexport interface ExecutionTaskReturn<TaskOutput = unknown, TaskLog = unknown> {\n output?: TaskOutput;\n log?: TaskLog;\n recorder?: ExecutionRecorderItem[];\n hitBy?: ExecutionTaskHitBy;\n}\n\nexport type ExecutionTask<\n E extends ExecutionTaskApply<any, any, any> = ExecutionTaskApply<\n any,\n any,\n any\n >,\n> = E &\n ExecutionTaskReturn<\n E extends ExecutionTaskApply<any, any, infer TaskOutput, any>\n ? TaskOutput\n : unknown,\n E extends ExecutionTaskApply<any, any, any, infer TaskLog>\n ? TaskLog\n : unknown\n > & {\n taskId: string;\n status: 'pending' | 'running' | 'finished' | 'failed' | 'cancelled';\n /** Readiness strategy selected for this atomic action execution. */\n actionReadiness?: 'default' | 'custom';\n /**\n * Optional feedback produced by a task for the next planning round.\n * This is execution metadata, not part of the action return value.\n */\n planningFeedback?: string;\n /**\n * A bounded diagnostic DTO created when the task executor throws. Arbitrary\n * upstream payloads are intentionally omitted; use this field for structured\n * diagnostics or errorMessage/errorStack for the common display path.\n */\n error?: SerializedError;\n errorMessage?: string;\n errorStack?: string;\n timing?: {\n start: number;\n getUiContextStart?: number;\n getUiContextEnd?: number;\n callAiStart?: number;\n callAiEnd?: number;\n beforeInvokeActionHookStart?: number;\n beforeInvokeActionHookEnd?: number;\n callActionStart?: number;\n callActionEnd?: number;\n afterInvokeActionHookStart?: number;\n afterInvokeActionHookEnd?: number;\n waitForActionReadyStart?: number;\n waitForActionReadyEnd?: number;\n captureAfterCallingSnapshotStart?: number;\n captureAfterCallingSnapshotEnd?: number;\n end?: number;\n cost?: number;\n };\n usage?: AIUsageInfo;\n /**\n * Pixel rect of the deepLocate first-stage search area in screenshot\n * coordinates. Used by reports to explain the crop/zoom area that the\n * final locate ran against.\n */\n searchArea?: Rect;\n searchAreaUsage?: AIUsageInfo;\n reasoning_content?: string;\n };\n\nexport interface IExecutionDump extends DumpMeta {\n /** Stable unique identifier for this execution run */\n id?: string;\n name: string;\n description?: string;\n tasks: ExecutionTask[];\n aiActContext?: string;\n}\n\n/*\ntask - service-locate\n*/\nexport interface ExecutionTaskInsightLocateOutput {\n element: LocateResultElement | null;\n}\n\nexport type ExecutionTaskInsightDump = ServiceDump;\n\nexport type ExecutionTaskInsightLocateApply = ExecutionTaskApply<\n 'Insight',\n DetailedLocateParam,\n ExecutionTaskInsightLocateOutput,\n ExecutionTaskInsightDump\n>;\n\nexport type ExecutionTaskInsightLocate =\n ExecutionTask<ExecutionTaskInsightLocateApply>;\n\n/*\ntask - service-query\n*/\nexport interface ExecutionTaskInsightQueryParam {\n dataDemand: ServiceExtractParam;\n domIncluded?: boolean | 'visible-only';\n context?: string;\n}\n\nexport interface ExecutionTaskInsightQueryOutput {\n data: any;\n}\n\nexport type ExecutionTaskInsightQueryApply = ExecutionTaskApply<\n 'Insight',\n ExecutionTaskInsightQueryParam,\n any,\n ExecutionTaskInsightDump\n>;\n\nexport type ExecutionTaskInsightQuery =\n ExecutionTask<ExecutionTaskInsightQueryApply>;\n\n/*\ntask - assertion\n*/\nexport interface ExecutionTaskInsightAssertionParam {\n assertion: string;\n}\n\nexport type ExecutionTaskInsightAssertionApply = ExecutionTaskApply<\n 'Insight',\n ExecutionTaskInsightAssertionParam,\n ServiceAssertionResponse,\n ExecutionTaskInsightDump\n>;\n\nexport type ExecutionTaskInsightAssertion =\n ExecutionTask<ExecutionTaskInsightAssertionApply>;\n\n/*\ntask - action (i.e. interact) \n*/\nexport type ExecutionTaskActionApply<ActionParam = any> = ExecutionTaskApply<\n 'Action Space',\n ActionParam,\n void,\n void\n>;\n\nexport type ExecutionTaskAction = ExecutionTask<ExecutionTaskActionApply>;\n\n/*\ntask - Log\n*/\n\nexport type ExecutionTaskLogApply<\n LogParam = {\n content: string;\n },\n> = ExecutionTaskApply<'Log', LogParam, void, void>;\n\nexport type ExecutionTaskLog = ExecutionTask<ExecutionTaskLogApply>;\n\n/*\ntask - planning\n*/\n\nexport interface ExecutionTaskPlanningParam {\n userInstruction: TUserPrompt;\n userInstructionDisplay?: string;\n replanningCycleLimit?: number;\n aiActContext?: string;\n imagesIncludeCount?: number;\n effort?: AiActEffort;\n subGoalStatus?: string;\n memoriesStatus?: string;\n}\n\nexport type ExecutionTaskPlanningApply = ExecutionTaskApply<\n 'Planning',\n ExecutionTaskPlanningParam,\n PlanningAIResponse\n>;\n\nexport type ExecutionTaskPlanning = ExecutionTask<ExecutionTaskPlanningApply>;\n\n/*\ntask - planning-locate\n*/\nexport interface ExecutionTaskPlanningLocateOutput {\n element: LocateResultElement | null;\n}\n\nexport type ExecutionTaskPlanningDump = ServiceDump;\n\nexport type ExecutionTaskPlanningLocateApply = ExecutionTaskApply<\n 'Planning',\n DetailedLocateParam,\n ExecutionTaskPlanningLocateOutput,\n ExecutionTaskPlanningDump\n>;\n\nexport type ExecutionTaskPlanningLocate =\n ExecutionTask<ExecutionTaskPlanningLocateApply>;\n\n/*\nHow a report file stores screenshots:\n- `inline`: base64 image script tags embedded in the single HTML file\n- `directory`: external PNG files under a sibling `screenshots/` dir\n*/\nexport type ScreenshotMode = 'inline' | 'directory';\n\n/*\nReport metadata - extracted from ReportActionDump for per-execution writes\n*/\nexport interface ReportMeta {\n groupName: string;\n groupDescription?: string;\n sdkVersion: string;\n modelBriefs: ModelBrief[];\n deviceType?: string;\n}\n\n// Backward-compatible aliases for existing external consumers.\nexport type GroupMeta = ReportMeta;\n\n/*\nReport dump\n*/\nexport interface IReportActionDump {\n sdkVersion: string;\n groupName: string;\n groupDescription?: string;\n modelBriefs: ModelBrief[];\n executions: IExecutionDump[];\n deviceType?: string;\n}\n\n// Backward-compatible aliases for existing external consumers.\nexport type IGroupedActionDump = IReportActionDump;\n\nexport interface ModelBrief {\n /**\n * The intent/category of the model call, for example \"planning\" or \"insight\".\n */\n intent?: string;\n\n /**\n * The model name returned by usage metadata, for example \"gpt-4o\".\n */\n name?: string;\n\n /**\n * Optional human-readable model description, for example \"qwen2.5-vl mode\".\n */\n modelDescription?: string;\n}\n\nexport type InterfaceType =\n | 'puppeteer'\n | 'playwright'\n | 'static'\n | 'chrome-extension-proxy'\n | 'android'\n | string;\n\nexport interface StreamingCodeGenerationOptions {\n /** Whether to enable streaming output */\n stream?: boolean;\n /** Callback function to handle streaming chunks */\n onChunk?: StreamingCallback;\n /** Callback function to handle streaming completion */\n onComplete?: (finalCode: string) => void;\n /** Callback function to handle streaming errors */\n onError?: (error: Error) => void;\n}\n\nexport type StreamingCallback = (chunk: CodeGenerationChunk) => void;\n\nexport interface CodeGenerationChunk {\n /** The incremental content chunk */\n content: string;\n /** The reasoning content */\n reasoning_content: string;\n /** The accumulated content so far */\n accumulated: string;\n /** Whether this is the final chunk */\n isComplete: boolean;\n /** Provider token usage, without guaranteed Midscene metadata. See the final response for AIUsageInfo. */\n usage?: OpenAI.CompletionUsage;\n}\n\nexport interface StreamingAIResponse {\n /** The final accumulated content */\n content: string;\n /** Token usage information */\n usage?: AIUsageInfo;\n /** Whether the response was streamed */\n isStreamed: boolean;\n}\n\nexport interface DeviceAction<TParam = any, TReturn = any> {\n /**\n * Allow System One planners to construct this action directly.\n * Only enable for actions with no parameters or locator-only parameters.\n * Omitted/false actions are offered as delegation choices to the default model.\n */\n supportedBySystemOne?: boolean;\n name: string;\n description?: string;\n interfaceAlias?: string;\n paramSchema?: z.ZodType<TParam>;\n /**\n * Maximum number of characters from planningFeedback sent to the next\n * planning round. Omit to use the core default, or set to 'unlimited' to\n * disable truncation for this action.\n */\n planningFeedbackMaxLength?: number | 'unlimited';\n call: (\n param: TParam,\n context?: ExecutorContext,\n ) => Promise<TReturn> | TReturn;\n delayBeforeRunner?: number;\n delayAfterRunner?: number;\n /**\n * An example param object for this action.\n * Locate fields with { prompt } may be resolved to internal pixel bboxes when needed.\n */\n sample?: { [K in keyof TParam]?: any };\n}\n\n/**\n * Type utilities for extracting types from DeviceAction definitions\n */\n\n/**\n * Extract parameter type from a DeviceAction\n */\nexport type ActionParam<Action extends DeviceAction<any, any>> =\n Action extends DeviceAction<infer P, any> ? P : never;\n\n/**\n * Extract return type from a DeviceAction\n */\nexport type ActionReturn<Action extends DeviceAction<any, any>> =\n Action extends DeviceAction<any, infer R> ? R : never;\n\n/**\n * Web-specific types\n */\nexport interface WebElementInfo extends BaseElement {\n id: string;\n attributes: {\n nodeType: NodeType;\n [key: string]: string;\n };\n}\n\n/**\n * Agent\n */\n\nexport type CacheConfig = {\n strategy?: 'read-only' | 'read-write' | 'write-only';\n id: string;\n /**\n * Optional cache directory path.\n * When set, cache files are written to this directory instead of\n * `<MIDSCENE_RUN_DIR>/cache`.\n */\n cacheDir?: string;\n};\n\nexport type Cache =\n | false // No read, no write\n | true // Will throw error at runtime - deprecated\n | CacheConfig; // Object configuration (requires explicit id)\n\nexport interface ActionReadyContext {\n /** Cancels this execution. Use it to stop polling, requests, or listeners. */\n readonly signal?: AbortSignal;\n /** A new identity for each executed atomic action, including cache replay. */\n action: {\n readonly id: string;\n readonly name: string;\n /** Resolved action parameters. Treat them as read-only. */\n readonly param: unknown;\n };\n}\n\n/** Runs after a successful atomic action. Slow callbacks warn after 5 seconds. */\nexport type WaitForActionReady = (context: ActionReadyContext) => Promise<void>;\n\nexport interface AgentOpt {\n // @deprecated Use `reportFileName` and `cache.id` instead.\n testId?: string;\n // @deprecated\n cacheId?: string; // Keep backward compatibility, but marked as deprecated\n groupName?: string;\n groupDescription?: string;\n /* if auto generate report, default true */\n generateReport?: boolean;\n /* if persist per-execution dump files next to the report, default false */\n persistExecutionDump?: boolean;\n /* if auto print report msg, default true */\n autoPrintReportMsg?: boolean;\n\n /**\n * Use directory-based report format with separate image files.\n *\n * When enabled:\n * - Screenshots are saved as PNG files in a `screenshots/` subdirectory\n * - Report is generated as `index.html` with relative image paths\n * - Reduces memory usage and report file size\n *\n * IMPORTANT: 'html-and-external-assets' reports must be served via HTTP server\n * (e.g., `npx serve ./report-dir`). The file:// protocol will not\n * work due to browser CORS restrictions.\n *\n * @default 'single-html'\n */\n outputFormat?: 'single-html' | 'html-and-external-assets';\n\n onTaskStartTip?: OnTaskStartTip;\n /**\n * Agent-level AI guidance containing business facts, rules, constraints, or\n * output requirements. `aiContexts.default` is a shared fallback used only\n * when neither the call nor the matching API key provides a context.\n *\n * A per-call `options.context` overrides the matching API context, which\n * overrides `aiContexts.default`. An empty string explicitly clears\n * inherited user context for that scope. These layers are not automatically\n * merged.\n */\n aiContexts?: AgentAIContexts;\n /**\n * Compatibility alias for `aiContexts.aiAct`. `aiContexts.aiAct` takes\n * precedence when both are provided.\n * @deprecated Use `aiContexts.aiAct` instead.\n */\n aiActContext?: string;\n /**\n * Older compatibility alias for `aiContexts.aiAct`.\n * @deprecated Use `aiContexts.aiAct` instead.\n */\n aiActionContext?: string;\n /* custom report file name */\n reportFileName?: string;\n reportAttributes?: ReportAttributes;\n modelConfig?: TModelConfig;\n cache?: Cache;\n /**\n * Maximum number of replanning cycles for aiAct.\n * Defaults are resolved by the active model adapter: 20 for standard planning,\n * 40 for UI-TARS, and 100 for Auto-GLM.\n * If omitted, the agent will also read `MIDSCENE_REPLANNING_CYCLE_LIMIT` for backward compatibility.\n */\n replanningCycleLimit?: number;\n\n /**\n * Wait time in milliseconds after each action execution.\n * This allows the UI to settle and stabilize before the next action.\n * Defaults to 300ms when not provided.\n */\n waitAfterAction?: number;\n\n /**\n * Await application readiness after each successful atomic action, including\n * aiAct substeps and cache replay. Replaces default action waits.\n * After 5 seconds, logs one warning and continues waiting without a timeout.\n */\n waitForActionReady?: WaitForActionReady;\n\n /**\n * When set to true, Midscene will use the target device's formatted local\n * time instead of the runtime system time. The target interface must implement\n * getDeviceLocalTimeString to provide device-local wall-clock time.\n * Default: false\n */\n useDeviceTime?: boolean;\n\n /**\n * Custom screenshot shrink factor to reduce AI token usage.\n * When set, the screenshot will be scaled down by this factor from the physical resolution.\n *\n * Example:\n * - Physical screen width: 3000px, dpr=6\n * - Logical width: 500px\n * - screenshotShrinkFactor: 2\n * - Actual shrunk screenshot width: 3000 / 2 = 1500px\n * - AI analyzes the 1500px screenshot\n * - Coordinates are transformed back to logical (500px) before actions execute\n *\n * Benefits:\n * - Reduces token usage for high-resolution screenshots\n * - Maintains accuracy by scaling coordinates appropriately\n *\n * Must be >= 1 (shrinking only, enlarging is not supported).\n *\n * @default 1 (no shrinking, uses original physical screenshot)\n */\n screenshotShrinkFactor?: number;\n\n /**\n * Custom OpenAI client factory function\n *\n * If provided, this function will be called to create OpenAI client instances\n * for each AI call, allowing you to:\n * - Wrap clients with observability tools (langsmith, langfuse)\n * - Use custom OpenAI-compatible clients\n * - Apply different configurations based on intent\n *\n * @param config - Resolved model configuration\n * @returns OpenAI client instance (original or wrapped)\n *\n * @example\n * ```typescript\n * createOpenAIClient: async (openai, opts) => {\n * // Wrap with langsmith for planning tasks\n * if (opts.baseURL?.includes('planning')) {\n * return wrapOpenAI(openai, { metadata: { task: 'planning' } });\n * }\n *\n * return openai;\n * }\n * ```\n */\n createOpenAIClient?: CreateOpenAIClientFn;\n\n /**\n * Called once per LLM call as soon as its usage is available, with the raw\n * {@link AIUsageInfo} (token counts, model name, intent, request id, etc.).\n *\n * Use this for real-time, per-spec cost observability — e.g. push each call\n * to Langfuse without waiting for the run to finish. For aggregated totals,\n * read `agent.metrics` instead.\n */\n onLLMUsage?: (usage: AIUsageInfo) => void;\n}\n\nexport type TestStatus =\n | 'passed'\n | 'failed'\n | 'timedOut'\n | 'skipped'\n | 'interrupted';\n\nexport interface ReportFileAttributes {\n testDuration: number;\n testStatus: TestStatus;\n testTitle: string;\n testId: string;\n testDescription: string;\n}\n\ntype SkippedReportFileAttributes = Omit<ReportFileAttributes, 'testStatus'> & {\n testStatus: 'skipped';\n};\n\nexport type ReportFileWithAttributes =\n | {\n reportFilePath: string;\n reportAttributes: ReportFileAttributes;\n }\n | {\n reportFilePath?: undefined;\n reportAttributes: SkippedReportFileAttributes;\n };\n"],"names":["UIContext","aiActProgressScope"],"mappings":";;;AAqLO,MAAeA;AAqCtB;AAmWO,MAAMC,qBAAqB"}
|
|
1
|
+
{"version":3,"file":"types.mjs","sources":["../../src/types.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { AgentAIContexts } from '@midscene/shared/agent-tools/agent-context';\nimport type { SerializedError } from '@midscene/shared/agent-tools/error-formatter';\nimport type { NodeType } from '@midscene/shared/constants';\nimport type { CreateOpenAIClientFn, TModelConfig } from '@midscene/shared/env';\nimport type {\n BaseElement,\n LocateResultElement,\n Rect,\n Size,\n} from '@midscene/shared/types';\nimport type OpenAI from 'openai';\nimport type { z } from 'zod';\nimport type { TUserPrompt } from './common';\nimport type { ScreenshotItem } from './screenshot-item';\nimport type {\n DetailedLocateParam,\n MidsceneYamlFlowItem,\n ServiceExtractOption,\n} from './yaml';\n\nexport type {\n ElementTreeNode,\n BaseElement,\n Rect,\n Size,\n Point,\n} from '@midscene/shared/types';\nexport type { SerializedError } from '@midscene/shared/agent-tools/error-formatter';\nexport type {\n AgentAIContextKey,\n AgentAIContexts,\n AiApiName,\n} from '@midscene/shared/agent-tools/agent-context';\nexport * from './yaml';\n\nexport { ServiceError } from './errors';\nexport {\n ExecutionDump,\n ReportActionDump,\n GroupedActionDump,\n} from './dump/report-action-dump';\n\nexport type RawAssistantOutput =\n | {\n type: 'chat-completion';\n rawValue: OpenAI.Chat.Completions.ChatCompletionMessage;\n }\n | {\n type: 'responses';\n rawValue: OpenAI.Responses.ResponseOutputItem[];\n };\n\nexport type AIUsageInfo = Record<string, any> & {\n prompt_tokens: number | undefined;\n completion_tokens: number | undefined;\n total_tokens: number | undefined;\n cached_input: number | undefined;\n /** Duration of the final successful request attempt, in milliseconds. */\n time_cost: number | undefined;\n /** Request duration including all attempts and retry waits, excluding preparation, in milliseconds. */\n total_time_cost?: number;\n /** Request retries performed within this call; excludes semantic parse retries. */\n retry_count?: number;\n /** Actual protocol used for the model call, resolved by Midscene. */\n request_kind?: 'chat-completion' | 'responses' | 'codex' | 'system-one';\n /** Why a task uses the default model instead of its configured specialist. */\n modelFallback?: {\n requestedModel: string;\n requestedSlot: string;\n taskType: string;\n reason: string;\n };\n /** Whether the model call used streaming, after resolving call options. */\n stream?: boolean;\n model_name: string | undefined;\n model_description: string | undefined;\n /**\n * Raw top-level `.model` value returned by the model service response.\n */\n response_model_name: string | undefined;\n /**\n * Semantic intent of the model call, such as default, planning, or insight.\n */\n intent: string | undefined;\n /**\n * Config slot where the model config was resolved from. For example, a\n * planning call may use the default slot when no planning model is configured.\n */\n slot: string | undefined;\n request_id: string | undefined;\n};\n\nexport type { LocateResultElement };\n\nexport type AISingleElementResponseByPosition = {\n position?: {\n x: number;\n y: number;\n };\n bbox?: [number, number, number, number];\n reason: string;\n text: string;\n};\n\nexport type LocateResultPoint = [number, number];\nexport type Bbox = [number, number, number, number];\nexport type LocateResultBbox = Bbox;\nexport type PixelBbox = Bbox;\n\nexport interface AIElementLocateResponse {\n bbox?: LocateResultBbox;\n point?: LocateResultPoint;\n error?: string;\n}\n\nexport interface AIDataExtractionResponse<DataDemand> {\n data: DataDemand;\n errors?: string[];\n thought?: string;\n}\n\nexport interface AISectionLocatorResponse {\n bbox?: LocateResultBbox;\n point?: LocateResultPoint;\n references_bbox?: LocateResultBbox[];\n references_point?: LocateResultPoint[];\n error?: string;\n}\n\nexport interface AIAssertionResponse {\n pass: boolean;\n thought: string;\n}\n\nexport interface AIDescribeElementResponse {\n description: string;\n error?: string;\n}\n\nexport interface LocatorValidatorOption {\n centerDistanceThreshold?: number;\n}\n\nexport interface LocateValidatorResult {\n pass: boolean;\n rect?: Rect;\n center: [number, number];\n centerDistance?: number;\n /** Whether the expected point is inside the located rect; absent for point-only results. */\n includedInRect?: boolean;\n}\n\nexport interface AgentDescribeElementAtPointResult {\n prompt: string;\n deepLocate: boolean;\n deepDescribe: boolean;\n verifyResult?: LocateValidatorResult;\n success: boolean;\n error?: string;\n failureStage?: 'describe' | 'verify';\n}\n\n/**\n * context\n */\n\nexport interface UiNode {\n type: string;\n attrs: Record<string, string | undefined>;\n bounds: Rect;\n children: UiNode[];\n}\n\nexport interface UITreeSnapshot {\n platform: 'android';\n capturedAt: number;\n root: UiNode;\n}\n\nexport abstract class UIContext {\n /**\n * screenshot of the current UI state. which size is shotSize(be shrunk by screenshotShrinkFactor),\n */\n abstract screenshot: ScreenshotItem;\n\n /**\n * Optional sequence of screenshots captured over a short time window, in\n * temporal order (earliest first, latest last). When present with more than\n * one frame, extract/assert flows submit all frames to the model so it can\n * observe transient UI (toasts, carousels, auto-hiding controls). The last\n * frame is the same state as {@link screenshot}.\n */\n abstract screenshotSequence?: ScreenshotItem[];\n\n /**\n * screenshot size after shrinking\n */\n abstract shotSize: Size;\n\n /**\n * The ratio for converting shrunk screenshot coordinates to logical coordinates.\n *\n * Example:\n * - Physical screen width: 3000px, dpr=6\n * - Logical width: 500px\n * - User-defined screenshotShrinkFactor: 2\n * - Actual shrunk screenshot width: 3000 / 2 = 1500px\n * - shrunkShotToLogicalRatio: dpr / screenshotShrinkFactor = 6 / 2 = 3\n * - To map back to logical coordinates: 1500 / shrunkShotToLogicalRatio = 500px\n */\n abstract shrunkShotToLogicalRatio: number;\n\n abstract _isFrozen?: boolean;\n\n // @deprecated - backward compatibility for aiLocate\n abstract deprecatedDpr?: number;\n}\n\nexport type EnsureObject<T> = { [K in keyof T]: any };\n\nexport type ServiceAction = 'locate' | 'extract' | 'assert' | 'describe';\n\nexport type ServiceExtractParam = string | Record<string, string>;\n\nexport type ElementCacheFeature = Record<string, unknown>;\n\nexport interface LocateResult {\n element: LocateResultElement | null;\n}\n\nexport type ThinkingLevel = 'off' | 'medium' | 'high';\n\nexport type AiActEffort = 'fast' | 'balance' | 'deepThink';\n\nexport type DeepThinkOption = 'unset' | true | false;\n\nexport interface ServiceTaskInfo {\n durationMs: number;\n formatResponse?: unknown;\n /**\n * Adapter-extracted content used by Midscene for parsing. This is not the\n * full provider response or choices[0].message.\n */\n rawResponse?: unknown;\n rawAssistantOutput?: RawAssistantOutput;\n usage?: AIUsageInfo;\n searchArea?: Rect;\n /**\n * Adapter-extracted content from the search-area model call. This is not the\n * full provider response or choices[0].message.\n */\n searchAreaRawResponse?: string;\n searchAreaRawChoiceMessage?: unknown;\n searchAreaUsage?: AIUsageInfo;\n reasoning_content?: string;\n}\n\nexport interface DumpMeta {\n logTime: number;\n}\n\nexport type ReportAttributes = Record<\n string,\n string | number | boolean | null | undefined\n>;\n\nexport interface ReportDumpWithAttributes {\n dumpString: string;\n attributes?: ReportAttributes;\n}\n\nexport interface ServiceDump extends DumpMeta {\n type: 'locate' | 'extract' | 'assert';\n logId: string;\n userQuery: {\n element?: TUserPrompt;\n dataDemand?: ServiceExtractParam;\n assertion?: TUserPrompt;\n };\n matchedElement?: LocateResultElement[];\n deepLocate?: boolean;\n data: any;\n assertionPass?: boolean;\n assertionThought?: string;\n taskInfo: ServiceTaskInfo;\n error?: string;\n output?: any;\n}\n\nexport type PartialServiceDumpFromSDK = Omit<\n ServiceDump,\n 'logTime' | 'logId' | 'model_name'\n>;\n\nexport interface ServiceResultBase {\n dump: ServiceDump;\n}\n\nexport type LocateResultWithDump = LocateResult & ServiceResultBase;\n\nexport interface ServiceExtractResult<T> extends ServiceResultBase {\n data: T;\n thought?: string;\n usage?: AIUsageInfo;\n reasoning_content?: string;\n}\n\n// intermediate variables to optimize the return value by AI\nexport interface LiteUISection {\n name: string;\n description: string;\n sectionCharacteristics: string;\n textIds: string[];\n}\n\nexport type ElementById = (id: string) => BaseElement | null;\n\nexport type ServiceAssertionResponse = AIAssertionResponse & {\n usage?: AIUsageInfo;\n};\n\n/**\n * agent\n */\n\nexport type OnTaskStartTip = (tip: string) => Promise<void> | void;\n\nexport interface AgentWaitForOpt extends ServiceExtractOption {\n /** Cancels the complete wait, including active model checks. */\n abortSignal?: AbortSignal;\n checkIntervalMs?: number;\n timeoutMs?: number;\n}\n\nexport interface AgentAssertOpt {\n keepRawResponse?: boolean;\n /**\n * Additional facts, decision rules, constraints, or output requirements for\n * this assertion. It overrides `aiContexts.aiAssert` and\n * `aiContexts.default`;\n * `''` disables inherited user context for this call.\n */\n context?: string;\n abortSignal?: AbortSignal;\n}\n\nexport interface AgentAssertResult {\n pass: boolean;\n thought?: string;\n message?: string;\n}\n\nexport type QueryOptions = ServiceExtractOption;\nexport type AssertOptions = AgentAssertOpt & ServiceExtractOption;\n\n/** Options for fixed observations, which never read the live DOM. */\nexport type ObservationQueryOptions = Omit<QueryOptions, 'domIncluded'> & {\n domIncluded?: never;\n};\n\n/** Assertion options for fixed observations, which never read the live DOM. */\nexport type ObservationAssertOptions = Omit<AssertOptions, 'domIncluded'> & {\n domIncluded?: never;\n};\n\n/** Read-only AI operations supported by both live Agents and UI observations. */\nexport interface InsightAPI<\n QueryOpt extends QueryOptions = QueryOptions,\n AssertOpt extends AssertOptions = AssertOptions,\n> {\n aiQuery<ReturnType = any>(\n demand: ServiceExtractParam,\n options?: QueryOpt,\n ): Promise<ReturnType>;\n aiBoolean(prompt: TUserPrompt, options?: QueryOpt): Promise<boolean>;\n aiNumber(prompt: TUserPrompt, options?: QueryOpt): Promise<number>;\n aiString(prompt: TUserPrompt, options?: QueryOpt): Promise<string>;\n aiAsk(prompt: TUserPrompt, options?: QueryOpt): Promise<string>;\n aiAssert(\n assertion: TUserPrompt,\n message?: string,\n options?: AssertOpt,\n ): Promise<AgentAssertResult | undefined>;\n}\n\n/**\n * planning\n *\n */\n\ntype PlanningActionBase = {\n thought?: string;\n log?: string; // a brief preamble to the user explaining what you’re about to do\n type: string;\n};\n\nexport type PlanningAction<ParamType = undefined> = PlanningActionBase &\n ([ParamType] extends [undefined] ? { param?: any } : { param: ParamType });\n\nexport type SubGoalStatus = 'pending' | 'running' | 'finished';\n\nexport interface SubGoal {\n index: number;\n status: SubGoalStatus;\n description: string;\n logs?: string[];\n}\n\nexport interface RawResponsePlanningAIResponse {\n action: PlanningAction | null;\n thought?: string;\n log: string;\n memory?: string;\n error?: string;\n finalizeMessage?: string;\n finalizeSuccess?: boolean;\n updateSubGoals?: SubGoal[];\n markFinishedIndexes?: number[];\n}\n\nexport interface PlanningAIResponse\n extends Omit<RawResponsePlanningAIResponse, 'action'> {\n actions?: PlanningAction[];\n /** Request another planning cycle using the default model, without executing actions. */\n delegation?: {\n reason: string;\n suggestedAction?: string;\n };\n usage?: AIUsageInfo;\n /**\n * Adapter-extracted content used by Midscene for parsing. This is not the\n * full provider response or choices[0].message.\n */\n rawResponse?: string;\n rawAssistantOutput?: RawAssistantOutput;\n yamlFlow?: MidsceneYamlFlowItem[];\n yamlString?: string;\n error?: string;\n reasoning_content?: string;\n shouldContinuePlanning: boolean;\n output?: string; // Output message from <complete> tag (same as finalizeMessage)\n}\n\nexport interface PlanningActionParamSleep {\n timeMs: number;\n}\n\nexport interface PlanningActionParamError {\n thought: string;\n}\n\nexport type PlanningActionParamWaitFor = AgentWaitForOpt & {};\n\nexport interface LongPressParam {\n duration?: number;\n}\n\nexport interface PullParam {\n direction: 'up' | 'down';\n distance?: number;\n duration?: number;\n}\n/**\n * misc\n */\n\nexport interface Color {\n name: string;\n hex: string;\n}\n\nexport interface BaseAgentParserOpt {\n selector?: string;\n}\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface PuppeteerParserOpt extends BaseAgentParserOpt {}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface PlaywrightParserOpt extends BaseAgentParserOpt {}\n\n/*\naction\n*/\nexport interface ExecutionTaskProgressOptions {\n onTaskStart?: (\n task: ExecutionTask,\n signal?: AbortSignal,\n ) => Promise<void> | void;\n}\n\n/**\n * Generic agent progress bus.\n *\n * Progress notifications are a single, generic stream the agent broadcasts as\n * it works. Each event is a thin envelope: a `scope` naming the producer, a\n * `phase` within that producer's lifecycle, a monotonic `sequence`, and a\n * structured, presentation-free `data` payload. The bus knows nothing about any\n * particular producer's payload - consumers narrow by `scope`. `aiAct` is the\n * first producer (\"pilot\") on this bus; others (queries, waits, ...) can be\n * added without touching the bus, the listener API, or the renderer core.\n */\nexport interface AgentProgressEvent<\n TScope extends string = string,\n TData = unknown,\n TPhase extends string = string,\n> {\n scope: TScope;\n phase: TPhase;\n sequence: number;\n data: TData;\n}\n\nexport type AgentProgressListener<\n TScope extends string = string,\n TData = unknown,\n TPhase extends string = string,\n> = (event: AgentProgressEvent<TScope, TData, TPhase>) => Promise<void> | void;\n\n// --- aiAct: the first producer on the generic progress bus ---\n\nexport type AiActProgressPhase =\n | 'start'\n | 'plan_thinking'\n | 'plan_planned'\n | 'plan_action'\n | 'plan_failed'\n | 'action_running'\n | 'action_done'\n | 'action_failed'\n | 'complete'\n | 'failed';\n\nexport interface AiActProgressAction {\n name: string;\n target?: string;\n point?: [number, number];\n bbox?: [number, number, number, number];\n /**\n * Structured, compacted summary of the action params for actions that are\n * not described by a point/bbox (e.g. `Sleep` -> `{ timeMs }`). This is data,\n * never a pre-formatted display string; consumers decide how to render it.\n */\n param?: unknown;\n}\n\n/**\n * Structured payload carried by aiAct progress events. The producer only\n * reports *what happened* as data: the action involved, the raw text the model\n * produced, timings and errors. It never assembles human-readable log lines or\n * truncates strings for display - that belongs to whichever layer consumes the\n * stream (e.g. the CLI verbose renderer).\n */\nexport interface AiActProgressData {\n /** Original user instruction, present on the `start` phase. */\n prompt?: string;\n planIndex?: number;\n planLimit?: number;\n /** Latest screenshot, present on `plan_thinking`. */\n screenshot?: ScreenshotItem;\n /** Structured action descriptor, present on the `*action*` phases. */\n action?: AiActProgressAction;\n /**\n * Raw, untruncated semantic text produced by the model. Consumers choose\n * which field to surface and how to format/truncate it.\n */\n thought?: string;\n log?: string;\n output?: string;\n /** Wall-clock cost of an action, present on `action_done`/`action_failed`. */\n durationMs?: number;\n error?: string;\n}\n\nexport const aiActProgressScope = 'aiAct';\n\nexport interface ExecutionRecorderItem {\n type: 'screenshot';\n ts: number;\n screenshot?: ScreenshotItem;\n description?: string;\n timing?: string;\n}\n\nexport interface RecordToReportScreenshot {\n /**\n * PNG/JPEG data URI, or raw PNG base64 body.\n */\n base64: string;\n description?: string;\n}\n\nexport interface RecordToReportOptions {\n content?: string;\n /**\n * @deprecated Use `screenshots: [{ base64 }]` instead.\n */\n screenshotBase64?: string;\n /**\n * Custom screenshots to display under a single report entry.\n */\n screenshots?: RecordToReportScreenshot[];\n}\n\nexport type ExecutionTaskType = 'Planning' | 'Insight' | 'Action Space' | 'Log';\n\nexport interface ExecutorContext {\n /** Cancellation of this execution; adapters may forward it to cancellable I/O. */\n signal?: AbortSignal;\n task: ExecutionTask;\n element?: LocateResultElement | null;\n uiContext?: UIContext;\n /** Custom readiness owns optional post-action settling, not input/gesture timing. */\n skipDefaultWait?: boolean;\n}\n\nexport interface ExecutionTaskApply<\n Type extends ExecutionTaskType = any,\n TaskParam = any,\n TaskOutput = any,\n TaskLog = any,\n> {\n type: Type;\n subType?: string;\n param?: TaskParam;\n thought?: string;\n uiContext?: UIContext;\n /**\n * Maximum planning feedback length inherited from the action definition.\n * Set to 'unlimited' to disable truncation for this task.\n */\n planningFeedbackMaxLength?: number | 'unlimited';\n executor: (\n context: ExecutorContext,\n ) => // biome-ignore lint/suspicious/noConfusingVoidType: void is intentionally allowed as some executors may not return a value\n | Promise<ExecutionTaskReturn<TaskOutput, TaskLog> | undefined | void>\n | undefined\n | void;\n}\n\nexport interface ExecutionTaskHitBy {\n from: string;\n context: Record<string, any>;\n}\n\nexport interface ExecutionTaskReturn<TaskOutput = unknown, TaskLog = unknown> {\n output?: TaskOutput;\n log?: TaskLog;\n recorder?: ExecutionRecorderItem[];\n hitBy?: ExecutionTaskHitBy;\n}\n\nexport type ExecutionTask<\n E extends ExecutionTaskApply<any, any, any> = ExecutionTaskApply<\n any,\n any,\n any\n >,\n> = E &\n ExecutionTaskReturn<\n E extends ExecutionTaskApply<any, any, infer TaskOutput, any>\n ? TaskOutput\n : unknown,\n E extends ExecutionTaskApply<any, any, any, infer TaskLog>\n ? TaskLog\n : unknown\n > & {\n taskId: string;\n status: 'pending' | 'running' | 'finished' | 'failed' | 'cancelled';\n /** Readiness strategy selected for this atomic action execution. */\n actionReadiness?: 'default' | 'custom';\n /**\n * Optional feedback produced by a task for the next planning round.\n * This is execution metadata, not part of the action return value.\n */\n planningFeedback?: string;\n /**\n * A bounded diagnostic DTO created when the task executor throws. Arbitrary\n * upstream payloads are intentionally omitted; use this field for structured\n * diagnostics or errorMessage/errorStack for the common display path.\n */\n error?: SerializedError;\n errorMessage?: string;\n errorStack?: string;\n timing?: {\n start: number;\n getUiContextStart?: number;\n getUiContextEnd?: number;\n callAiStart?: number;\n callAiEnd?: number;\n beforeInvokeActionHookStart?: number;\n beforeInvokeActionHookEnd?: number;\n callActionStart?: number;\n callActionEnd?: number;\n afterInvokeActionHookStart?: number;\n afterInvokeActionHookEnd?: number;\n waitForActionReadyStart?: number;\n waitForActionReadyEnd?: number;\n captureAfterCallingSnapshotStart?: number;\n captureAfterCallingSnapshotEnd?: number;\n end?: number;\n cost?: number;\n };\n usage?: AIUsageInfo;\n /**\n * Pixel rect of the deepLocate first-stage search area in screenshot\n * coordinates. Used by reports to explain the crop/zoom area that the\n * final locate ran against.\n */\n searchArea?: Rect;\n searchAreaUsage?: AIUsageInfo;\n reasoning_content?: string;\n };\n\nexport interface IExecutionDump extends DumpMeta {\n /** Stable unique identifier for this execution run */\n id?: string;\n name: string;\n description?: string;\n tasks: ExecutionTask[];\n aiActContext?: string;\n}\n\n/*\ntask - service-locate\n*/\nexport interface ExecutionTaskInsightLocateOutput {\n element: LocateResultElement | null;\n}\n\nexport type ExecutionTaskInsightDump = ServiceDump;\n\nexport type ExecutionTaskInsightLocateApply = ExecutionTaskApply<\n 'Insight',\n DetailedLocateParam,\n ExecutionTaskInsightLocateOutput,\n ExecutionTaskInsightDump\n>;\n\nexport type ExecutionTaskInsightLocate =\n ExecutionTask<ExecutionTaskInsightLocateApply>;\n\n/*\ntask - service-query\n*/\nexport interface ExecutionTaskInsightQueryParam {\n dataDemand: ServiceExtractParam;\n domIncluded?: boolean | 'visible-only';\n context?: string;\n}\n\nexport interface ExecutionTaskInsightQueryOutput {\n data: any;\n}\n\nexport type ExecutionTaskInsightQueryApply = ExecutionTaskApply<\n 'Insight',\n ExecutionTaskInsightQueryParam,\n any,\n ExecutionTaskInsightDump\n>;\n\nexport type ExecutionTaskInsightQuery =\n ExecutionTask<ExecutionTaskInsightQueryApply>;\n\n/*\ntask - assertion\n*/\nexport interface ExecutionTaskInsightAssertionParam {\n assertion: string;\n}\n\nexport type ExecutionTaskInsightAssertionApply = ExecutionTaskApply<\n 'Insight',\n ExecutionTaskInsightAssertionParam,\n ServiceAssertionResponse,\n ExecutionTaskInsightDump\n>;\n\nexport type ExecutionTaskInsightAssertion =\n ExecutionTask<ExecutionTaskInsightAssertionApply>;\n\n/*\ntask - action (i.e. interact) \n*/\nexport type ExecutionTaskActionApply<ActionParam = any> = ExecutionTaskApply<\n 'Action Space',\n ActionParam,\n void,\n void\n>;\n\nexport type ExecutionTaskAction = ExecutionTask<ExecutionTaskActionApply>;\n\n/*\ntask - Log\n*/\n\nexport type ExecutionTaskLogApply<\n LogParam = {\n content: string;\n },\n> = ExecutionTaskApply<'Log', LogParam, void, void>;\n\nexport type ExecutionTaskLog = ExecutionTask<ExecutionTaskLogApply>;\n\n/*\ntask - planning\n*/\n\nexport interface ExecutionTaskPlanningParam {\n userInstruction: TUserPrompt;\n userInstructionDisplay?: string;\n replanningCycleLimit?: number;\n aiActContext?: string;\n imagesIncludeCount?: number;\n effort?: AiActEffort;\n subGoalStatus?: string;\n memoriesStatus?: string;\n}\n\nexport type ExecutionTaskPlanningApply = ExecutionTaskApply<\n 'Planning',\n ExecutionTaskPlanningParam,\n PlanningAIResponse\n>;\n\nexport type ExecutionTaskPlanning = ExecutionTask<ExecutionTaskPlanningApply>;\n\n/*\ntask - planning-locate\n*/\nexport interface ExecutionTaskPlanningLocateOutput {\n element: LocateResultElement | null;\n}\n\nexport type ExecutionTaskPlanningDump = ServiceDump;\n\nexport type ExecutionTaskPlanningLocateApply = ExecutionTaskApply<\n 'Planning',\n DetailedLocateParam,\n ExecutionTaskPlanningLocateOutput,\n ExecutionTaskPlanningDump\n>;\n\nexport type ExecutionTaskPlanningLocate =\n ExecutionTask<ExecutionTaskPlanningLocateApply>;\n\n/*\nHow a report file stores screenshots:\n- `inline`: base64 image script tags embedded in the single HTML file\n- `directory`: external PNG files under a sibling `screenshots/` dir\n*/\nexport type ScreenshotMode = 'inline' | 'directory';\n\n/*\nReport metadata - extracted from ReportActionDump for per-execution writes\n*/\nexport interface ReportMeta {\n groupName: string;\n groupDescription?: string;\n sdkVersion: string;\n modelBriefs: ModelBrief[];\n deviceType?: string;\n}\n\n// Backward-compatible aliases for existing external consumers.\nexport type GroupMeta = ReportMeta;\n\n/*\nReport dump\n*/\nexport interface IReportActionDump {\n sdkVersion: string;\n groupName: string;\n groupDescription?: string;\n modelBriefs: ModelBrief[];\n executions: IExecutionDump[];\n deviceType?: string;\n}\n\n// Backward-compatible aliases for existing external consumers.\nexport type IGroupedActionDump = IReportActionDump;\n\nexport interface ModelBrief {\n /**\n * The intent/category of the model call, for example \"planning\" or \"insight\".\n */\n intent?: string;\n\n /**\n * The model name returned by usage metadata, for example \"gpt-4o\".\n */\n name?: string;\n\n /**\n * Optional human-readable model description, for example \"qwen2.5-vl mode\".\n */\n modelDescription?: string;\n}\n\nexport type InterfaceType =\n | 'puppeteer'\n | 'playwright'\n | 'static'\n | 'chrome-extension-proxy'\n | 'android'\n | string;\n\nexport interface StreamingCodeGenerationOptions {\n /** Whether to enable streaming output */\n stream?: boolean;\n /** Callback function to handle streaming chunks */\n onChunk?: StreamingCallback;\n /** Callback function to handle streaming completion */\n onComplete?: (finalCode: string) => void;\n /** Callback function to handle streaming errors */\n onError?: (error: Error) => void;\n}\n\nexport type StreamingCallback = (chunk: CodeGenerationChunk) => void;\n\nexport interface CodeGenerationChunk {\n /** The incremental content chunk */\n content: string;\n /** The reasoning content */\n reasoning_content: string;\n /** The accumulated content so far */\n accumulated: string;\n /** Whether this is the final chunk */\n isComplete: boolean;\n /** Provider token usage, without guaranteed Midscene metadata. See the final response for AIUsageInfo. */\n usage?: OpenAI.CompletionUsage;\n}\n\nexport interface StreamingAIResponse {\n /** The final accumulated content */\n content: string;\n /** Token usage information */\n usage?: AIUsageInfo;\n /** Whether the response was streamed */\n isStreamed: boolean;\n}\n\nexport interface DeviceAction<TParam = any, TReturn = any> {\n /**\n * Allow System One planners to construct this action directly.\n * Only enable for actions with no parameters or locator-only parameters.\n * Omitted/false actions are offered as delegation choices to the default model.\n */\n supportedBySystemOne?: boolean;\n name: string;\n description?: string;\n interfaceAlias?: string;\n paramSchema?: z.ZodType<TParam>;\n /**\n * Maximum number of characters from planningFeedback sent to the next\n * planning round. Omit to use the core default, or set to 'unlimited' to\n * disable truncation for this action.\n */\n planningFeedbackMaxLength?: number | 'unlimited';\n call: (\n param: TParam,\n context?: ExecutorContext,\n ) => Promise<TReturn> | TReturn;\n delayBeforeRunner?: number;\n delayAfterRunner?: number;\n /**\n * An example param object for this action.\n * Locate fields with { prompt } may be resolved to internal pixel bboxes when needed.\n */\n sample?: { [K in keyof TParam]?: any };\n}\n\n/**\n * Type utilities for extracting types from DeviceAction definitions\n */\n\n/**\n * Extract parameter type from a DeviceAction\n */\nexport type ActionParam<Action extends DeviceAction<any, any>> =\n Action extends DeviceAction<infer P, any> ? P : never;\n\n/**\n * Extract return type from a DeviceAction\n */\nexport type ActionReturn<Action extends DeviceAction<any, any>> =\n Action extends DeviceAction<any, infer R> ? R : never;\n\n/**\n * Web-specific types\n */\nexport interface WebElementInfo extends BaseElement {\n id: string;\n attributes: {\n nodeType: NodeType;\n [key: string]: string;\n };\n}\n\n/**\n * Agent\n */\n\nexport type CacheConfig = {\n strategy?: 'read-only' | 'read-write' | 'write-only';\n id: string;\n /**\n * Optional cache directory path.\n * When set, cache files are written to this directory instead of\n * `<MIDSCENE_RUN_DIR>/cache`.\n */\n cacheDir?: string;\n};\n\nexport type Cache =\n | false // No read, no write\n | true // Will throw error at runtime - deprecated\n | CacheConfig; // Object configuration (requires explicit id)\n\nexport interface ActionReadyContext {\n /** Cancels this execution. Use it to stop polling, requests, or listeners. */\n readonly signal?: AbortSignal;\n /** A new identity for each executed atomic action, including cache replay. */\n action: {\n readonly id: string;\n readonly name: string;\n /** Resolved action parameters. Treat them as read-only. */\n readonly param: unknown;\n };\n}\n\n/** Runs after a successful atomic action. Slow callbacks warn after 5 seconds. */\nexport type WaitForActionReady = (context: ActionReadyContext) => Promise<void>;\n\nexport interface AgentOpt {\n // @deprecated Use `reportFileName` and `cache.id` instead.\n testId?: string;\n // @deprecated\n cacheId?: string; // Keep backward compatibility, but marked as deprecated\n groupName?: string;\n groupDescription?: string;\n /* if auto generate report, default true */\n generateReport?: boolean;\n /* if persist per-execution dump files next to the report, default false */\n persistExecutionDump?: boolean;\n /* if auto print report msg, default true */\n autoPrintReportMsg?: boolean;\n\n /**\n * Use directory-based report format with separate image files.\n *\n * When enabled:\n * - Screenshots are saved as PNG files in a `screenshots/` subdirectory\n * - Report is generated as `index.html` with relative image paths\n * - Reduces memory usage and report file size\n *\n * IMPORTANT: 'html-and-external-assets' reports must be served via HTTP server\n * (e.g., `npx serve ./report-dir`). The file:// protocol will not\n * work due to browser CORS restrictions.\n *\n * @default 'single-html'\n */\n outputFormat?: 'single-html' | 'html-and-external-assets';\n\n onTaskStartTip?: OnTaskStartTip;\n /**\n * Agent-level AI guidance containing business facts, rules, constraints, or\n * output requirements. `aiContexts.default` is a shared fallback used only\n * when neither the call nor the matching API key provides a context.\n *\n * A per-call `options.context` overrides the matching API context, which\n * overrides `aiContexts.default`. An empty string explicitly clears\n * inherited user context for that scope. These layers are not automatically\n * merged.\n */\n aiContexts?: AgentAIContexts;\n /**\n * Compatibility alias for `aiContexts.aiAct`. `aiContexts.aiAct` takes\n * precedence when both are provided.\n * @deprecated Use `aiContexts.aiAct` instead.\n */\n aiActContext?: string;\n /**\n * Older compatibility alias for `aiContexts.aiAct`.\n * @deprecated Use `aiContexts.aiAct` instead.\n */\n aiActionContext?: string;\n /* custom report file name */\n reportFileName?: string;\n reportAttributes?: ReportAttributes;\n modelConfig?: TModelConfig;\n cache?: Cache;\n /**\n * Maximum number of replanning cycles for aiAct.\n * Defaults are resolved by the active model adapter: 20 for standard planning,\n * 40 for UI-TARS, and 100 for Auto-GLM.\n * If omitted, the agent will also read `MIDSCENE_REPLANNING_CYCLE_LIMIT` for backward compatibility.\n */\n replanningCycleLimit?: number;\n\n /**\n * Expose WaitFor(condition) to aiAct planning. Defaults to false.\n * Uses visual aiWaitFor checks (30s deadline, 2s minimum check interval).\n * Conditions are rechecked on cache replay; failures stop the action.\n * Requires a planning model that supports the supplied action space.\n * Additional checks consume model calls. Reserves the WaitFor action name.\n */\n planningWaitFor?: boolean;\n\n /**\n * Wait time in milliseconds after each action execution.\n * This allows the UI to settle and stabilize before the next action.\n * Defaults to 300ms when not provided.\n */\n waitAfterAction?: number;\n\n /**\n * Await application readiness after each successful atomic action, including\n * aiAct substeps and cache replay. Replaces default action waits.\n * After 5 seconds, logs one warning and continues waiting without a timeout.\n */\n waitForActionReady?: WaitForActionReady;\n\n /**\n * When set to true, Midscene will use the target device's formatted local\n * time instead of the runtime system time. The target interface must implement\n * getDeviceLocalTimeString to provide device-local wall-clock time.\n * Default: false\n */\n useDeviceTime?: boolean;\n\n /**\n * Custom screenshot shrink factor to reduce AI token usage.\n * When set, the screenshot will be scaled down by this factor from the physical resolution.\n *\n * Example:\n * - Physical screen width: 3000px, dpr=6\n * - Logical width: 500px\n * - screenshotShrinkFactor: 2\n * - Actual shrunk screenshot width: 3000 / 2 = 1500px\n * - AI analyzes the 1500px screenshot\n * - Coordinates are transformed back to logical (500px) before actions execute\n *\n * Benefits:\n * - Reduces token usage for high-resolution screenshots\n * - Maintains accuracy by scaling coordinates appropriately\n *\n * Must be >= 1 (shrinking only, enlarging is not supported).\n *\n * @default 1 (no shrinking, uses original physical screenshot)\n */\n screenshotShrinkFactor?: number;\n\n /**\n * Custom OpenAI client factory function\n *\n * If provided, this function will be called to create OpenAI client instances\n * for each AI call, allowing you to:\n * - Wrap clients with observability tools (langsmith, langfuse)\n * - Use custom OpenAI-compatible clients\n * - Apply different configurations based on intent\n *\n * @param config - Resolved model configuration\n * @returns OpenAI client instance (original or wrapped)\n *\n * @example\n * ```typescript\n * createOpenAIClient: async (openai, opts) => {\n * // Wrap with langsmith for planning tasks\n * if (opts.baseURL?.includes('planning')) {\n * return wrapOpenAI(openai, { metadata: { task: 'planning' } });\n * }\n *\n * return openai;\n * }\n * ```\n */\n createOpenAIClient?: CreateOpenAIClientFn;\n\n /**\n * Called once per LLM call as soon as its usage is available, with the raw\n * {@link AIUsageInfo} (token counts, model name, intent, request id, etc.).\n *\n * Use this for real-time, per-spec cost observability — e.g. push each call\n * to Langfuse without waiting for the run to finish. For aggregated totals,\n * read `agent.metrics` instead.\n */\n onLLMUsage?: (usage: AIUsageInfo) => void;\n}\n\nexport type TestStatus =\n | 'passed'\n | 'failed'\n | 'timedOut'\n | 'skipped'\n | 'interrupted';\n\nexport interface ReportFileAttributes {\n testDuration: number;\n testStatus: TestStatus;\n testTitle: string;\n testId: string;\n testDescription: string;\n}\n\ntype SkippedReportFileAttributes = Omit<ReportFileAttributes, 'testStatus'> & {\n testStatus: 'skipped';\n};\n\nexport type ReportFileWithAttributes =\n | {\n reportFilePath: string;\n reportAttributes: ReportFileAttributes;\n }\n | {\n reportFilePath?: undefined;\n reportAttributes: SkippedReportFileAttributes;\n };\n"],"names":["UIContext","aiActProgressScope"],"mappings":";;;AAqLO,MAAeA;AAqCtB;AAqWO,MAAMC,qBAAqB"}
|
package/dist/es/utils.mjs
CHANGED
|
@@ -184,7 +184,7 @@ function stringifyDumpData(data, indents) {
|
|
|
184
184
|
return JSON.stringify(data, replacerForPageObject, indents);
|
|
185
185
|
}
|
|
186
186
|
function getVersion() {
|
|
187
|
-
return "1.17.
|
|
187
|
+
return "1.17.5-beta-20261102094111.0";
|
|
188
188
|
}
|
|
189
189
|
function debugLog(...message) {
|
|
190
190
|
const debugMode = process.env[MIDSCENE_DEBUG_MODE];
|
package/dist/lib/agent/agent.js
CHANGED
|
@@ -46,6 +46,7 @@ var external_service_index_js_default = /*#__PURE__*/ __webpack_require__.n(exte
|
|
|
46
46
|
const resource_operations_js_namespaceObject = require("../test-runner/engine/resource-operations.js");
|
|
47
47
|
const external_types_js_namespaceObject = require("../types.js");
|
|
48
48
|
const execution_session_js_namespaceObject = require("../yaml/execution-session.js");
|
|
49
|
+
const external_planned_wait_js_namespaceObject = require("./planned-wait.js");
|
|
49
50
|
const external_yaml_index_js_namespaceObject = require("../yaml/index.js");
|
|
50
51
|
const promises_namespaceObject = require("node:fs/promises");
|
|
51
52
|
const external_node_path_namespaceObject = require("node:path");
|
|
@@ -503,7 +504,11 @@ class Agent {
|
|
|
503
504
|
const runAiAct = async ()=>{
|
|
504
505
|
const planningModel = this.resolveModelRuntime('planning', 'planning');
|
|
505
506
|
const locateModel = this.resolveModelRuntime('locate', 'locate');
|
|
506
|
-
const
|
|
507
|
+
const userContext = this.resolveUserContext('aiAct', opt?.context);
|
|
508
|
+
const aiActContext = this.opts.planningWaitFor ? [
|
|
509
|
+
external_planned_wait_js_namespaceObject.plannedWaitContext,
|
|
510
|
+
userContext
|
|
511
|
+
].filter(Boolean).join('\n\n') : userContext;
|
|
507
512
|
const cachePrompt = (0, external_prompt_context_js_namespaceObject.buildPromptWithContext)(taskPrompt, aiActContext);
|
|
508
513
|
const effort = (()=>{
|
|
509
514
|
const resolvedEffort = opt?.effort ?? (opt?.deepThink === true ? 'deepThink' : 'balance');
|
|
@@ -520,7 +525,7 @@ class Agent {
|
|
|
520
525
|
warn(`The "deepLocate" option is not supported for aiAct with the current planning adapter (modelFamily: ${planningModel.config.modelFamily ?? 'unknown'}). It will be ignored.`);
|
|
521
526
|
deepLocate = false;
|
|
522
527
|
}
|
|
523
|
-
const cacheable = opt?.cacheable;
|
|
528
|
+
const cacheable = opt?.checkScreenChanges ? false : opt?.cacheable;
|
|
524
529
|
const replanningCycleLimit = this.resolveReplanningCycleLimit(planningModel);
|
|
525
530
|
const planCacheEnabled = planningModel.adapter.planning.cacheEnabled;
|
|
526
531
|
const matchedCache = planCacheEnabled && false !== cacheable ? this.taskCache?.matchPlanCache(cachePrompt) : void 0;
|
|
@@ -542,13 +547,13 @@ class Agent {
|
|
|
542
547
|
});
|
|
543
548
|
return;
|
|
544
549
|
} catch (error) {
|
|
545
|
-
if (error instanceof execution_session_js_namespaceObject.YamlExecutionOwnershipError || (0, external_action_readiness_js_namespaceObject.isActionReadinessError)(error)) throw error;
|
|
550
|
+
if (error instanceof execution_session_js_namespaceObject.YamlExecutionOwnershipError || (0, external_action_readiness_js_namespaceObject.isActionReadinessError)(error) || (0, external_planned_wait_js_namespaceObject.isPlannedWaitError)(error)) throw error;
|
|
546
551
|
abortSignal?.throwIfAborted();
|
|
547
552
|
cachedYamlFailed = true;
|
|
548
553
|
warn(`cached aiAct plan failed, will replan and disable the stale cache: ${error instanceof Error ? error.message : String(error)}`);
|
|
549
554
|
}
|
|
550
555
|
}
|
|
551
|
-
const { output: actionOutput } = await this.taskExecutor.action(taskPrompt, planningModel, locateModel, aiActContext, cacheable, replanningCycleLimit, effort, void 0, deepLocate, abortSignal, internalReportDisplay);
|
|
556
|
+
const { output: actionOutput } = await this.taskExecutor.action(taskPrompt, planningModel, locateModel, aiActContext, cacheable, replanningCycleLimit, effort, void 0, deepLocate, abortSignal, internalReportDisplay, opt?.checkScreenChanges);
|
|
552
557
|
if (this.taskCache && false !== cacheable) {
|
|
553
558
|
const yamlFlow = cachedYamlFailed ? [] : actionOutput?.yamlFlow;
|
|
554
559
|
if (!cachedYamlFailed && !yamlFlow?.length) return actionOutput?.output;
|
|
@@ -927,6 +932,7 @@ class Agent {
|
|
|
927
932
|
cacheDir: cacheConfigObj.cacheDir
|
|
928
933
|
});
|
|
929
934
|
const baseActionSpace = this.interface.actionSpace();
|
|
935
|
+
if (this.opts.planningWaitFor && baseActionSpace.some((action)=>'WaitFor' === action.name)) throw new Error('planningWaitFor reserves the WaitFor action name; remove the custom WaitFor action or disable planningWaitFor');
|
|
930
936
|
const fileChooserActions = this.interface.registerFileChooserListener ? [
|
|
931
937
|
(0, external_device_index_js_namespaceObject.defineActionRegisterFileChooserAccept)(async (files)=>{
|
|
932
938
|
if (!this.activeFileChooserAccepter) throw new Error('RegisterFileChooserAccept can only be used while aiAct is running');
|
|
@@ -937,6 +943,15 @@ class Agent {
|
|
|
937
943
|
this.fullActionSpace = [
|
|
938
944
|
...baseActionSpace,
|
|
939
945
|
...fileChooserActions,
|
|
946
|
+
...this.opts.planningWaitFor ? [
|
|
947
|
+
(0, external_planned_wait_js_namespaceObject.definePlannedWait)(async (condition, abortSignal)=>{
|
|
948
|
+
await this.aiWaitFor(condition, {
|
|
949
|
+
timeoutMs: 30000,
|
|
950
|
+
checkIntervalMs: 2000,
|
|
951
|
+
abortSignal
|
|
952
|
+
});
|
|
953
|
+
})
|
|
954
|
+
] : [],
|
|
940
955
|
(0, external_device_index_js_namespaceObject.defineActionSleep)()
|
|
941
956
|
];
|
|
942
957
|
this.taskExecutor = new external_tasks_js_namespaceObject.TaskExecutor(this.interface, this.service, {
|
|
@@ -944,6 +959,7 @@ class Agent {
|
|
|
944
959
|
taskCache: this.taskCache,
|
|
945
960
|
onTaskStart: this.callbackOnTaskStartTip.bind(this),
|
|
946
961
|
replanningCycleLimit: this.opts.replanningCycleLimit,
|
|
962
|
+
planningWaitFor: this.opts.planningWaitFor,
|
|
947
963
|
waitAfterAction: this.opts.waitAfterAction,
|
|
948
964
|
actionReadiness: this.actionReadiness,
|
|
949
965
|
useDeviceTime: this.opts.useDeviceTime,
|