diff --git a/docs/changelog.md b/docs/changelog.md index afd9108c..c0ce4c92 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -1,5 +1,6 @@ ## Unreleased +- Add `sema4ai.fixWrongAgentImport` command - Show Output button when there are errors while running action or agent package commands - Show datasource configuration status in the tree - Add Data Sources to the Packages tree diff --git a/sema4ai/codegen/commands.py b/sema4ai/codegen/commands.py index fab3477f..b948efaa 100644 --- a/sema4ai/codegen/commands.py +++ b/sema4ai/codegen/commands.py @@ -1056,6 +1056,12 @@ def __init__( add_to_package_json=True, icon="$(diff-added)", ), + Command( + "sema4ai.fixWrongAgentImport", + "Fix wrong agent import", + server_handled=False, + hide_from_command_palette=False, + ), ] diff --git a/sema4ai/package.json b/sema4ai/package.json index 8d4bf499..8e73895c 100644 --- a/sema4ai/package.json +++ b/sema4ai/package.json @@ -179,6 +179,7 @@ "onCommand:sema4ai.openDataSourceDefinition", "onCommand:sema4ai.dropAllDataSources", "onCommand:sema4ai.setupAllDataSources", + "onCommand:sema4ai.fixWrongAgentImport", "onDebugInitialConfigurations", "onDebugResolve:sema4ai", "onView:sema4ai-task-packages-tree", @@ -1041,6 +1042,11 @@ "title": "Setup All Data Sources", "category": "Sema4.ai", "icon": "$(diff-added)" + }, + { + "command": "sema4ai.fixWrongAgentImport", + "title": "Fix wrong agent import", + "category": "Sema4.ai" } ], "menus": { diff --git a/sema4ai/src/sema4ai_code/agents/agent_spec_handler.py b/sema4ai/src/sema4ai_code/agents/agent_spec_handler.py index cfd763d2..9d53d445 100644 --- a/sema4ai/src/sema4ai_code/agents/agent_spec_handler.py +++ b/sema4ai/src/sema4ai_code/agents/agent_spec_handler.py @@ -50,6 +50,7 @@ class _YamlNodeKind(Enum): class ErrorCode(Enum): action_package_info_unsynchronized = "action_package_info_unsynchronized" agent_package_incomplete = "agent_package_incomplete" + zipped_action_inside_unzipped_agent = "zipped_action_inside_unzipped_agent" @dataclass @@ -742,6 +743,7 @@ def _verify_yaml_matches_spec( "maybe it was just unzipped instead of using the `Import Agent Package` to import the agent into VSCode?", node=yaml_node.data.node, severity=Severity.critical, + code=ErrorCode.zipped_action_inside_unzipped_agent, ) elif spec_node.data.expected_type.expected_type == _ExpectedTypeEnum.file: diff --git a/sema4ai/src/sema4ai_code/agents/list_actions_from_agent.py b/sema4ai/src/sema4ai_code/agents/list_actions_from_agent.py index 3b700e4e..b255b3ea 100644 --- a/sema4ai/src/sema4ai_code/agents/list_actions_from_agent.py +++ b/sema4ai/src/sema4ai_code/agents/list_actions_from_agent.py @@ -120,6 +120,10 @@ def list_actions_from_agent( ) for zip_path in actions_dir.rglob("*.zip"): + # Skip zips if there is a package.yaml in the same directory. + if (zip_path.parent / "package.yaml").exists(): + continue + zip_path = zip_path.absolute() package_yaml_contents = get_package_yaml_from_zip(zip_path) relative_path = zip_path.relative_to(actions_dir).as_posix() diff --git a/sema4ai/src/sema4ai_code/commands.py b/sema4ai/src/sema4ai_code/commands.py index ee0c6a1e..d735a1b4 100644 --- a/sema4ai/src/sema4ai_code/commands.py +++ b/sema4ai/src/sema4ai_code/commands.py @@ -152,6 +152,7 @@ SEMA4AI_OPEN_DATA_SOURCE_DEFINITION = "sema4ai.openDataSourceDefinition" # Open Data Source definition SEMA4AI_DROP_ALL_DATA_SOURCES = "sema4ai.dropAllDataSources" # Remove All Data Sources SEMA4AI_SETUP_ALL_DATA_SOURCES = "sema4ai.setupAllDataSources" # Setup All Data Sources +SEMA4AI_FIX_WRONG_AGENT_IMPORT = "sema4ai.fixWrongAgentImport" # Fix wrong agent import ALL_SERVER_COMMANDS = [ SEMA4AI_GET_PLUGINS_DIR, diff --git a/sema4ai/src/sema4ai_code/robocorp_language_server.py b/sema4ai/src/sema4ai_code/robocorp_language_server.py index 445886ba..e7651a77 100644 --- a/sema4ai/src/sema4ai_code/robocorp_language_server.py +++ b/sema4ai/src/sema4ai_code/robocorp_language_server.py @@ -453,10 +453,30 @@ def m_text_document__code_action(self, **kwargs) -> list[CodeActionTypedDict]: ] ] + manually_unpacked_agent = [ + d + for d in diagnostics + if d.get("code") == ErrorCode.zipped_action_inside_unzipped_agent.value + ] + document_dir = Path( sema4ai_ls_core.uris.to_fs_path(params["textDocument"]["uri"]) ) + if manually_unpacked_agent: + code_action_list.append( + { + "title": "Fix wrong agent import", + "kind": "quickfix", + "diagnostics": manually_unpacked_agent, + "command": { + "title": "Fix wrong agent import", + "command": commands.SEMA4AI_FIX_WRONG_AGENT_IMPORT, + "arguments": [str(document_dir.parent)], + }, + } + ) + if incomplete_package_diags: code_action_list.append( { @@ -2241,6 +2261,57 @@ def _refresh_agent_spec(self, params: AgentSpecPathDict) -> ActionResultDict: return ActionResult(success=True, message=None).as_dict() + def _fix_wrong_agent_import(self, agent_dir, monitor: IMonitor) -> ActionResultDict: + import shutil + import zipfile + + agent_root_dir = Path(agent_dir) + actions_dir: Path = (agent_root_dir / "actions").absolute() + had_zips = False + + try: + for zip_path in actions_dir.rglob("*.zip"): + # Check if a package.yaml exists in the same directory as the zip file then skip + if (zip_path.parent / "package.yaml").exists(): + continue + + had_zips = True + zip_folder_name = zip_path.name.replace(".zip", "") + temp_extract_path = zip_path.parent / zip_folder_name + + with zipfile.ZipFile(zip_path, "r") as zip_ref: + zip_ref.extractall(temp_extract_path) + + # Move files and directories from the versioned folder to the root action directory + for item in temp_extract_path.rglob("*"): + if ( + item.is_file() + and item.name != "__action_server_metadata__.json" + ): + relative_path = item.relative_to(temp_extract_path) + final_path = zip_path.parent / relative_path + + final_path.parent.mkdir(parents=True, exist_ok=True) + + shutil.move(str(item), str(final_path)) + + shutil.rmtree(temp_extract_path) + zip_path.unlink() + + if had_zips: + metadata_file = agent_root_dir / "__agent_package_metadata__.json" + if metadata_file.exists(): + metadata_file.unlink() + except Exception as e: + return ActionResult( + success=False, message=f"Failed to unzip action zips: {e}" + ).as_dict() + + return ActionResult(success=True, message=None).as_dict() + + def m_fix_wrong_agent_import(self, agent_dir) -> ActionResultDict: + return require_monitor(partial(self._fix_wrong_agent_import, agent_dir)) + def _pack_agent_package_threaded(self, directory, ws, monitor: IMonitor): from sema4ai_ls_core.progress_report import progress_context diff --git a/sema4ai/tests/sema4ai_code_tests/_resources/agent-package/actions/MyActions/action-one/.gitignore b/sema4ai/tests/sema4ai_code_tests/_resources/agent-package/actions/MyActions/action-one/.gitignore new file mode 100644 index 00000000..1688dca1 --- /dev/null +++ b/sema4ai/tests/sema4ai_code_tests/_resources/agent-package/actions/MyActions/action-one/.gitignore @@ -0,0 +1,13 @@ +*.pyc +*.zip +.DS_Store +.env +.project +.pydevproject +.use +.venv/ +.vscode +metadata.json +output/ +temp/ +venv/ diff --git a/sema4ai/tests/sema4ai_code_tests/_resources/agent-package/actions/MyActions/action-one/LICENSE b/sema4ai/tests/sema4ai_code_tests/_resources/agent-package/actions/MyActions/action-one/LICENSE new file mode 100644 index 00000000..1fb76e9b --- /dev/null +++ b/sema4ai/tests/sema4ai_code_tests/_resources/agent-package/actions/MyActions/action-one/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2024 Sema4.ai, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/sema4ai/tests/sema4ai_code_tests/_resources/agent-package/actions/MyActions/action-one/README.md b/sema4ai/tests/sema4ai_code_tests/_resources/agent-package/actions/MyActions/action-one/README.md new file mode 100644 index 00000000..94f8e714 --- /dev/null +++ b/sema4ai/tests/sema4ai_code_tests/_resources/agent-package/actions/MyActions/action-one/README.md @@ -0,0 +1,9 @@ +# Template: Basic + +The template is a simple example to show how to get started with some basic configuration in place. + +The action enables you to get the Wikipedia article summary. + +🚀 You can leverage the whole Python ecosystem when creating actions. Sema4.ai provides a [bunch of libraries](https://pypi.org/search/?q=robocorp-); you can make your own. The sky is the limit. + +👉 Check [Action Server](https://github.com/Sema4AI/actions/tree/master/action_server/docs) and [Actions](https://github.com/Sema4AI/actions/tree/master/actions/docs) docs for more information. \ No newline at end of file diff --git a/sema4ai/tests/sema4ai_code_tests/_resources/agent-package/actions/MyActions/action-one/actions.py b/sema4ai/tests/sema4ai_code_tests/_resources/agent-package/actions/MyActions/action-one/actions.py new file mode 100644 index 00000000..757a5dd5 --- /dev/null +++ b/sema4ai/tests/sema4ai_code_tests/_resources/agent-package/actions/MyActions/action-one/actions.py @@ -0,0 +1,41 @@ +""" +A simple AI Action template for retrieving Wikipedia article summary + +Please check out the base guidance on AI Actions in our main repository readme: +https://github.com/sema4ai/actions/blob/master/README.md + +""" + +import os +from sema4ai.actions import action +from robocorp import browser + +HEADLESS_BROWSER = not os.getenv("HEADLESS_BROWSER") + + +@action +def get_wikipedia_article_summary(article_url: str) -> str: + """ + Retrieves the summary (first paragraph) of given Wikipedia article. + + Args: + article_url: URL of the article to get the summary of. + + Returns: + Summary of the article. + """ + + browser.configure(browser_engine="chromium", headless=HEADLESS_BROWSER) + + page = browser.goto(article_url) + + page.wait_for_load_state("domcontentloaded") + page.wait_for_load_state("networkidle") + + paragraphs = page.query_selector_all(".mw-content-ltr>p:not(.mw-empty-elt)") + summary = paragraphs[0].inner_text() + + # Pretty print for log + print(summary) + + return summary diff --git a/sema4ai/tests/sema4ai_code_tests/_resources/agent-package/actions/MyActions/action-one/devdata/input_get_wikipedia_article_summary.json b/sema4ai/tests/sema4ai_code_tests/_resources/agent-package/actions/MyActions/action-one/devdata/input_get_wikipedia_article_summary.json new file mode 100644 index 00000000..ee2cf666 --- /dev/null +++ b/sema4ai/tests/sema4ai_code_tests/_resources/agent-package/actions/MyActions/action-one/devdata/input_get_wikipedia_article_summary.json @@ -0,0 +1,19 @@ +{ + "inputs": [ + { + "inputName": "Summarize Wikipedia Intelligence", + "inputValue": { + "article_url": "https://en.wikipedia.org/wiki/Intelligence" + } + } + ], + "metadata": { + "actionName": "get_wikipedia_article_summary", + "actionRelativePath": "actions.py", + "schemaDescription": [ + "article_url: string: URL of the article to get the summary of." + ], + "managedParamsSchemaDescription": {}, + "inputFileVersion": "v2" + } +} diff --git a/sema4ai/tests/sema4ai_code_tests/_resources/agent-package/actions/MyActions/action-one/package.png b/sema4ai/tests/sema4ai_code_tests/_resources/agent-package/actions/MyActions/action-one/package.png new file mode 100644 index 00000000..032dfbc9 Binary files /dev/null and b/sema4ai/tests/sema4ai_code_tests/_resources/agent-package/actions/MyActions/action-one/package.png differ diff --git a/sema4ai/tests/sema4ai_code_tests/_resources/agent-package/actions/MyActions/action-one/package.yaml b/sema4ai/tests/sema4ai_code_tests/_resources/agent-package/actions/MyActions/action-one/package.yaml new file mode 100644 index 00000000..cea9ec8a --- /dev/null +++ b/sema4ai/tests/sema4ai_code_tests/_resources/agent-package/actions/MyActions/action-one/package.yaml @@ -0,0 +1,30 @@ +# Required: A short name for the action package +name: Action One + +# Required: A description of what's in the action package. +description: Action package description + +# Package version number, recommend using semver.org +version: 0.0.1 + +dependencies: + conda-forge: + - python=3.10.14 + - uv=0.4.17 + pypi: + - sema4ai-actions=1.0.1 + - robocorp-browser=2.3.3 + +packaging: + # By default, all files and folders in this directory are packaged when uploaded. + # Add exclusion rules below (expects glob format: https://docs.python.org/3/library/glob.html) + exclude: + - ./.git/** + - ./.vscode/** + - ./devdata/** + - ./output/** + - ./venv/** + - ./.venv/** + - ./.DS_store/** + - ./**/*.pyc + - ./**/*.zip diff --git a/sema4ai/tests/sema4ai_code_tests/_resources/agent-package/agent-spec.yaml b/sema4ai/tests/sema4ai_code_tests/_resources/agent-package/agent-spec.yaml new file mode 100644 index 00000000..ded83779 --- /dev/null +++ b/sema4ai/tests/sema4ai_code_tests/_resources/agent-package/agent-spec.yaml @@ -0,0 +1,22 @@ +agent-package: + spec-version: v2 + agents: + - name: Test Agent + description: New Agent Description + model: + provider: OpenAI + name: gpt-4o + version: 0.0.1 + architecture: agent + reasoning: disabled + runbook: runbook.md + action-packages: + - name: Action One + organization: MyActions + version: 0.0.1 + path: MyActions/action-one + type: folder + whitelist: '' + knowledge: [] + metadata: + mode: conversational diff --git a/sema4ai/tests/sema4ai_code_tests/_resources/agent-package/runbook.md b/sema4ai/tests/sema4ai_code_tests/_resources/agent-package/runbook.md new file mode 100644 index 00000000..ac39ad92 --- /dev/null +++ b/sema4ai/tests/sema4ai_code_tests/_resources/agent-package/runbook.md @@ -0,0 +1 @@ +You are a helpful assistant. \ No newline at end of file diff --git a/sema4ai/tests/sema4ai_code_tests/agents/test_agent_spec_analysis/test_agent_spec_analysis_v2_agent3_ok_.yml b/sema4ai/tests/sema4ai_code_tests/agents/test_agent_spec_analysis/test_agent_spec_analysis_v2_agent3_ok_.yml index 43703341..77f4cddd 100644 --- a/sema4ai/tests/sema4ai_code_tests/agents/test_agent_spec_analysis/test_agent_spec_analysis_v2_agent3_ok_.yml +++ b/sema4ai/tests/sema4ai_code_tests/agents/test_agent_spec_analysis/test_agent_spec_analysis_v2_agent3_ok_.yml @@ -1,4 +1,5 @@ -- message: The 'zip' mode is only supported inside a .zip distribution. When unzipped, +- code: zipped_action_inside_unzipped_agent + message: The 'zip' mode is only supported inside a .zip distribution. When unzipped, action packages must NOT be zipped! -- maybe it was just unzipped instead of using the `Import Agent Package` to import the agent into VSCode? range: diff --git a/sema4ai/tests/sema4ai_code_tests/agents/test_agent_spec_analysis/test_agent_spec_analysis_v2_agent3_v2_bad_action_package_name_.yml b/sema4ai/tests/sema4ai_code_tests/agents/test_agent_spec_analysis/test_agent_spec_analysis_v2_agent3_v2_bad_action_package_name_.yml index 2b51e8b3..0978da97 100644 --- a/sema4ai/tests/sema4ai_code_tests/agents/test_agent_spec_analysis/test_agent_spec_analysis_v2_agent3_v2_bad_action_package_name_.yml +++ b/sema4ai/tests/sema4ai_code_tests/agents/test_agent_spec_analysis/test_agent_spec_analysis_v2_agent3_v2_bad_action_package_name_.yml @@ -11,7 +11,8 @@ line: 15 severity: 1 source: sema4ai -- message: The 'zip' mode is only supported inside a .zip distribution. When unzipped, +- code: zipped_action_inside_unzipped_agent + message: The 'zip' mode is only supported inside a .zip distribution. When unzipped, action packages must NOT be zipped! -- maybe it was just unzipped instead of using the `Import Agent Package` to import the agent into VSCode? range: diff --git a/sema4ai/tests/sema4ai_code_tests/agents/test_agent_spec_analysis/test_agent_spec_analysis_v2_agent3_v2_bad_type_.yml b/sema4ai/tests/sema4ai_code_tests/agents/test_agent_spec_analysis/test_agent_spec_analysis_v2_agent3_v2_bad_type_.yml index 2147292f..3b07eeab 100644 --- a/sema4ai/tests/sema4ai_code_tests/agents/test_agent_spec_analysis/test_agent_spec_analysis_v2_agent3_v2_bad_type_.yml +++ b/sema4ai/tests/sema4ai_code_tests/agents/test_agent_spec_analysis/test_agent_spec_analysis_v2_agent3_v2_bad_type_.yml @@ -10,7 +10,8 @@ line: 17 severity: 1 source: sema4ai -- message: The 'zip' mode is only supported inside a .zip distribution. When unzipped, +- code: zipped_action_inside_unzipped_agent + message: The 'zip' mode is only supported inside a .zip distribution. When unzipped, action packages must NOT be zipped! -- maybe it was just unzipped instead of using the `Import Agent Package` to import the agent into VSCode? range: diff --git a/sema4ai/tests/sema4ai_code_tests/data_server_fixtures.py b/sema4ai/tests/sema4ai_code_tests/data_server_fixtures.py index b5fcb804..263771f3 100644 --- a/sema4ai/tests/sema4ai_code_tests/data_server_fixtures.py +++ b/sema4ai/tests/sema4ai_code_tests/data_server_fixtures.py @@ -277,5 +277,4 @@ def create_another_sqlite_sample_db(tmpdir) -> Path: # Commit changes and close the connection conn.commit() conn.close() - return db_path diff --git a/sema4ai/tests/sema4ai_code_tests/test_vscode_integration.py b/sema4ai/tests/sema4ai_code_tests/test_vscode_integration.py index edb0e40b..74219878 100644 --- a/sema4ai/tests/sema4ai_code_tests/test_vscode_integration.py +++ b/sema4ai/tests/sema4ai_code_tests/test_vscode_integration.py @@ -8,8 +8,6 @@ from unittest import mock import pytest -from sema4ai_code_tests.fixtures import RCC_TEMPLATE_NAMES, RccPatch -from sema4ai_code_tests.protocols import IRobocorpLanguageServerClient from sema4ai_ls_core import uris from sema4ai_ls_core.basic import wait_for_condition from sema4ai_ls_core.callbacks import Callback @@ -33,6 +31,8 @@ LocalPackageMetadataInfoDict, WorkspaceInfoDict, ) +from sema4ai_code_tests.fixtures import RCC_TEMPLATE_NAMES, RccPatch +from sema4ai_code_tests.protocols import IRobocorpLanguageServerClient log = logging.getLogger(__name__) @@ -1082,10 +1082,11 @@ def test_hover_image_integration( ): import base64 - from sema4ai_code_tests.fixtures import IMAGE_IN_BASE64 from sema4ai_ls_core import uris from sema4ai_ls_core.workspace import Document + from sema4ai_code_tests.fixtures import IMAGE_IN_BASE64 + locators_json = tmpdir.join("locators.json") locators_json.write_text("", "utf-8") @@ -1681,10 +1682,11 @@ def test_web_inspector_integrated( This test should be a reference spanning all the APIs that are available for the inspector webview to use. """ + from sema4ai_ls_core import uris + from sema4ai_code_tests.robocode_language_server_client import ( RobocorpLanguageServerClient, ) - from sema4ai_ls_core import uris cases.copy_to("robots", ws_root_path) ls_client: RobocorpLanguageServerClient = language_server_initialized @@ -3045,3 +3047,52 @@ def test_get_external_api_url( # Cleanup: Remove the PID file after the test if pid_file_content: os.remove(str(pid_file_path)) + + +def test_fix_wrong_agent_import( + language_server_initialized, cases: CasesFixture, tmpdir, ws_root_path +) -> None: + language_server = language_server_initialized + + cases.copy_to("agent-package", ws_root_path) + + from sema4ai_code import commands + + language_server.execute_command( + commands.SEMA4AI_PACK_AGENT_PACKAGE_INTERNAL, + [ + { + "directory": ws_root_path, + } + ], + ) + + agent_package_zip = f"{ws_root_path}/agent-package.zip" + + import zipfile + + temp_dir = Path(ws_root_path) / "temp" + with zipfile.ZipFile(agent_package_zip, "r") as zip_ref: + zip_ref.extractall(temp_dir) + + action_zip = Path(f"{temp_dir}/actions/MyActions/action-one/0.0.1.zip") + assert action_zip.exists() + + result = language_server.request( + { + "jsonrpc": "2.0", + "id": language_server.next_id(), + "method": "fixWrongAgentImport", + "params": { + "agent_dir": str(temp_dir), + }, + } + )["result"] + + assert result["success"] + assert not action_zip.exists() + assert (action_zip.parent / "package.yaml").exists() + assert not (temp_dir / "__agent_package_metadata__.json").exists() + assert not ( + temp_dir / "actions/MyActions/action-one/__action_server_metadata__.json" + ).exists() diff --git a/sema4ai/vscode-client/src/extension.ts b/sema4ai/vscode-client/src/extension.ts index ae4d75dd..9ef9811b 100644 --- a/sema4ai/vscode-client/src/extension.ts +++ b/sema4ai/vscode-client/src/extension.ts @@ -168,6 +168,7 @@ import { SEMA4AI_OPEN_DATA_SOURCE_DEFINITION, SEMA4AI_DROP_ALL_DATA_SOURCES, SEMA4AI_SETUP_ALL_DATA_SOURCES, + SEMA4AI_FIX_WRONG_AGENT_IMPORT, } from "./robocorpCommands"; import { installWorkspaceWatcher } from "./pythonExtIntegration"; import { refreshCloudTreeView } from "./viewsRobocorp"; @@ -203,6 +204,7 @@ import { importAgentPackage, updateAgentVersion, refreshAgentSpec, + fixWrongAgentImport, } from "./robo/agentPackage"; import { getSema4AIStudioURLForAgentZipPath, getSema4AIStudioURLForFolderPath } from "./deepLink"; import { DatasourceInfo, LocalPackageMetadataInfo } from "./protocols"; @@ -534,6 +536,7 @@ function registerRobocorpCodeCommands(C: CommandRegistry, context: ExtensionCont openDataSourceDefinition(datasource) ); C.register(SEMA4AI_SETUP_ALL_DATA_SOURCES, async (datasource?: RobotEntry) => setupAllDataSources(datasource)); + C.register(SEMA4AI_FIX_WRONG_AGENT_IMPORT, async (agentPath: string) => fixWrongAgentImport(agentPath)); } async function clearEnvAndRestart() { diff --git a/sema4ai/vscode-client/src/robo/agentPackage.ts b/sema4ai/vscode-client/src/robo/agentPackage.ts index 9e7aa5aa..6ef41125 100644 --- a/sema4ai/vscode-client/src/robo/agentPackage.ts +++ b/sema4ai/vscode-client/src/robo/agentPackage.ts @@ -282,3 +282,25 @@ export const refreshAgentSpec = async (agentPath: string): Promise => { showErrorMessageWithShowOutputButton(errorMsg); } }; + +export const fixWrongAgentImport = async (agentPath: string): Promise => { + getAgentCliLocation(); + + if (!agentPath) { + agentPath = await selectAgentPackage(); + if (!agentPath) { + return; + } + } + + const result = await langServer.sendRequest("fixWrongAgentImport", { + agent_dir: agentPath, + }); + + if (!result["success"]) { + window.showErrorMessage(result["message"] || `Unknown error while fixing the agent at: ${agentPath}`); + return; + } + + await refreshAgentSpec(agentPath); +}; diff --git a/sema4ai/vscode-client/src/robocorpCommands.ts b/sema4ai/vscode-client/src/robocorpCommands.ts index 7775ea0d..d0bc050f 100644 --- a/sema4ai/vscode-client/src/robocorpCommands.ts +++ b/sema4ai/vscode-client/src/robocorpCommands.ts @@ -150,4 +150,5 @@ export const SEMA4AI_DROP_DATA_SOURCE = "sema4ai.dropDataSource"; // Remove Dat export const SEMA4AI_SETUP_DATA_SOURCE = "sema4ai.setupDataSource"; // Setup Data Source export const SEMA4AI_OPEN_DATA_SOURCE_DEFINITION = "sema4ai.openDataSourceDefinition"; // Open Data Source definition export const SEMA4AI_DROP_ALL_DATA_SOURCES = "sema4ai.dropAllDataSources"; // Remove All Data Sources -export const SEMA4AI_SETUP_ALL_DATA_SOURCES = "sema4ai.setupAllDataSources"; // Setup All Data Sources \ No newline at end of file +export const SEMA4AI_SETUP_ALL_DATA_SOURCES = "sema4ai.setupAllDataSources"; // Setup All Data Sources +export const SEMA4AI_FIX_WRONG_AGENT_IMPORT = "sema4ai.fixWrongAgentImport"; // Fix wrong agent import \ No newline at end of file