@midscene/test 1.12.4-beta-20260903111111.0 → 1.12.4
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/android/index.mjs +50 -106
- package/dist/es/android/index.mjs.map +1 -1
- package/dist/es/cli/index.mjs +99 -149
- package/dist/es/cli/index.mjs.map +1 -1
- package/dist/es/harmony/index.mjs +119 -0
- package/dist/es/harmony/index.mjs.map +1 -0
- package/dist/es/index.mjs +36 -87
- package/dist/es/index.mjs.map +1 -1
- package/dist/es/ios/index.mjs +51 -101
- package/dist/es/ios/index.mjs.map +1 -1
- package/dist/es/midscene/index.mjs +37 -235
- package/dist/es/midscene/index.mjs.map +1 -1
- package/dist/es/playwright/index.mjs +14 -10
- package/dist/es/playwright/index.mjs.map +1 -1
- package/dist/es/test-cli.mjs +102 -150
- package/dist/es/test-cli.mjs.map +1 -1
- package/dist/lib/android/index.js +151 -178
- package/dist/lib/android/index.js.map +1 -1
- package/dist/lib/cli/index.js +99 -149
- package/dist/lib/cli/index.js.map +1 -1
- package/dist/lib/harmony/index.js +188 -0
- package/dist/lib/harmony/index.js.map +1 -0
- package/dist/lib/index.js +37 -100
- package/dist/lib/index.js.map +1 -1
- package/dist/lib/ios/index.js +152 -173
- package/dist/lib/ios/index.js.map +1 -1
- package/dist/lib/midscene/index.js +264 -412
- package/dist/lib/midscene/index.js.map +1 -1
- package/dist/lib/playwright/index.js +14 -10
- package/dist/lib/playwright/index.js.map +1 -1
- package/dist/lib/test-cli.js +102 -150
- package/dist/lib/test-cli.js.map +1 -1
- package/dist/types/android/index.d.ts +27 -101
- package/dist/types/cli/index.d.ts +9 -32
- package/dist/types/harmony/index.d.ts +124 -0
- package/dist/types/index.d.ts +18 -45
- package/dist/types/ios/index.d.ts +28 -107
- package/dist/types/midscene/index.d.ts +54 -153
- package/dist/types/playwright/index.d.ts +9 -63
- package/package.json +25 -6
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { androidAgentTestRunnerNodeDefinitions, launchInputSchema, runAdbShellInputSchema, runAdbShellOptionsInputSchema, terminateInputSchema } from "@midscene/android/test-runner";
|
|
2
|
+
import "@midscene/core/agent/test-runner";
|
|
1
3
|
import { z } from "zod/v4";
|
|
2
4
|
function _define_property(obj, key, value) {
|
|
3
5
|
if (key in obj) Object.defineProperty(obj, key, {
|
|
@@ -29,7 +31,7 @@ class WorkflowError extends Error {
|
|
|
29
31
|
this.details = options.details;
|
|
30
32
|
}
|
|
31
33
|
}
|
|
32
|
-
class
|
|
34
|
+
class errors_NodeDefinitionError extends WorkflowError {
|
|
33
35
|
constructor(message, details){
|
|
34
36
|
super(message, {
|
|
35
37
|
code: 'NODE_DEFINITION_ERROR',
|
|
@@ -37,139 +39,81 @@ class NodeDefinitionError extends WorkflowError {
|
|
|
37
39
|
});
|
|
38
40
|
}
|
|
39
41
|
}
|
|
40
|
-
class NodeExecutionError extends WorkflowError {
|
|
41
|
-
constructor(node, cause){
|
|
42
|
-
const causeMessage = cause instanceof Error ? cause.message : String(cause ?? 'Unknown error');
|
|
43
|
-
super(`Node "${node}" failed: ${causeMessage}`, {
|
|
44
|
-
code: 'NODE_EXECUTION_ERROR',
|
|
45
|
-
details: {
|
|
46
|
-
node
|
|
47
|
-
},
|
|
48
|
-
cause
|
|
49
|
-
}), _define_property(this, "node", void 0);
|
|
50
|
-
this.node = node;
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
42
|
const validateOptionalText = (value, field, node)=>{
|
|
54
|
-
if (void 0 !== value && ('string' != typeof value || 0 === value.trim().length)) throw new
|
|
43
|
+
if (void 0 !== value && ('string' != typeof value || 0 === value.trim().length)) throw new errors_NodeDefinitionError(`Node "${node}" ${field} must be a non-empty string.`, {
|
|
55
44
|
node,
|
|
56
45
|
field
|
|
57
46
|
});
|
|
58
47
|
};
|
|
59
48
|
const validateInputSchema = (schema, node)=>{
|
|
60
49
|
if (void 0 === schema) return;
|
|
61
|
-
if (!(schema instanceof z.ZodObject)) throw new
|
|
50
|
+
if (!(schema instanceof z.ZodObject)) throw new errors_NodeDefinitionError(`Node "${node}" inputSchema must be a Zod object schema.`, {
|
|
62
51
|
node,
|
|
63
52
|
field: 'inputSchema'
|
|
64
53
|
});
|
|
65
|
-
if ('$' in schema.shape) throw new
|
|
54
|
+
if ('$' in schema.shape) throw new errors_NodeDefinitionError(`Node "${node}" inputSchema must not declare "$" as an input property.`, {
|
|
66
55
|
node,
|
|
67
56
|
field: 'inputSchema.$'
|
|
68
57
|
});
|
|
69
58
|
};
|
|
70
59
|
const validateDefinition = (options)=>{
|
|
71
|
-
if (!options || 'object' != typeof options) throw new
|
|
72
|
-
if ('string' != typeof options.name || 0 === options.name.trim().length) throw new
|
|
60
|
+
if (!options || 'object' != typeof options) throw new errors_NodeDefinitionError('Node definition must be an object.');
|
|
61
|
+
if ('string' != typeof options.name || 0 === options.name.trim().length) throw new errors_NodeDefinitionError('Node name must be a non-empty string.');
|
|
73
62
|
validateOptionalText(options.title, 'title', options.name);
|
|
74
63
|
validateOptionalText(options.description, "description", options.name);
|
|
64
|
+
if (void 0 !== options.stringInputKey && false !== options.stringInputKey && ('string' != typeof options.stringInputKey || 0 === options.stringInputKey.trim().length)) throw new errors_NodeDefinitionError(`Node "${options.name}" stringInputKey must be a non-empty string or false.`, {
|
|
65
|
+
node: options.name,
|
|
66
|
+
field: 'stringInputKey'
|
|
67
|
+
});
|
|
75
68
|
validateInputSchema(options.inputSchema, options.name);
|
|
76
|
-
if ('
|
|
69
|
+
if ('string' == typeof options.stringInputKey && options.inputSchema instanceof z.ZodObject && !(options.stringInputKey in options.inputSchema.shape)) throw new errors_NodeDefinitionError(`Node "${options.name}" stringInputKey must reference a field in inputSchema.`, {
|
|
70
|
+
node: options.name,
|
|
71
|
+
field: 'stringInputKey'
|
|
72
|
+
});
|
|
73
|
+
if ('function' != typeof options.execute) throw new errors_NodeDefinitionError(`Node "${options.name}" must provide an execute function.`, {
|
|
77
74
|
node: options.name
|
|
78
75
|
});
|
|
79
76
|
};
|
|
80
|
-
function
|
|
77
|
+
function define_node_defineNode(options) {
|
|
81
78
|
validateDefinition(options);
|
|
82
79
|
return options;
|
|
83
80
|
}
|
|
84
|
-
const
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
});
|
|
93
|
-
const launchInputSchema = lifecycleInputSchema('launch', 'The app, URL, URI, package name, or bundle identifier to launch.');
|
|
94
|
-
const terminateInputSchema = lifecycleInputSchema('terminate', 'The package name, bundle identifier, or app name to terminate.');
|
|
95
|
-
const requireLifecycleMethod = (agent, method, agentName)=>{
|
|
96
|
-
if ('object' != typeof agent || null === agent || 'function' != typeof agent[method]) throw new NodeExecutionError(method, new TypeError(`getAgent() must return ${agentName} with ${method}().`));
|
|
97
|
-
return agent[method];
|
|
98
|
-
};
|
|
99
|
-
const createLaunchNode = (getAgent, agentName = 'an Agent')=>defineNode({
|
|
100
|
-
name: 'launch',
|
|
101
|
-
description: 'Launch an app, URL, or URI through the current Midscene Agent. This Node does not install or manage applications.',
|
|
102
|
-
inputSchema: launchInputSchema,
|
|
103
|
-
async execute (ctx) {
|
|
104
|
-
const uri = ctx.input.uri ?? ctx.input.prompt;
|
|
105
|
-
const agent = await getAgent(ctx);
|
|
106
|
-
const launch = requireLifecycleMethod(agent, 'launch', agentName);
|
|
107
|
-
await launch.call(agent, uri);
|
|
108
|
-
return {
|
|
109
|
-
summary: `Launched ${uri}`
|
|
110
|
-
};
|
|
111
|
-
}
|
|
112
|
-
});
|
|
113
|
-
const createTerminateNode = (getAgent, agentName)=>defineNode({
|
|
114
|
-
name: 'terminate',
|
|
115
|
-
description: 'Terminate an application through the current Midscene Agent. This Node does not uninstall the application or clear its data.',
|
|
116
|
-
inputSchema: terminateInputSchema,
|
|
117
|
-
async execute (ctx) {
|
|
118
|
-
const uri = ctx.input.uri ?? ctx.input.prompt;
|
|
119
|
-
const agent = await getAgent(ctx);
|
|
120
|
-
const terminate = requireLifecycleMethod(agent, 'terminate', agentName);
|
|
121
|
-
await terminate.call(agent, uri);
|
|
122
|
-
return {
|
|
123
|
-
summary: `Terminated ${uri}`
|
|
124
|
-
};
|
|
125
|
-
}
|
|
126
|
-
});
|
|
127
|
-
const createDeviceLifecycleNodes = (getAgent, agentName)=>[
|
|
128
|
-
createLaunchNode(getAgent, agentName),
|
|
129
|
-
createTerminateNode(getAgent, agentName)
|
|
130
|
-
];
|
|
131
|
-
const runAdbShellInputSchema = z.strictObject({
|
|
132
|
-
prompt: z.string().regex(/\S/).optional().describe('String shorthand for the ADB shell command.'),
|
|
133
|
-
command: z.string().regex(/\S/).optional().describe('The shell command, without an adb shell prefix.'),
|
|
134
|
-
timeoutMs: z.number().int().positive().optional().describe('ADB shell command timeout in milliseconds.')
|
|
135
|
-
}).superRefine((input, ctx)=>{
|
|
136
|
-
if (void 0 === input.prompt === (void 0 === input.command)) ctx.addIssue({
|
|
137
|
-
code: 'custom',
|
|
138
|
-
message: 'exactly one of prompt and command is required'
|
|
139
|
-
});
|
|
81
|
+
const nonBlankPrompt = (description)=>z.string().regex(/\S/, 'prompt must contain a non-whitespace character').describe(description);
|
|
82
|
+
z.strictObject({
|
|
83
|
+
duration: z.number().positive().describe('How long to wait.'),
|
|
84
|
+
unit: z["enum"]([
|
|
85
|
+
'ms',
|
|
86
|
+
's',
|
|
87
|
+
'min'
|
|
88
|
+
]).default('ms').describe('Duration unit: milliseconds, seconds, or minutes.')
|
|
140
89
|
});
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
90
|
+
z.strictObject({
|
|
91
|
+
prompt: nonBlankPrompt('A self-contained task, including allowed tools and success conditions.')
|
|
92
|
+
});
|
|
93
|
+
const createAgentTestRunnerNodes = (definitions, getAgent)=>definitions.map((definition)=>define_node_defineNode({
|
|
94
|
+
name: definition.name,
|
|
95
|
+
...void 0 === definition.title ? {} : {
|
|
96
|
+
title: definition.title
|
|
97
|
+
},
|
|
98
|
+
...void 0 === definition.description ? {} : {
|
|
99
|
+
description: definition.description
|
|
100
|
+
},
|
|
101
|
+
...void 0 === definition.stringInputKey ? {} : {
|
|
102
|
+
stringInputKey: definition.stringInputKey
|
|
103
|
+
},
|
|
104
|
+
inputSchema: definition.inputSchema,
|
|
151
105
|
async execute (ctx) {
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
const agent = await options.getAgent(ctx);
|
|
156
|
-
if ('function' != typeof agent?.runAdbShell) throw new NodeExecutionError('runAdbShell', new TypeError('getAgent() must return an Android Agent with runAdbShell().'));
|
|
157
|
-
const stdout = await agent.runAdbShell(command, {
|
|
158
|
-
...void 0 === ctx.input.timeoutMs ? {} : {
|
|
159
|
-
timeout: ctx.input.timeoutMs
|
|
160
|
-
}
|
|
106
|
+
const agent = await getAgent(ctx);
|
|
107
|
+
return definition.execute(agent, ctx.input, {
|
|
108
|
+
signal: ctx.signal
|
|
161
109
|
});
|
|
162
|
-
if ('string' != typeof stdout) throw new NodeExecutionError('runAdbShell', new TypeError('runAdbShell() must return stdout as a string.'));
|
|
163
|
-
return {
|
|
164
|
-
summary: `Executed ADB shell command (${stdout.length} stdout characters)`,
|
|
165
|
-
data: {
|
|
166
|
-
stdout
|
|
167
|
-
}
|
|
168
|
-
};
|
|
169
110
|
}
|
|
170
|
-
})
|
|
171
|
-
|
|
111
|
+
}));
|
|
112
|
+
function createAndroidNodes(options) {
|
|
113
|
+
if (!options || 'object' != typeof options) throw new errors_NodeDefinitionError('createAndroidNodes() options must be an object.');
|
|
114
|
+
if ('function' != typeof options.getAgent) throw new errors_NodeDefinitionError('createAndroidNodes() requires getAgent().');
|
|
115
|
+
return createAgentTestRunnerNodes(androidAgentTestRunnerNodeDefinitions, options.getAgent);
|
|
172
116
|
}
|
|
173
|
-
export { createAndroidNodes, launchInputSchema, runAdbShellInputSchema, terminateInputSchema };
|
|
117
|
+
export { createAndroidNodes, launchInputSchema, runAdbShellInputSchema, runAdbShellOptionsInputSchema, terminateInputSchema };
|
|
174
118
|
|
|
175
119
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"android/index.mjs","sources":["../../../src/errors.ts","../../../src/node/define-node.ts","../../../src/device/lifecycle.ts","../../../src/android/index.ts"],"sourcesContent":["import type { z } from 'zod/v4';\n\nexport interface WorkflowErrorOptions {\n code?: string;\n details?: unknown;\n cause?: unknown;\n}\n\nexport class WorkflowError extends Error {\n readonly code: string;\n readonly details?: unknown;\n\n constructor(message: string, options: WorkflowErrorOptions = {}) {\n super(message, { cause: options.cause });\n this.name = new.target.name;\n this.code = options.code ?? 'WORKFLOW_ERROR';\n this.details = options.details;\n }\n\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n ...(this.details === undefined ? {} : { details: this.details }),\n };\n }\n}\n\nexport class WorkflowParseError extends WorkflowError {\n constructor(message: string, details?: unknown, cause?: unknown) {\n super(message, { code: 'WORKFLOW_PARSE_ERROR', details, cause });\n }\n}\n\nexport class NodeDefinitionError extends WorkflowError {\n constructor(message: string, details?: unknown) {\n super(message, { code: 'NODE_DEFINITION_ERROR', details });\n }\n}\n\nexport class DuplicateNodeError extends WorkflowError {\n readonly node: string;\n\n constructor(node: string) {\n super(`Node \"${node}\" is already registered.`, {\n code: 'DUPLICATE_NODE',\n details: { node },\n });\n this.node = node;\n }\n}\n\nexport class NodeNotFoundError extends WorkflowError {\n readonly node: string;\n\n constructor(node: string) {\n super(`Node \"${node}\" is not registered.`, {\n code: 'NODE_NOT_FOUND',\n details: { node },\n });\n this.node = node;\n }\n}\n\nexport class NodeInputValidationError extends WorkflowError {\n constructor(message: string, details?: unknown) {\n super(message, { code: 'NODE_INPUT_VALIDATION_ERROR', details });\n }\n\n static fromZod(node: string, error: z.ZodError): NodeInputValidationError {\n const issues = error.issues.map((issue) => ({\n code: issue.code,\n path: issue.path.map(String).join('.'),\n message: issue.message,\n }));\n const firstIssue = issues[0];\n const path = firstIssue?.path || '<root>';\n const message = firstIssue?.message ?? 'invalid input';\n return new NodeInputValidationError(\n `Node \"${node}\" input validation failed at \"${path}\": ${message}`,\n { node, issues },\n );\n }\n}\n\nexport class StepTimeoutError extends WorkflowError {\n readonly timeoutMs: number;\n readonly node?: string;\n\n constructor(timeoutMs: number, node?: string) {\n super(\n node\n ? `Node \"${node}\" timed out after ${timeoutMs}ms.`\n : `Step timed out after ${timeoutMs}ms.`,\n {\n code: 'STEP_TIMEOUT',\n details: { timeoutMs, ...(node === undefined ? {} : { node }) },\n },\n );\n this.timeoutMs = timeoutMs;\n this.node = node;\n }\n}\n\nexport class NodeExecutionError extends WorkflowError {\n readonly node: string;\n\n constructor(node: string, cause: unknown) {\n const causeMessage =\n cause instanceof Error ? cause.message : String(cause ?? 'Unknown error');\n super(`Node \"${node}\" failed: ${causeMessage}`, {\n code: 'NODE_EXECUTION_ERROR',\n details: { node },\n cause,\n });\n this.node = node;\n }\n}\n\nexport class WorkflowLifecycleError extends WorkflowError {\n constructor(message: string, details?: unknown) {\n super(message, { code: 'WORKFLOW_LIFECYCLE_ERROR', details });\n }\n}\n\nexport class ProjectSetupError extends WorkflowError {\n constructor(cause: unknown, details: { projectName: string }) {\n const causeMessage =\n cause instanceof Error ? cause.message : String(cause ?? 'Unknown error');\n super(`Project \"${details.projectName}\" setup failed: ${causeMessage}`, {\n code: 'PROJECT_SETUP_ERROR',\n details,\n cause,\n });\n }\n}\n\nexport class ProjectTeardownError extends WorkflowError {\n constructor(\n cause: unknown,\n details: { projectName: string; registrationIndex: number },\n ) {\n const causeMessage =\n cause instanceof Error ? cause.message : String(cause ?? 'Unknown error');\n super(`Project \"${details.projectName}\" teardown failed: ${causeMessage}`, {\n code: 'PROJECT_TEARDOWN_ERROR',\n details,\n cause,\n });\n }\n}\n\nexport class NodeScopeTeardownError extends WorkflowError {\n constructor(\n cause: unknown,\n details: {\n scope: 'case' | 'document';\n scopeId: string;\n node: string;\n registrationIndex: number;\n },\n ) {\n const causeMessage =\n cause instanceof Error ? cause.message : String(cause ?? 'Unknown error');\n super(\n `${details.scope === 'case' ? 'Case attempt' : 'Workflow document'} node teardown failed for \"${details.node}\": ${causeMessage}`,\n { code: 'NODE_SCOPE_TEARDOWN_ERROR', details, cause },\n );\n }\n}\n\nexport class FatalDeviceError extends WorkflowError {\n constructor(message: string, cause?: unknown) {\n super(message, { code: 'FATAL_DEVICE_ERROR', cause });\n }\n}\n\nexport const isFatalDeviceError = (error: unknown): boolean => {\n if (error instanceof FatalDeviceError) return true;\n if (error instanceof WorkflowError && error.code === 'FATAL_DEVICE_ERROR') {\n return true;\n }\n if (\n error instanceof Error &&\n /device offline|device not found|(?:adb|bdc|device) connection (?:was )?closed/i.test(\n error.message,\n )\n ) {\n return true;\n }\n return error instanceof Error && error.cause !== undefined\n ? isFatalDeviceError(error.cause)\n : false;\n};\n\nexport class CaseExecutionError extends WorkflowError {\n readonly result: import('./engine/types').CaseRunResult;\n\n constructor(result: import('./engine/types').CaseRunResult) {\n super(`Case \"${result.name}\" failed.`, {\n code: 'CASE_EXECUTION_FAILED',\n details: { caseId: result.caseId, runId: result.runId },\n });\n this.result = result;\n }\n}\n\nexport class WorkflowDocumentExecutionError extends WorkflowError {\n readonly result: import('./engine/types').WorkflowDocumentRunResult;\n\n constructor(result: import('./engine/types').WorkflowDocumentRunResult) {\n super(`Workflow document \"${result.sourcePath}\" failed.`, {\n code: 'WORKFLOW_DOCUMENT_EXECUTION_FAILED',\n details: {\n documentId: result.documentId,\n documentRunId: result.documentRunId,\n },\n });\n this.result = result;\n }\n}\n\nexport function normalizeNodeExecutionError(\n error: unknown,\n node: string,\n): WorkflowError {\n return error instanceof WorkflowError\n ? error\n : new NodeExecutionError(node, error);\n}\n","import { z } from 'zod/v4';\nimport { NodeDefinitionError } from '../errors';\nimport type {\n DefineNodeOptions,\n DefineNodeWithSchemaOptions,\n NodeDefinition,\n NodeDefinitionWithSchema,\n NodeInputSchema,\n} from './types';\n\nconst validateOptionalText = (\n value: unknown,\n field: 'title' | 'description',\n node: string,\n): void => {\n if (\n value !== undefined &&\n (typeof value !== 'string' || value.trim().length === 0)\n ) {\n throw new NodeDefinitionError(\n `Node \"${node}\" ${field} must be a non-empty string.`,\n { node, field },\n );\n }\n};\n\nconst validateInputSchema = (schema: unknown, node: string): void => {\n if (schema === undefined) return;\n if (!(schema instanceof z.ZodObject)) {\n throw new NodeDefinitionError(\n `Node \"${node}\" inputSchema must be a Zod object schema.`,\n { node, field: 'inputSchema' },\n );\n }\n if ('$' in schema.shape) {\n throw new NodeDefinitionError(\n `Node \"${node}\" inputSchema must not declare \"$\" as an input property.`,\n { node, field: 'inputSchema.$' },\n );\n }\n};\n\nconst validateDefinition = (options: {\n name: string;\n title?: unknown;\n description?: unknown;\n inputSchema?: unknown;\n execute: unknown;\n}): void => {\n if (!options || typeof options !== 'object') {\n throw new NodeDefinitionError('Node definition must be an object.');\n }\n\n if (typeof options.name !== 'string' || options.name.trim().length === 0) {\n throw new NodeDefinitionError('Node name must be a non-empty string.');\n }\n\n validateOptionalText(options.title, 'title', options.name);\n validateOptionalText(options.description, 'description', options.name);\n validateInputSchema(options.inputSchema, options.name);\n\n if (typeof options.execute !== 'function') {\n throw new NodeDefinitionError(\n `Node \"${options.name}\" must provide an execute function.`,\n { node: options.name },\n );\n }\n};\n\nexport function defineNode<\n TSchema extends NodeInputSchema,\n TData = unknown,\n TContext = unknown,\n>(\n options: DefineNodeWithSchemaOptions<TSchema, TData, TContext>,\n): NodeDefinitionWithSchema<TSchema, TData, TContext>;\n\nexport function defineNode<\n TInput = unknown,\n TData = unknown,\n TContext = unknown,\n>(\n options: DefineNodeOptions<TInput, TData, TContext>,\n): NodeDefinition<TInput, TData, TContext>;\n\nexport function defineNode(\n options: DefineNodeOptions<any, any, any>,\n): NodeDefinition<any, any, any> {\n validateDefinition(options);\n return options;\n}\n","import { z } from 'zod/v4';\nimport type { Awaitable } from '../engine/types';\nimport { NodeExecutionError } from '../errors';\nimport { defineNode } from '../node/define-node';\nimport type { NodeDefinition, NodeExecutionContext } from '../node/types';\n\ntype NodeContext<TContext> = NodeExecutionContext<unknown, TContext>;\ntype AgentGetter<TContext> = (ctx: NodeContext<TContext>) => Awaitable<unknown>;\ntype LifecycleMethod = 'launch' | 'terminate';\n\n/** Device capabilities required by Android and iOS lifecycle Nodes. */\nexport interface DeviceLifecycleAgent {\n launch(uri: string): Promise<void>;\n terminate(uri: string): Promise<void>;\n}\n\nconst lifecycleInputSchema = (\n operation: LifecycleMethod,\n description: string,\n) =>\n z\n .strictObject({\n prompt: z\n .string()\n .regex(/\\S/, 'prompt must contain a non-whitespace character')\n .optional()\n .describe(`String shorthand for the app to ${operation}.`),\n uri: z\n .string()\n .regex(/\\S/, 'uri must contain a non-whitespace character')\n .optional()\n .describe(description),\n })\n .superRefine((input, ctx) => {\n if ((input.prompt === undefined) === (input.uri === undefined)) {\n ctx.addIssue({\n code: 'custom',\n message: 'exactly one of prompt and uri is required',\n });\n }\n });\n\n/** Input schema for the device launch Node. */\nexport const launchInputSchema = lifecycleInputSchema(\n 'launch',\n 'The app, URL, URI, package name, or bundle identifier to launch.',\n);\n\n/** Input schema for the device terminate Node. */\nexport const terminateInputSchema = lifecycleInputSchema(\n 'terminate',\n 'The package name, bundle identifier, or app name to terminate.',\n);\n\nexport type LaunchNodeInput = z.infer<typeof launchInputSchema>;\nexport type TerminateNodeInput = z.infer<typeof terminateInputSchema>;\n\nconst requireLifecycleMethod = (\n agent: unknown,\n method: LifecycleMethod,\n agentName: string,\n): DeviceLifecycleAgent[LifecycleMethod] => {\n if (\n typeof agent !== 'object' ||\n agent === null ||\n typeof (agent as Record<LifecycleMethod, unknown>)[method] !== 'function'\n ) {\n throw new NodeExecutionError(\n method,\n new TypeError(`getAgent() must return ${agentName} with ${method}().`),\n );\n }\n return (agent as DeviceLifecycleAgent)[method];\n};\n\nexport const createLaunchNode = <TContext>(\n getAgent: AgentGetter<TContext>,\n agentName = 'an Agent',\n): NodeDefinition<any, any, TContext> =>\n defineNode<typeof launchInputSchema, unknown, TContext>({\n name: 'launch',\n description:\n 'Launch an app, URL, or URI through the current Midscene Agent. This Node does not install or manage applications.',\n inputSchema: launchInputSchema,\n async execute(ctx) {\n const uri = ctx.input.uri ?? ctx.input.prompt!;\n const agent = await getAgent(ctx);\n const launch = requireLifecycleMethod(agent, 'launch', agentName);\n await launch.call(agent, uri);\n return { summary: `Launched ${uri}` };\n },\n });\n\nconst createTerminateNode = <TContext>(\n getAgent: AgentGetter<TContext>,\n agentName: string,\n): NodeDefinition<any, any, TContext> =>\n defineNode<typeof terminateInputSchema, unknown, TContext>({\n name: 'terminate',\n description:\n 'Terminate an application through the current Midscene Agent. This Node does not uninstall the application or clear its data.',\n inputSchema: terminateInputSchema,\n async execute(ctx) {\n const uri = ctx.input.uri ?? ctx.input.prompt!;\n const agent = await getAgent(ctx);\n const terminate = requireLifecycleMethod(agent, 'terminate', agentName);\n await terminate.call(agent, uri);\n return { summary: `Terminated ${uri}` };\n },\n });\n\nexport const createDeviceLifecycleNodes = <TContext>(\n getAgent: (ctx: NodeContext<TContext>) => Awaitable<DeviceLifecycleAgent>,\n agentName: string,\n): readonly NodeDefinition<any, any, TContext>[] => [\n createLaunchNode(getAgent, agentName),\n createTerminateNode(getAgent, agentName),\n];\n","import { z } from 'zod/v4';\nimport {\n type DeviceLifecycleAgent,\n createDeviceLifecycleNodes,\n} from '../device/lifecycle';\nexport type {\n LaunchNodeInput,\n TerminateNodeInput,\n} from '../device/lifecycle';\nexport { launchInputSchema, terminateInputSchema } from '../device/lifecycle';\nimport type { Awaitable } from '../engine/types';\nimport { NodeDefinitionError, NodeExecutionError } from '../errors';\nimport { defineNode } from '../node/define-node';\nimport type { NodeDefinition, NodeExecutionContext } from '../node/types';\n\ntype NodeContext<TContext> = NodeExecutionContext<unknown, TContext>;\n\n/** Minimal Android Agent capability required by the preset Node. */\nexport interface AndroidRunnerAgent extends DeviceLifecycleAgent {\n /** Execute a command in the connected Android device shell. */\n runAdbShell(command: string, options?: { timeout?: number }): Promise<string>;\n}\n\n/** Dependencies used by the Android preset Nodes. */\nexport interface CreateAndroidNodesOptions<TContext> {\n /** Return the Android Agent associated with the current workflow. */\n getAgent(ctx: NodeContext<TContext>): Awaitable<AndroidRunnerAgent>;\n}\n\n/** Input schema for the Android runAdbShell Node. */\nexport const runAdbShellInputSchema = z\n .strictObject({\n prompt: z\n .string()\n .regex(/\\S/)\n .optional()\n .describe('String shorthand for the ADB shell command.'),\n command: z\n .string()\n .regex(/\\S/)\n .optional()\n .describe('The shell command, without an adb shell prefix.'),\n timeoutMs: z\n .number()\n .int()\n .positive()\n .optional()\n .describe('ADB shell command timeout in milliseconds.'),\n })\n .superRefine((input, ctx) => {\n if ((input.prompt === undefined) === (input.command === undefined)) {\n ctx.addIssue({\n code: 'custom',\n message: 'exactly one of prompt and command is required',\n });\n }\n });\n\n/** Validated input accepted by the Android runAdbShell Node. */\nexport type RunAdbShellNodeInput = z.infer<typeof runAdbShellInputSchema>;\n\n/** Create the P0 Android preset Nodes for an injected Android Agent. */\nexport function createAndroidNodes<TContext>(\n options: CreateAndroidNodesOptions<TContext>,\n): readonly NodeDefinition<any, any, TContext>[] {\n if (!options || typeof options !== 'object') {\n throw new NodeDefinitionError(\n 'createAndroidNodes() options must be an object.',\n );\n }\n if (typeof options.getAgent !== 'function') {\n throw new NodeDefinitionError('createAndroidNodes() requires getAgent().');\n }\n\n return [\n ...createDeviceLifecycleNodes(options.getAgent, 'an Android Agent'),\n defineNode<typeof runAdbShellInputSchema, { stdout: string }, TContext>({\n name: 'runAdbShell',\n title: 'Run an ADB shell command',\n description:\n 'Execute a shell command through the current Android Agent. Pass only the shell command, without the adb shell prefix.',\n inputSchema: runAdbShellInputSchema,\n async execute(ctx) {\n if (ctx.signal.aborted) {\n throw ctx.signal.reason ?? new Error('runAdbShell aborted.');\n }\n const command = ctx.input.command ?? ctx.input.prompt!;\n if (/^\\s*adb(?:\\s|$)/i.test(command)) {\n throw new NodeExecutionError(\n 'runAdbShell',\n new TypeError(\n 'command must not include an adb or adb shell prefix.',\n ),\n );\n }\n const agent = await options.getAgent(ctx);\n if (typeof agent?.runAdbShell !== 'function') {\n throw new NodeExecutionError(\n 'runAdbShell',\n new TypeError(\n 'getAgent() must return an Android Agent with runAdbShell().',\n ),\n );\n }\n const stdout = await agent.runAdbShell(command, {\n ...(ctx.input.timeoutMs === undefined\n ? {}\n : { timeout: ctx.input.timeoutMs }),\n });\n if (typeof stdout !== 'string') {\n throw new NodeExecutionError(\n 'runAdbShell',\n new TypeError('runAdbShell() must return stdout as a string.'),\n );\n }\n return {\n summary: `Executed ADB shell command (${stdout.length} stdout characters)`,\n data: { stdout },\n };\n },\n }),\n ];\n}\n"],"names":["WorkflowError","Error","undefined","message","options","NodeDefinitionError","details","NodeExecutionError","node","cause","causeMessage","String","validateOptionalText","value","field","validateInputSchema","schema","z","validateDefinition","defineNode","lifecycleInputSchema","operation","description","input","ctx","launchInputSchema","terminateInputSchema","requireLifecycleMethod","agent","method","agentName","TypeError","createLaunchNode","getAgent","uri","launch","createTerminateNode","terminate","createDeviceLifecycleNodes","runAdbShellInputSchema","createAndroidNodes","command","stdout"],"mappings":";;;;;;;;;;;AAQO,MAAMA,sBAAsBC;IAWjC,SAAkC;QAChC,OAAO;YACL,MAAM,IAAI,CAAC,IAAI;YACf,SAAS,IAAI,CAAC,OAAO;YACrB,MAAM,IAAI,CAAC,IAAI;YACf,GAAI,AAAiBC,WAAjB,IAAI,CAAC,OAAO,GAAiB,CAAC,IAAI;gBAAE,SAAS,IAAI,CAAC,OAAO;YAAC,CAAC;QACjE;IACF;IAdA,YAAYC,OAAe,EAAEC,UAAgC,CAAC,CAAC,CAAE;QAC/D,KAAK,CAACD,SAAS;YAAE,OAAOC,QAAQ,KAAK;QAAC,IAJxC,uBAAS,QAAT,SACA,uBAAS,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C,mBACR,eACA,IAAIwB,UAAU;gBAGlB,OAAO;oBACL,SAAS,CAAC,4BAA4B,EAAEW,OAAO,MAAM,CAAC,mBAAmB,CAAC;oBAC1E,MAAM;wBAAEA;oBAAO;gBACjB;YACF;QACF;KACD;AACH"}
|
|
1
|
+
{"version":3,"file":"android/index.mjs","sources":["../../../src/errors.ts","../../../src/node/define-node.ts","../../../src/midscene/index.ts","../../../src/android/index.ts"],"sourcesContent":["import type { z } from 'zod/v4';\n\nexport interface WorkflowErrorOptions {\n code?: string;\n details?: unknown;\n cause?: unknown;\n}\n\nexport class WorkflowError extends Error {\n readonly code: string;\n readonly details?: unknown;\n\n constructor(message: string, options: WorkflowErrorOptions = {}) {\n super(message, { cause: options.cause });\n this.name = new.target.name;\n this.code = options.code ?? 'WORKFLOW_ERROR';\n this.details = options.details;\n }\n\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n ...(this.details === undefined ? {} : { details: this.details }),\n };\n }\n}\n\nexport class WorkflowParseError extends WorkflowError {\n constructor(message: string, details?: unknown, cause?: unknown) {\n super(message, { code: 'WORKFLOW_PARSE_ERROR', details, cause });\n }\n}\n\nexport class NodeDefinitionError extends WorkflowError {\n constructor(message: string, details?: unknown) {\n super(message, { code: 'NODE_DEFINITION_ERROR', details });\n }\n}\n\nexport class DuplicateNodeError extends WorkflowError {\n readonly node: string;\n\n constructor(node: string) {\n super(`Node \"${node}\" is already registered.`, {\n code: 'DUPLICATE_NODE',\n details: { node },\n });\n this.node = node;\n }\n}\n\nexport class NodeNotFoundError extends WorkflowError {\n readonly node: string;\n\n constructor(node: string) {\n super(`Node \"${node}\" is not registered.`, {\n code: 'NODE_NOT_FOUND',\n details: { node },\n });\n this.node = node;\n }\n}\n\nexport class NodeInputValidationError extends WorkflowError {\n constructor(message: string, details?: unknown) {\n super(message, { code: 'NODE_INPUT_VALIDATION_ERROR', details });\n }\n\n static fromZod(node: string, error: z.ZodError): NodeInputValidationError {\n const issues = error.issues.map((issue) => ({\n code: issue.code,\n path: issue.path.map(String).join('.'),\n message: issue.message,\n }));\n const firstIssue = issues[0];\n const path = firstIssue?.path || '<root>';\n const message = firstIssue?.message ?? 'invalid input';\n return new NodeInputValidationError(\n `Node \"${node}\" input validation failed at \"${path}\": ${message}`,\n { node, issues },\n );\n }\n}\n\nexport class StepTimeoutError extends WorkflowError {\n readonly timeoutMs: number;\n readonly node?: string;\n\n constructor(timeoutMs: number, node?: string) {\n super(\n node\n ? `Node \"${node}\" timed out after ${timeoutMs}ms.`\n : `Step timed out after ${timeoutMs}ms.`,\n {\n code: 'STEP_TIMEOUT',\n details: { timeoutMs, ...(node === undefined ? {} : { node }) },\n },\n );\n this.timeoutMs = timeoutMs;\n this.node = node;\n }\n}\n\nexport class NodeExecutionError extends WorkflowError {\n readonly node: string;\n\n constructor(node: string, cause: unknown) {\n const causeMessage =\n cause instanceof Error ? cause.message : String(cause ?? 'Unknown error');\n super(`Node \"${node}\" failed: ${causeMessage}`, {\n code: 'NODE_EXECUTION_ERROR',\n details: { node },\n cause,\n });\n this.node = node;\n }\n}\n\nexport class WorkflowLifecycleError extends WorkflowError {\n constructor(message: string, details?: unknown) {\n super(message, { code: 'WORKFLOW_LIFECYCLE_ERROR', details });\n }\n}\n\nexport class ProjectSetupError extends WorkflowError {\n constructor(cause: unknown, details: { projectName: string }) {\n const causeMessage =\n cause instanceof Error ? cause.message : String(cause ?? 'Unknown error');\n super(`Project \"${details.projectName}\" setup failed: ${causeMessage}`, {\n code: 'PROJECT_SETUP_ERROR',\n details,\n cause,\n });\n }\n}\n\nexport class ProjectTeardownError extends WorkflowError {\n constructor(\n cause: unknown,\n details: { projectName: string; registrationIndex: number },\n ) {\n const causeMessage =\n cause instanceof Error ? cause.message : String(cause ?? 'Unknown error');\n super(`Project \"${details.projectName}\" teardown failed: ${causeMessage}`, {\n code: 'PROJECT_TEARDOWN_ERROR',\n details,\n cause,\n });\n }\n}\n\nexport class NodeScopeTeardownError extends WorkflowError {\n constructor(\n cause: unknown,\n details: {\n scope: 'case' | 'document';\n scopeId: string;\n node: string;\n registrationIndex: number;\n },\n ) {\n const causeMessage =\n cause instanceof Error ? cause.message : String(cause ?? 'Unknown error');\n super(\n `${details.scope === 'case' ? 'Case attempt' : 'Workflow document'} node teardown failed for \"${details.node}\": ${causeMessage}`,\n { code: 'NODE_SCOPE_TEARDOWN_ERROR', details, cause },\n );\n }\n}\n\nexport class FatalDeviceError extends WorkflowError {\n constructor(message: string, cause?: unknown) {\n super(message, { code: 'FATAL_DEVICE_ERROR', cause });\n }\n}\n\nexport const isFatalDeviceError = (error: unknown): boolean => {\n if (error instanceof FatalDeviceError) return true;\n if (error instanceof WorkflowError && error.code === 'FATAL_DEVICE_ERROR') {\n return true;\n }\n if (\n error instanceof Error &&\n /device offline|device not found|(?:adb|bdc|device) connection (?:was )?closed/i.test(\n error.message,\n )\n ) {\n return true;\n }\n return error instanceof Error && error.cause !== undefined\n ? isFatalDeviceError(error.cause)\n : false;\n};\n\nexport class CaseExecutionError extends WorkflowError {\n readonly result: import('./engine/types').CaseRunResult;\n\n constructor(result: import('./engine/types').CaseRunResult) {\n super(`Case \"${result.name}\" failed.`, {\n code: 'CASE_EXECUTION_FAILED',\n details: { caseId: result.caseId, runId: result.runId },\n });\n this.result = result;\n }\n}\n\nexport class WorkflowDocumentExecutionError extends WorkflowError {\n readonly result: import('./engine/types').WorkflowDocumentRunResult;\n\n constructor(result: import('./engine/types').WorkflowDocumentRunResult) {\n super(`Workflow document \"${result.sourcePath}\" failed.`, {\n code: 'WORKFLOW_DOCUMENT_EXECUTION_FAILED',\n details: {\n documentId: result.documentId,\n documentRunId: result.documentRunId,\n },\n });\n this.result = result;\n }\n}\n\nexport function normalizeNodeExecutionError(\n error: unknown,\n node: string,\n): WorkflowError {\n return error instanceof WorkflowError\n ? error\n : new NodeExecutionError(node, error);\n}\n","import { z } from 'zod/v4';\nimport { NodeDefinitionError } from '../errors';\nimport type {\n DefineNodeOptions,\n DefineNodeWithSchemaOptions,\n NodeDefinition,\n NodeDefinitionWithSchema,\n NodeInputSchema,\n} from './types';\n\nconst validateOptionalText = (\n value: unknown,\n field: 'title' | 'description',\n node: string,\n): void => {\n if (\n value !== undefined &&\n (typeof value !== 'string' || value.trim().length === 0)\n ) {\n throw new NodeDefinitionError(\n `Node \"${node}\" ${field} must be a non-empty string.`,\n { node, field },\n );\n }\n};\n\nconst validateInputSchema = (schema: unknown, node: string): void => {\n if (schema === undefined) return;\n if (!(schema instanceof z.ZodObject)) {\n throw new NodeDefinitionError(\n `Node \"${node}\" inputSchema must be a Zod object schema.`,\n { node, field: 'inputSchema' },\n );\n }\n if ('$' in schema.shape) {\n throw new NodeDefinitionError(\n `Node \"${node}\" inputSchema must not declare \"$\" as an input property.`,\n { node, field: 'inputSchema.$' },\n );\n }\n};\n\nconst validateDefinition = (options: {\n name: string;\n title?: unknown;\n description?: unknown;\n stringInputKey?: unknown;\n inputSchema?: unknown;\n execute: unknown;\n}): void => {\n if (!options || typeof options !== 'object') {\n throw new NodeDefinitionError('Node definition must be an object.');\n }\n\n if (typeof options.name !== 'string' || options.name.trim().length === 0) {\n throw new NodeDefinitionError('Node name must be a non-empty string.');\n }\n\n validateOptionalText(options.title, 'title', options.name);\n validateOptionalText(options.description, 'description', options.name);\n if (\n options.stringInputKey !== undefined &&\n options.stringInputKey !== false &&\n (typeof options.stringInputKey !== 'string' ||\n options.stringInputKey.trim().length === 0)\n ) {\n throw new NodeDefinitionError(\n `Node \"${options.name}\" stringInputKey must be a non-empty string or false.`,\n { node: options.name, field: 'stringInputKey' },\n );\n }\n validateInputSchema(options.inputSchema, options.name);\n\n if (\n typeof options.stringInputKey === 'string' &&\n options.inputSchema instanceof z.ZodObject &&\n !(options.stringInputKey in options.inputSchema.shape)\n ) {\n throw new NodeDefinitionError(\n `Node \"${options.name}\" stringInputKey must reference a field in inputSchema.`,\n { node: options.name, field: 'stringInputKey' },\n );\n }\n\n if (typeof options.execute !== 'function') {\n throw new NodeDefinitionError(\n `Node \"${options.name}\" must provide an execute function.`,\n { node: options.name },\n );\n }\n};\n\nexport function defineNode<\n TSchema extends NodeInputSchema,\n TData = unknown,\n TContext = unknown,\n>(\n options: DefineNodeWithSchemaOptions<TSchema, TData, TContext>,\n): NodeDefinitionWithSchema<TSchema, TData, TContext>;\n\nexport function defineNode<\n TInput = unknown,\n TData = unknown,\n TContext = unknown,\n>(\n options: DefineNodeOptions<TInput, TData, TContext>,\n): NodeDefinition<TInput, TData, TContext>;\n\nexport function defineNode(\n options: DefineNodeOptions<any, any, any>,\n): NodeDefinition<any, any, any> {\n validateDefinition(options);\n return options;\n}\n","import {\n type AgentTestRunnerNodeDefinition,\n type AgentTestRunnerNodeProvider,\n type CommonAgentTestRunnerApi,\n aiActInputSchema,\n aiActOptionsInputSchema,\n aiAssertInputSchema,\n aiAssertOptionsInputSchema,\n aiTapInputSchema,\n insightInputSchema,\n insightOptionsInputSchema,\n locateOptionsInputSchema,\n promptImageInputSchema,\n recordToReportInputSchema,\n recordToReportOptionsInputSchema,\n reportScreenshotInputSchema,\n structuredUserPromptInputSchema,\n userPromptInputSchema,\n} from '@midscene/core/agent/test-runner';\nimport { z } from 'zod/v4';\nimport type { Awaitable } from '../engine/types';\nimport { NodeDefinitionError, NodeExecutionError } from '../errors';\nimport { defineNode } from '../node/define-node';\nimport type {\n NodeDefinition,\n NodeExecutionContext,\n NodeResult,\n} from '../node/types';\n\nexport type MidsceneUIAgent = CommonAgentTestRunnerApi;\n\nexport {\n aiActInputSchema,\n aiActOptionsInputSchema,\n aiAssertInputSchema,\n aiAssertOptionsInputSchema,\n aiTapInputSchema,\n insightInputSchema,\n insightOptionsInputSchema,\n locateOptionsInputSchema,\n promptImageInputSchema,\n recordToReportInputSchema,\n recordToReportOptionsInputSchema,\n reportScreenshotInputSchema,\n structuredUserPromptInputSchema,\n userPromptInputSchema,\n};\n\nexport interface AgentProvider<TContext> {\n getAgent(\n runId: string,\n ctx: NodeExecutionContext<unknown, TContext>,\n ): Awaitable<MidsceneUIAgent>;\n // biome-ignore lint/suspicious/noConfusingVoidType: providers without a report intentionally return void.\n releaseAgent?(runId: string): Awaitable<AgentReleaseResult | void>;\n dispose?(): Awaitable<void>;\n}\n\nexport interface AgentReleaseResult {\n /** Absolute path to the finalized report for this Agent scope. */\n reportPath?: string;\n}\n\nexport interface AgentExecutorInput<TContext> {\n prompt: string;\n context: TContext;\n signal: AbortSignal;\n execution:\n | { scope: 'case'; runId: string }\n | { scope: 'document'; runId: string };\n}\n\nexport interface AgentExecutor<TContext> {\n // biome-ignore lint/suspicious/noConfusingVoidType: executors may perform side effects without returning a summary.\n execute(input: AgentExecutorInput<TContext>): Awaitable<NodeResult | void>;\n}\n\nconst nonBlankPrompt = (description: string) =>\n z\n .string()\n .regex(/\\S/, 'prompt must contain a non-whitespace character')\n .describe(description);\n\nexport const waitInputSchema = z.strictObject({\n duration: z.number().positive().describe('How long to wait.'),\n unit: z\n .enum(['ms', 's', 'min'])\n .default('ms')\n .describe('Duration unit: milliseconds, seconds, or minutes.'),\n});\n\nexport const agentInputSchema = z.strictObject({\n prompt: nonBlankPrompt(\n 'A self-contained task, including allowed tools and success conditions.',\n ),\n});\n\nexport type AiActNodeInput = z.infer<typeof aiActInputSchema>;\nexport type AiAssertNodeInput = z.infer<typeof aiAssertInputSchema>;\nexport type AiTapNodeInput = z.infer<typeof aiTapInputSchema>;\nexport type InsightNodeInput = z.infer<typeof insightInputSchema>;\nexport type RecordToReportNodeInput = z.infer<typeof recordToReportInputSchema>;\nexport type WaitNodeInput = z.infer<typeof waitInputSchema>;\nexport type AgentNodeInput = z.infer<typeof agentInputSchema>;\n\nexport interface CreateMidsceneNodesOptions<TContext> {\n getAgent?(\n ctx: NodeExecutionContext<unknown, TContext>,\n ): Awaitable<MidsceneUIAgent>;\n agentProvider?: AgentProvider<TContext>;\n /** Agent class that declares the Agent-backed Nodes to register. */\n agentClass: AgentTestRunnerNodeProvider;\n agentExecutor?: AgentExecutor<TContext>;\n}\n\nconst waitFor = async (durationMs: number, signal: AbortSignal) => {\n if (signal.aborted) {\n throw signal.reason ?? new Error('Wait aborted.');\n }\n await new Promise<void>((resolve, reject) => {\n const timeout = setTimeout(() => {\n signal.removeEventListener('abort', abort);\n resolve();\n }, durationMs);\n const abort = () => {\n clearTimeout(timeout);\n reject(signal.reason ?? new Error('Wait aborted.'));\n };\n signal.addEventListener('abort', abort, { once: true });\n });\n};\n\n/** Adapt Agent-owned descriptions to executable Test Runner Nodes. */\nexport const createAgentTestRunnerNodes = <TContext>(\n definitions: readonly AgentTestRunnerNodeDefinition[],\n getAgent: (\n ctx: NodeExecutionContext<unknown, TContext>,\n ) => Awaitable<unknown>,\n): readonly NodeDefinition<any, any, TContext>[] =>\n definitions.map((definition) =>\n defineNode({\n name: definition.name,\n ...(definition.title === undefined ? {} : { title: definition.title }),\n ...(definition.description === undefined\n ? {}\n : { description: definition.description }),\n ...(definition.stringInputKey === undefined\n ? {}\n : { stringInputKey: definition.stringInputKey }),\n inputSchema: definition.inputSchema,\n async execute(ctx) {\n const agent = await getAgent(ctx);\n return definition.execute(agent, ctx.input, {\n signal: ctx.signal,\n });\n },\n }),\n );\n\nexport function createMidsceneNodes<TContext>(\n options: CreateMidsceneNodesOptions<TContext>,\n): readonly NodeDefinition<any, any, TContext>[] {\n if (!options || typeof options !== 'object') {\n throw new NodeDefinitionError(\n 'createMidsceneNodes() options must be an object.',\n );\n }\n if (\n typeof options.agentProvider?.getAgent !== 'function' &&\n typeof options.getAgent !== 'function'\n ) {\n throw new NodeDefinitionError(\n 'createMidsceneNodes() requires getAgent or agentProvider.getAgent.',\n );\n }\n if (\n !options.agentClass ||\n typeof options.agentClass.getTestRunnerNodeDefinitions !== 'function'\n ) {\n throw new NodeDefinitionError(\n 'createMidsceneNodes() requires agentClass.getTestRunnerNodeDefinitions().',\n );\n }\n\n const registeredAgentScopes = new Set<string>();\n const getExecutionId = (ctx: NodeExecutionContext<unknown, TContext>) =>\n ctx.scope === 'case' ? ctx.case.runId : ctx.document.documentRunId;\n const getAgent = async (\n ctx: NodeExecutionContext<unknown, TContext>,\n ): Promise<MidsceneUIAgent> => {\n if (!options.agentProvider) return options.getAgent!(ctx);\n const runId = getExecutionId(ctx);\n if (\n options.agentProvider.releaseAgent &&\n !registeredAgentScopes.has(runId)\n ) {\n registeredAgentScopes.add(runId);\n ctx.onTeardown(async () => {\n try {\n const released = await options.agentProvider!.releaseAgent!(runId);\n return released?.reportPath\n ? { reportPaths: [released.reportPath] }\n : undefined;\n } finally {\n registeredAgentScopes.delete(runId);\n }\n });\n }\n return options.agentProvider.getAgent(runId, ctx);\n };\n\n const agentDefinitions = options.agentClass.getTestRunnerNodeDefinitions();\n\n return [\n ...createAgentTestRunnerNodes(agentDefinitions, getAgent),\n defineNode<typeof waitInputSchema, unknown, TContext>({\n name: 'wait',\n description: 'Wait for a fixed duration while honoring cancellation.',\n stringInputKey: false,\n inputSchema: waitInputSchema,\n async execute(ctx) {\n const multiplier =\n ctx.input.unit === 'min'\n ? 60_000\n : ctx.input.unit === 's'\n ? 1_000\n : 1;\n const durationMs = ctx.input.duration * multiplier;\n await waitFor(durationMs, ctx.signal);\n return { summary: `Waited ${durationMs}ms` };\n },\n }),\n defineNode<typeof agentInputSchema, unknown, TContext>({\n name: 'agent',\n description:\n 'Execute one self-contained natural-language task with an injected Agent executor.',\n stringInputKey: 'prompt',\n inputSchema: agentInputSchema,\n async execute(ctx) {\n if (!options.agentExecutor) {\n throw new NodeExecutionError(\n 'agent',\n new TypeError('createMidsceneNodes() requires an agentExecutor.'),\n );\n }\n const execution =\n ctx.scope === 'case'\n ? { scope: 'case' as const, runId: ctx.case.runId }\n : {\n scope: 'document' as const,\n runId: ctx.document.documentRunId,\n };\n const result = await options.agentExecutor.execute({\n prompt: ctx.input.prompt,\n context: ctx.context,\n signal: ctx.signal,\n execution,\n });\n return result ?? { summary: 'Agent task completed.' };\n },\n }),\n ];\n}\n","import type { AndroidAgent } from '@midscene/android';\nimport {\n androidAgentTestRunnerNodeDefinitions,\n launchInputSchema,\n runAdbShellInputSchema,\n runAdbShellOptionsInputSchema,\n terminateInputSchema,\n} from '@midscene/android/test-runner';\nexport type {\n LaunchNodeInput,\n RunAdbShellNodeInput,\n TerminateNodeInput,\n} from '@midscene/android/test-runner';\nimport type { Awaitable } from '../engine/types';\nimport { NodeDefinitionError } from '../errors';\nimport { createAgentTestRunnerNodes } from '../midscene';\nimport type { NodeDefinition, NodeExecutionContext } from '../node/types';\n\nexport {\n launchInputSchema,\n runAdbShellInputSchema,\n runAdbShellOptionsInputSchema,\n terminateInputSchema,\n};\n\nexport type AndroidRunnerAgent = Pick<\n AndroidAgent,\n 'launch' | 'terminate' | 'runAdbShell' | 'back' | 'home' | 'recentApps'\n>;\n\nexport interface CreateAndroidNodesOptions<TContext> {\n getAgent(\n ctx: NodeExecutionContext<unknown, TContext>,\n ): Awaitable<AndroidRunnerAgent>;\n}\n\nexport function createAndroidNodes<TContext>(\n options: CreateAndroidNodesOptions<TContext>,\n): readonly NodeDefinition<any, any, TContext>[] {\n if (!options || typeof options !== 'object') {\n throw new NodeDefinitionError(\n 'createAndroidNodes() options must be an object.',\n );\n }\n if (typeof options.getAgent !== 'function') {\n throw new NodeDefinitionError('createAndroidNodes() requires getAgent().');\n }\n\n return createAgentTestRunnerNodes(\n androidAgentTestRunnerNodeDefinitions,\n options.getAgent,\n );\n}\n"],"names":["WorkflowError","Error","undefined","message","options","NodeDefinitionError","details","validateOptionalText","value","field","node","validateInputSchema","schema","z","validateDefinition","defineNode","nonBlankPrompt","description","createAgentTestRunnerNodes","definitions","getAgent","definition","ctx","agent","createAndroidNodes","androidAgentTestRunnerNodeDefinitions"],"mappings":";;;;;;;;;;;;;AAQO,MAAMA,sBAAsBC;IAWjC,SAAkC;QAChC,OAAO;YACL,MAAM,IAAI,CAAC,IAAI;YACf,SAAS,IAAI,CAAC,OAAO;YACrB,MAAM,IAAI,CAAC,IAAI;YACf,GAAI,AAAiBC,WAAjB,IA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