### Installation Directory Setup Source: https://github.com/aaswordman/operit/blob/main/app/src/main/assets/templates/flutter/windows/CMakeLists.txt Configures installation directories, ensuring support files are placed next to the executable for in-place running, compatible with Visual Studio builds. ```cmake set(BUILD_BUNDLE_DIR "$") set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") ``` -------------------------------- ### Sync Example Packages Source: https://github.com/aaswordman/operit/blob/main/tools/JS_ADB_README.md This command synchronizes specified example packages into the application's assets and the connected device. It's crucial for validating package loading, hot reloading, and installation of tool packages. ```cmd d:\Code\prog\assistance\.venv\Scripts\python.exe d:\Code\prog\assistance\sync_example_packages.py --include operit_editor --include sidebar_bing_action ``` ```cmd d:\Code\prog\assistance\.venv\Scripts\python.exe d:\Code\prog\assistance\sync_example_packages.py --include sidebar_bing_action ``` -------------------------------- ### Example Command Line Execution Source: https://github.com/aaswordman/operit/blob/main/examples/README.md An example demonstrating how to execute the 'calculate' function from 'demo_script.js' using a parameter file on Windows. ```bash .\tools\execute_js.bat examples\demo_script.js calculate @params.json ``` -------------------------------- ### Install Application Target Source: https://github.com/aaswordman/operit/blob/main/app/src/main/assets/templates/flutter/windows/CMakeLists.txt Installs the main application executable to the runtime destination. ```cmake install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) ``` -------------------------------- ### Complete ToolPkg Manifest Example Source: https://github.com/aaswordman/operit/blob/main/docs/TOOLPKG_FORMAT_GUIDE.md This is a comprehensive example of a manifest.json file, illustrating all major fields including metadata, subpackages, resources, and templates. ```json { "schema_version": 1, "toolpkg_id": "com.operit.windows_bundle", "version": "0.2.0", "author": ["Operit Team", "Alice"], "main": "main.js", "display_name": { "zh": "Windows 工具包", "en": "Windows Bundle" }, "description": { "zh": "Windows 一键配置与控制工具包", "en": "Windows one-click setup and control bundle" }, "subpackages": [ { "id": "windows_control", "entry": "packages/windows_control.js", "enabled_by_default": false, "display_name": { "zh": "Windows 控制", "en": "Windows Control" }, "description": { "zh": "通过 Operit PC Agent 控制 Windows", "en": "Control Windows via Operit PC Agent" } } ], "resources": [ { "key": "pc_agent_zip", "path": "resources/pc_agent/operit-pc-agent.zip", "mime": "application/zip" } ], "workflow_templates": [ { "id": "quick_chat_workflow", "display_name": { "zh": "快速对话工作流", "en": "Quick Chat Workflow" }, "description": { "zh": "手动触发后自动启动聊天并发送一条引导消息。", "en": "Starts a chat and sends a guidance message after a manual trigger." }, "resource_key": "demo_workflow_template" } ], "workspace_templates": [ { "id": "quick_start_workspace", "display_name": { "zh": "快速开始工作区", "en": "Quick Start Workspace" }, "description": { "zh": "包含 .operit/config.json 的最小工作区模板。", "en": "A minimal workspace template containing .operit/config.json." }, "resource_key": "demo_workspace_template", "project_type": "template_try" } ] } ``` -------------------------------- ### Install Application Bundle Source: https://github.com/aaswordman/operit/blob/main/app/src/main/assets/templates/flutter/linux/CMakeLists.txt Configures the installation process to create a relocatable bundle in the build directory, including the executable, data, libraries, and assets. ```cmake # === Installation === # By default, "installing" just makes a relocatable bundle in the build # directory. set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() # Start with a clean build bundle directory every time. install(CODE " file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") " COMPONENT Runtime) set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) install(FILES "${bundled_library}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endforeach(bundled_library) # Copy the native assets provided by the build.dart from all packages. set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") install(DIRECTORY "${NATIVE_ASSETS_DIR}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) # Fully re-copy the assets directory on each build to avoid having stale files # from a previous install. set(FLUTTER_ASSET_DIR_NAME "flutter_assets") install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) # Install the AOT library on non-Debug builds only. if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() ``` -------------------------------- ### Sync Example Packages with Python Script Source: https://github.com/aaswordman/operit/blob/main/tools/JS_ADB_README.md The `sync_example_packages.py` script is used for managing example packages. It handles pre-building TypeScript, packing directories into `.toolpkg`, syncing outputs to device assets, and optionally hot-reloading. ```python d:\Code\prog\assistance\.venv\Scripts\python.exe d:\Code\prog\assistance\sync_example_packages.py --include sidebar_bing_action ``` ```python d:\Code\prog\assistance\.venv\Scripts\python.exe d:\Code\prog\assistance\sync_example_packages.py --mode test ``` ```python d:\Code\prog\assistance\.venv\Scripts\python.exe d:\Code\prog\assistance\sync_example_packages.py --include sidebar_bing_action --no-hot-reload ``` -------------------------------- ### Example of Executing a Script with Arguments Source: https://github.com/aaswordman/operit/blob/main/docs/SCRIPT_DEV_GUIDE.md An example demonstrating how to call the `hello_world` function in `my_new_script.js` with a JSON argument, specifically for Windows command prompt where quotes need escaping. ```cmd tools\execute_js.bat examples\my_new_script.js hello_world "{\"name\":\"世界\"}" ``` -------------------------------- ### Install Bundled Plugin Libraries Source: https://github.com/aaswordman/operit/blob/main/app/src/main/assets/templates/flutter/windows/CMakeLists.txt Installs any bundled libraries provided by plugins to the installation directory. ```cmake if(PLUGIN_BUNDLED_LIBRARIES) install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() ``` -------------------------------- ### ADB Example: Create New Chat, Group, Send Message, Show Floating Window Source: https://github.com/aaswordman/operit/blob/main/docs/external_intent_chat.md Example ADB command to demonstrate sending a message with options to create a new chat, assign it to a group, display the floating window, and return tool status. ```APIDOC ## ADB Example: New Chat, Group, Floating Window ### Command ```bash adb shell am broadcast \ -a com.ai.assistance.operit.EXTERNAL_CHAT \ --es request_id "req-001" \ --es message "你好,帮我总结一下这段话" \ --es group "workflow" \ --ez create_new_chat true \ --ez show_floating true \ --ez return_tool_status false \ --es initial_mode "WINDOW" \ --el auto_exit_after_ms 10000 ``` ``` -------------------------------- ### Install Native Assets Source: https://github.com/aaswordman/operit/blob/main/app/src/main/assets/templates/flutter/windows/CMakeLists.txt Installs native assets provided by build.dart from all packages to the installation directory. ```cmake set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") install(DIRECTORY "${NATIVE_ASSETS_DIR}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) ``` -------------------------------- ### 安装独立项目依赖 Source: https://github.com/aaswordman/operit/blob/main/docs/SCRIPT_DEV_GUIDE.md 在项目根目录下运行 `npm install` 命令来安装 `package.json` 中定义的开发依赖,如 TypeScript。 ```bash npm install ``` -------------------------------- ### Example of chat-info Metadata Source: https://github.com/aaswordman/operit/blob/main/docs/chat_import_markdown.md This example shows how to specify the chat title and group using the `chat-info` comment. ```markdown ``` -------------------------------- ### Gradle Version Catalog Example Source: https://github.com/aaswordman/operit/blob/main/app/src/main/assets/templates/android/README.md Defines versions and libraries for dependency management using Gradle Version Catalog. ```toml [versions] agp = "9.0.0" kotlin = "2.3.10" composeBom = "2026.01.01" [libraries] androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" } androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" } ``` -------------------------------- ### Execute JS Example: Say Hello (Cross-platform) Source: https://github.com/aaswordman/operit/blob/main/tools/JS_ADB_README.md Demonstrates executing a 'sayHello' function in a JavaScript file across Linux/macOS, Windows, and Python environments with appropriate parameter formats. ```bash # Linux/macOS ./execute_js.sh test_script.js sayHello '{"name":"John"}' ``` ```batch # Windows execute_js.bat test_script.js sayHello @params.json ``` ```python # Python (any platform) python execute_js.py test_script.js sayHello --params '{"name":"John"}' ``` -------------------------------- ### Automated ToolPkg Creation with Python Script Source: https://github.com/aaswordman/operit/blob/main/docs/TOOLPKG_FORMAT_GUIDE.md Demonstrates how to use the sync_example_packages.py script to automatically package ToolPkg examples. Various options like including specific packages, dry runs, and deleting extra packages are shown. ```bash # 打包所有白名单中的包 python sync_example_packages.py # 以“非白名单附加”的方式打包特定包 python sync_example_packages.py --include windows_control # 例如只额外同步 template_try 这个示例 python sync_example_packages.py --include template_try # 查看打包结果(不实际写入) python sync_example_packages.py --dry-run # 删除不在白名单中的包 python sync_example_packages.py --delete-extra ``` -------------------------------- ### Subpackage Definition Example Source: https://github.com/aaswordman/operit/blob/main/docs/TOOLPKG_FORMAT_GUIDE.md An example of a subpackage object within the manifest, defining its ID, entry point, and display properties. ```json { "id": "windows_control", "entry": "packages/windows_control.js", "enabled_by_default": false, "display_name": { "zh": "Windows 控制", "en": "Windows Control" }, "description": { "zh": "通过 Operit PC Agent 控制 Windows", "en": "Control Windows via Operit PC Agent" } } ``` -------------------------------- ### Build Project Commands (Windows) Source: https://github.com/aaswordman/operit/blob/main/app/src/main/assets/templates/android/README.md Common Gradle commands for building, assembling, and installing the Android project on Windows. ```bash # Windows gradlew.bat build gradlew.bat assembleDebug gradlew.bat installDebug ``` -------------------------------- ### Start Shower Server and Ensure Display Source: https://github.com/aaswordman/operit/blob/main/showerclient/README.md Initiate the Shower server and create or update the virtual display with specified dimensions and DPI. This is a prerequisite for sending input events or rendering video. ```kotlin // 1) Ensure server is started and Binder is received val ok = ShowerServerManager.ensureServerStarted(context) if (!ok) return // 2) Create / Update virtual display val displayOk = ShowerController.ensureDisplay( context = context, width = 1080, height = 2400, dpi = 480, bitrateKbps = 8000, ) if (!displayOk) return ``` -------------------------------- ### Install ICU Data and Flutter Library Source: https://github.com/aaswordman/operit/blob/main/app/src/main/assets/templates/flutter/windows/CMakeLists.txt Installs the ICU data file and the Flutter library to the data directory and root installation directory, respectively. ```cmake install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Install Flutter Assets Source: https://github.com/aaswordman/operit/blob/main/app/src/main/assets/templates/flutter/windows/CMakeLists.txt Installs the Flutter assets directory, ensuring it's re-copied on each build to prevent stale files. ```cmake set(FLUTTER_ASSET_DIR_NAME "flutter_assets") install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Execute JS Example: Calculation (Cross-platform) Source: https://github.com/aaswordman/operit/blob/main/tools/JS_ADB_README.md Demonstrates executing a 'calculate' function in a JavaScript file across Linux/macOS, Windows, and Python environments with complex JSON parameters. ```bash # Linux/macOS ./execute_js.sh test_script.js calculate '{"num1":10,"num2":5,"operation":"multiply"}' ``` ```batch # Windows execute_js.bat test_script.js calculate @params.json ``` ```python # Python (any platform) python execute_js.py test_script.js calculate --params '{"num1":10,"num2":5,"operation":"multiply"}' ``` -------------------------------- ### Build Project Commands (Linux/Mac) Source: https://github.com/aaswordman/operit/blob/main/app/src/main/assets/templates/android/README.md Common Gradle commands for building, assembling, and installing the Android project on Linux or macOS. ```bash # Linux/Mac ./gradlew build # 构建项目 ./gradlew assembleDebug # 打包Debug APK ./gradlew installDebug # 安装到设备 ./gradlew clean # 清理构建 ``` -------------------------------- ### TypeScript Example Package Source: https://github.com/aaswordman/operit/blob/main/examples/README.md Defines a simple 'hello_world' tool within a TypeScript package. Includes metadata for the package and its tools, and demonstrates asynchronous operations with `Tools.System.sleep`. ```typescript /* METADATA { "name": "typescript_example", "description": "A TypeScript example package", "tools": [ { "name": "hello_world", "description": "A simple hello world tool with TypeScript", "parameters": [ { "name": "name", "description": "Name to greet", "type": "string", "required": true } ] } ], "category": "FILE_READ" } */ /** * Simple hello world function with TypeScript * @param params Tool parameters with name property */ async function hello_world(params: { name: string }): Promise { // Access parameters with type checking const name = params.name || "World"; // Use async/await with proper typing await Tools.System.sleep(1); // Return a result complete(`Hello, ${name}!`); } // Export the function exports.hello_world = hello_world; ``` -------------------------------- ### 编译 TypeScript 脚本 Source: https://github.com/aaswordman/operit/blob/main/docs/SCRIPT_DEV_GUIDE.md 在 examples 目录下使用 `npx tsc` 命令编译所有的 TypeScript 脚本为 JavaScript。 ```bash cd examples npx tsc ``` -------------------------------- ### Promise-Based Async API Example Source: https://github.com/aaswordman/operit/blob/main/examples/README.md Demonstrates chaining multiple asynchronous tool calls using `async/await`. This pattern is useful for sequential operations like reading multiple files. ```javascript async function chain_example(params) { try { // Chain multiple tool calls with await const fileList = await Tools.Files.list("/some/path"); const fileContents = await Tools.Files.read("/some/path/file.txt"); // Do work with the results const result = `Found ${fileList.length} files. First file contents: ${fileContents}`; complete(result); } catch (error) { complete(`Error: ${error.message}`); } } ``` -------------------------------- ### Execute JS Directory with Parameters (Windows) Source: https://github.com/aaswordman/operit/blob/main/tools/JS_ADB_README.md Examples of executing JavaScript directories with different parameter formats, including JSON files and inline JSON strings. ```batch tools\execute_js_dir.bat app\src\androidTest\js com\ai\assistance\operit\core\tools\javascript\bridge_contract\bridge_contract_runner.js run @params.json ``` ```batch tools\execute_js_dir.bat app\src\androidTest\js com\ai\assistance\operit\core\tools\defaultTool\standard\browser\main.js run "{}" ``` -------------------------------- ### TypeScript Parameter Behavior in Example Packages Source: https://github.com/aaswordman/operit/blob/main/examples/README.md Details how parameters are handled in `.ts` example packages, relying on Kotlin's metadata-driven conversion. It advises focusing on business rules and trusting the primitive types provided after Kotlin's pre-processing. ```typescript // Parameters passed to `.ts` example packages rely on Kotlin’s metadata-driven conversion. The Kotlin bridge reads each tool’s `type`/`required` flags and converts values _before_ they arrive in JavaScript/TypeScript, which means the TS layer should trust the metadata typing and focus on higher-level business rules. Please do not add string→number/boolean/array coercion or re-check `required` fields that Kotlin already enforces, and treat `required: false` parameters as optional (`?`) with their actual primitive types. ``` -------------------------------- ### ARM64 AAPT2 Replacement Script Source: https://github.com/aaswordman/operit/blob/main/app/src/main/assets/templates/android/README.md Instructions for executing the setup script to replace AAPT2 binary for ARM64 environments. This script handles replacing binaries in the Android SDK and Gradle cache. ```bash chmod +x ./setup_android_env.sh ./setup_android_env.sh ``` -------------------------------- ### ADB Example: Send to Specific Chat ID Source: https://github.com/aaswordman/operit/blob/main/docs/external_intent_chat.md Example ADB command to send a message to a pre-existing chat identified by `chat_id`. ```APIDOC ## ADB Example: Send to Specific Chat ID ### Command ```bash adb shell am broadcast \ -a com.ai.assistance.operit.EXTERNAL_CHAT \ --es request_id "req-002" \ --es chat_id "YOUR_CHAT_ID" \ --es message "继续刚才的话题" ``` ``` -------------------------------- ### Message Metadata Shorthand Examples Source: https://github.com/aaswordman/operit/blob/main/docs/chat_import_markdown.md Demonstrates shorthand for specifying message roles and additional metadata like model and timestamp. ```markdown ``` -------------------------------- ### ADB Example: Prevent Auto-Creation of Chat Source: https://github.com/aaswordman/operit/blob/main/docs/external_intent_chat.md Example ADB command demonstrating how to prevent the automatic creation of a new chat if no chat ID is specified and no current chat exists. ```APIDOC ## ADB Example: Prevent Auto-Creation ### Command ```bash adb shell am broadcast \ -a com.ai.assistance.operit.EXTERNAL_CHAT \ --es request_id "req-003" \ --es message "测试" \ --ez create_if_none false ``` ### Behavior If no chat is active and `create_if_none` is false, the operation will fail and return an error. ``` -------------------------------- ### Sync Packages and Execute JavaScript Source: https://github.com/aaswordman/operit/blob/main/tools/JS_ADB_README.md Use this command to sync specified packages and then execute a JavaScript file using the debug install tool. Ensure the Python script and the JavaScript file paths are correct. ```bash d:\Code\prog\assistance\.venv\Scripts\python.exe d:\Code\prog\assistance\sync_example_packages.py --include operit_editor --include sidebar_bing_action tools\execute_js.bat examples\operit_editor.js debug_install_toolpkg @params.json ``` -------------------------------- ### Example of Typical Bad Tool Output Source: https://github.com/aaswordman/operit/blob/main/docs/tool_stream_reconcile_plan.md This XML snippet illustrates the problem where a tool stream is interrupted and retried, resulting in a mix of incomplete and complete tool outputs appearing in the UI. ```xml /a/b /a/b/c.txt ``` -------------------------------- ### Reproduce Scoring and Output Top-K Source: https://github.com/aaswordman/operit/blob/main/tools/memory/README.md Executes the scoring simulation with specified parameters for query, thresholds, weights, and output file. Use this to get ranked memory results for a given query. ```bash python tools/memory/memory_scoring_sim.py score \ --input tools/memory/sample_dataset.json \ --query "chang'an university in xian" \ --top-k 15 \ --semantic-threshold 0.4 \ --score-mode BALANCED \ --keyword-weight 10 \ --semantic-weight 0.5 \ --edge-weight 0.4 \ --min-score-threshold 0.025 \ --output tools/memory/out/score_result.json ``` -------------------------------- ### Script Metadata Example Source: https://github.com/aaswordman/operit/blob/main/docs/SCRIPT_DEV_GUIDE.md Defines script metadata including name, description, author, category, environment variables, and exposed tools. This block is essential for Operit AI to understand and invoke script functionalities. ```typescript /* METADATA { "name": "Automatic_bilibili_assistant", "display_name": { "zh": "B站智能助手", "en": "Bilibili Assistant" }, "description": "高级B站智能助手,通过UI自动化技术实现B站应用交互...", "author": ["Operit Team"], "category": "UI_AUTOMATION", "env": ["BILIBILI_SESSDATA"], "tools": [ { "name": "search_video", "description": "在B站搜索视频内容", "parameters": [ { "name": "keyword", "description": "搜索关键词", "type": "string", "required": true }, // ... more parameters ] }, // ... more tools ] } */ ``` -------------------------------- ### Install AOT Library Source: https://github.com/aaswordman/operit/blob/main/app/src/main/assets/templates/flutter/windows/CMakeLists.txt Installs the Ahead-Of-Time (AOT) compilation library on non-Debug builds (Profile and Release). ```cmake install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" CONFIGURATIONS Profile;Release COMPONENT Runtime) ``` -------------------------------- ### Inline Sandbox Script Debug Example Source: https://github.com/aaswordman/operit/blob/main/tools/JS_ADB_README.md An example of a JavaScript snippet for debugging sandbox scripts. It uses console logging, emits intermediate events, and completes with a structured result. ```javascript console.log("inline debug start"); emit({ stage: "inline", ok: true }); complete({ success: true, message: "inline debug finished" }); ``` -------------------------------- ### Manual ToolPkg File Structure Source: https://github.com/aaswordman/operit/blob/main/docs/TOOLPKG_FORMAT_GUIDE.md This shows the basic file structure for manually creating a ToolPkg. It includes the manifest, packages, UI, and resources directories. ```bash my_toolpkg/ ├── manifest.json ├── packages/ │ └── my_tool.js ├── ui/ │ └── my_ui/ │ └── index.ui.js └── resources/ └── icon.png ``` -------------------------------- ### Manual Gradle Commands Source: https://github.com/aaswordman/operit/blob/main/app/src/main/assets/templates/java/README.md Use these commands with the Gradle Wrapper for building, running, and testing your project. ```bash # Using Gradle Wrapper (recommended) ./gradlew build ./gradlew run ./gradlew test # Or directly using gradle gradle build grade run ``` -------------------------------- ### 在设备上运行整个 Sandbox Script (Windows) Source: https://github.com/aaswordman/operit/blob/main/docs/SCRIPT_DEV_GUIDE.md 使用 `run_sandbox_script.bat` 工具在连接的安卓设备上直接运行 JavaScript 脚本文件,并传递 JSON 格式的参数。 ```bash cd .. tools\run_sandbox_script.bat examples\my_first_script.js "{\"name\":\"世界\"}" ``` -------------------------------- ### Modify App Name in strings.xml Source: https://github.com/aaswordman/operit/blob/main/app/src/main/assets/templates/android/README.md Example of how to change the application's display name by editing the strings.xml file. ```xml 你的应用名 ``` -------------------------------- ### Generate Executable JAR Source: https://github.com/aaswordman/operit/blob/main/app/src/main/assets/templates/java/README.md Commands to build a JAR file and then run it. The JAR will include all dependencies. ```bash ./gradlew jar java -jar build/libs/operit-java-project-1.0.0.jar ``` -------------------------------- ### Packaging ToolPkg on Linux/macOS Source: https://github.com/aaswordman/operit/blob/main/docs/TOOLPKG_FORMAT_GUIDE.md Command to package a ToolPkg directory into a .toolpkg file using zip on Linux or macOS. ```bash cd my_toolpkg zip -r ../my_toolpkg.toolpkg * ``` -------------------------------- ### 在设备上运行脚本 (Linux/macOS) Source: https://github.com/aaswordman/operit/blob/main/docs/SCRIPT_DEV_GUIDE.md 使用 `execute_js.sh` 工具在连接的安卓设备上执行指定的 JavaScript 脚本及其函数。需要提供脚本路径、函数名和 JSON 格式的参数。 ```bash cd .. ./tools/execute_js.sh examples/my_first_script.js hello_world '{"name":"世界"}' ``` -------------------------------- ### Configure Minimum CMake Version Source: https://github.com/aaswordman/operit/blob/main/fbx/CMakeLists.txt Specifies the minimum version of CMake required for this project. Ensure your CMake installation meets this requirement. ```cmake cmake_minimum_required(VERSION 3.22.1) ``` -------------------------------- ### 在设备上运行整个 Sandbox Script (Linux/macOS) Source: https://github.com/aaswordman/operit/blob/main/docs/SCRIPT_DEV_GUIDE.md 使用 `run_sandbox_script.sh` 工具在连接的安卓设备上直接运行 JavaScript 脚本文件,并传递 JSON 格式的参数。 ```bash cd .. ./tools/run_sandbox_script.sh examples/my_first_script.js '{"name":"世界"}' ``` -------------------------------- ### Include Llama.cpp Subdirectory Source: https://github.com/aaswordman/operit/blob/main/llama/CMakeLists.txt Adds the llama.cpp subdirectory to the build if it's found. This reduces the build scope by disabling tests, tools, examples, and servers. ```cmake if (DEFINED OPERIT_LLAMA_CPP_DIR) # Reduce build scope when embedded set(LLAMA_BUILD_COMMON ON CACHE BOOL "" FORCE) set(LLAMA_BUILD_TESTS OFF CACHE BOOL "" FORCE) set(LLAMA_BUILD_TOOLS OFF CACHE BOOL "" FORCE) set(LLAMA_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) set(LLAMA_BUILD_SERVER OFF CACHE BOOL "" FORCE) add_subdirectory("${OPERIT_LLAMA_CPP_DIR}" "${CMAKE_BINARY_DIR}/llama.cpp") endif() ``` -------------------------------- ### Directory Structure for Workspace Templates Source: https://github.com/aaswordman/operit/blob/main/docs/TOOLPKG_FORMAT_GUIDE.md This illustrates a recommended directory structure for workspace templates. It includes the essential .operit/config.json file, README, and source files. ```text resources/ workspaces/ quick_start/ .operit/ config.json README.md src/ ... ``` -------------------------------- ### TypeScript Configuration (tsconfig.json) Source: https://github.com/aaswordman/operit/blob/main/docs/SCRIPT_DEV_GUIDE.md Defines TypeScript compiler options for compiling .ts files to .js. This configuration is recommended for compatibility with the project's standard setup. ```json { "compilerOptions": { "target": "es2020", "module": "commonjs", "lib": [ "es2020" ], "declaration": false, "strict": false, "noImplicitAny": false, "strictNullChecks": true, "noImplicitThis": true, "alwaysStrict": false, "noUnusedLocals": false, "noUnusedParameters": false, "noImplicitReturns": true, "moduleResolution": "node", "allowSyntheticDefaultImports": true, "esModuleInterop": true, "experimentalDecorators": true, "emitDecoratorMetadata": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "typeRoots": [ "./types" ] }, "include": [ "**/*.ts", "**/*.d.ts" ], "exclude": [ "node_modules" ] } ``` -------------------------------- ### JavaScript Function Example Source: https://github.com/aaswordman/operit/blob/main/tools/JS_ADB_README.md This is a required function structure for JavaScript files executed via ADB. Ensure your function accepts a 'params' object and exports itself using 'exports.functionName'. ```javascript function myFunction(params) { // Process parameters const name = params.name || "default"; // Execute business logic const result = `Result: ${name}`; // Return result return { success: true, result: result }; } // Export function exports.myFunction = myFunction; ``` -------------------------------- ### Receiving the Reply Broadcast Source: https://github.com/aaswordman/operit/blob/main/docs/external_intent_chat.md This section explains how to receive the broadcast sent by Operit after processing the chat request. It details the structure of the reply intent and provides an example of a BroadcastReceiver. ```APIDOC ## Receiving Reply Broadcast ### Description Operit sends a broadcast upon completion of the request. This section details how to receive and process this broadcast. ### Reply Intent - **Action**: The action specified in the `reply_action` extra, or `com.ai.assistance.operit.EXTERNAL_CHAT_RESULT` by default. ### Reply Intent Extras - **request_id** (String) - The original `request_id` if provided in the request. - **success** (Boolean) - Indicates if the operation was successful. - **chat_id** (String) - The ID of the chat interaction, if available. - **ai_response** (String) - The AI's response text, if available. - **error** (String) - Error message if the operation failed. ### Example Receiver (Kotlin) ```kotlin class ExternalChatResultReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (intent.action != "com.ai.assistance.operit.EXTERNAL_CHAT_RESULT") return val requestId = intent.getStringExtra("request_id") val success = intent.getBooleanExtra("success", false) val chatId = intent.getStringExtra("chat_id") val aiResponse = intent.getStringExtra("ai_response") val error = intent.getStringExtra("error") Log.d( "ExternalChatResult", "request_id=$requestId success=$success chat_id=$chatId ai_response=$aiResponse error=$error" ) } } ``` ``` -------------------------------- ### Define QuickJS Source Directory and Version Source: https://github.com/aaswordman/operit/blob/main/quickjs/src/main/cpp/CMakeLists.txt Sets the path to the QuickJS third-party directory and reads the QuickJS version from the VERSION file. This is used to include QuickJS sources and define the version in compile flags. ```cmake set(QUICKJS_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../thirdparty/quickjs") file(READ "${QUICKJS_DIR}/VERSION" QUICKJS_VERSION_RAW) string(STRIP "${QUICKJS_VERSION_RAW}" QUICKJS_VERSION) ``` -------------------------------- ### Set Minimum CMake Version and Project Name Source: https://github.com/aaswordman/operit/blob/main/quickjs/src/main/cpp/CMakeLists.txt Specifies the minimum required CMake version and sets the project name. This is a standard starting point for any CMake project. ```cmake cmake_minimum_required(VERSION 3.22.1) project(quickjsjni) ``` -------------------------------- ### 内联插件流式解析 Source: https://github.com/aaswordman/operit/blob/main/docs/RENDERER_ARCH.md 对块级解析后的内容流,使用内联插件进行第二次分割和 KMP 模式匹配,以正确解析嵌套的 Markdown 语法。 ```kotlin blockGroup.stream.splitBy(inlinePlugins).collect { inlineGroup -> // 对每个块的内容再次进行 KMP 模式匹配 // 实现嵌套语法的正确解析 } ``` -------------------------------- ### Message Metadata Format (msg) Source: https://github.com/aaswordman/operit/blob/main/docs/chat_import_markdown.md Each message starts with a `msg` comment. This comment supports role, model, and timestamp. The role can be specified directly without the `role=` prefix. ```html ``` -------------------------------- ### 在设备上运行脚本 (Windows) Source: https://github.com/aaswordman/operit/blob/main/docs/SCRIPT_DEV_GUIDE.md 使用 `execute_js.bat` 工具在连接的安卓设备上执行指定的 JavaScript 脚本及其函数。需要提供脚本路径、函数名和 JSON 格式的参数。 ```bash cd .. tools\execute_js.bat examples\my_first_script.js hello_world "{\"name\":\"世界\"}" ``` -------------------------------- ### Create New Chat + Group + Send Message + Show Floating Window Source: https://github.com/aaswordman/operit/blob/main/docs/external_intent_chat.md Use this adb command to initiate a new chat, assign it to a group, send a message, and display the floating window. It also disables tool status return and sets the initial floating window mode and auto-exit timeout. ```bash adb shell am broadcast \ -a com.ai.assistance.operit.EXTERNAL_CHAT \ --es request_id "req-001" \ --es message "你好,帮我总结一下这段话" \ --es group "workflow" \ --ez create_new_chat true \ --ez show_floating true \ --ez return_tool_status false \ --es initial_mode "WINDOW" \ --el auto_exit_after_ms 10000 ``` -------------------------------- ### Implement ShellRunner Interface Source: https://github.com/aaswordman/operit/blob/main/showerclient/README.md Provide an implementation for the `ShellRunner` interface to allow the client library to execute shell commands. Inject this implementation during application startup. ```kotlin fun interface ShellRunner { suspend fun run(command: String, identity: ShellIdentity): ShellCommandResult } class OperitShowerShellRunner : ShellRunner { override suspend fun run(command: String, identity: ShellIdentity): ShellCommandResult { // Call your own shell executor here // and convert the result to ShellCommandResult } } class YourApplication : Application() { override fun onCreate() { super.onCreate() ShowerEnvironment.shellRunner = OperitShowerShellRunner() } } ``` -------------------------------- ### Get Preset Markdown Plugins Source: https://github.com/aaswordman/operit/blob/main/app/src/main/java/com/ai/assistance/operit/util/stream/README.md Retrieve lists of block-level and inline Markdown plugins. Ensure that plugins with overlapping delimiters are ordered correctly, with longer delimiters preceding shorter ones. ```kotlin val blockPlugins = NestedMarkdownProcessor.getBlockPlugins() val inlinePlugins = NestedMarkdownProcessor.getInlinePlugins() ``` -------------------------------- ### 初始化独立脚本项目的 package.json Source: https://github.com/aaswordman/operit/blob/main/docs/SCRIPT_DEV_GUIDE.md 创建 `package.json` 文件来管理独立 Node.js 脚本项目的元数据和开发依赖,包括 TypeScript 和 Node.js 类型定义。 ```json { "name": "my-script-project", "version": "1.0.0", "description": "My new script project.", "scripts": { "build": "tsc" }, "devDependencies": { "@types/node": "^22.0.0", "typescript": "^5.4.5" } } ``` -------------------------------- ### Packaging ToolPkg on Windows (PowerShell) Source: https://github.com/aaswordman/operit/blob/main/docs/TOOLPKG_FORMAT_GUIDE.md Command to package a ToolPkg directory into a .toolpkg file using Compress-Archive in PowerShell on Windows. ```powershell Compress-Archive -Path my_toolpkg\* -DestinationPath my_toolpkg.toolpkg ``` -------------------------------- ### Java/Kotlin to JavaScript Type Conversion Example Source: https://github.com/aaswordman/operit/blob/main/docs/TOOLPKG_FORMAT_GUIDE.md Illustrates the common mistake of trying to use Java collection methods on JavaScript-converted types. JavaScript arrays should be accessed using `.length` and indexing, not `.size()` or `.get()`. ```javascript const items = someJavaApi.listSomething(); items.size(); // 不要这样写 items.get(0); // 不要这样写 items.length; // 对 items[0]; // 对 ``` -------------------------------- ### Basic Pattern Matching Conditions Source: https://github.com/aaswordman/operit/blob/main/app/src/main/java/com/ai/assistance/operit/util/stream/kmpREADME.md Demonstrates various basic conditions for defining patterns, including matching specific characters, literals, character ranges, and character sets. ```kotlin kmpPattern { // Match a single character 'a' char('a') // Match the string "hello" literal("hello") // Match any character between 'a' and 'z' range('a', 'z') // Match any one of 'a', 'e', 'i', 'o', 'u' anyOf('a', 'e', 'i', 'o', 'u') // Match any single character (wildcard) any() } ``` -------------------------------- ### JavaScript Function Example for execute_js Source: https://github.com/aaswordman/operit/blob/main/tools/JS_ADB_README.md This JavaScript code defines an exported function `main` that accepts parameters and returns a success status along with the echoed parameters. It must be a valid JavaScript file with an exported function. ```javascript function main(params) { return { success: true, echo: params }; } exports.main = main; ``` -------------------------------- ### 克隆项目并安装依赖 Source: https://github.com/aaswordman/operit/blob/main/docs/SCRIPT_DEV_GUIDE.md 克隆 Operit 项目仓库并安装必要的依赖,包括 TypeScript 编译器。 ```bash git clone https://github.com/AAswordman/Operit.git cd Operit npm install ``` -------------------------------- ### Project Structure Overview Source: https://github.com/aaswordman/operit/blob/main/app/src/main/assets/templates/android/README.md Provides a visual representation of the project's directory and file structure. ```tree android-project/ ├── app/ │ ├── src/ │ │ ├── main/ │ │ │ ├── java/com/java/myapplication/ │ │ │ │ ├── MainActivity.kt # 主Activity │ │ │ │ └── ui/theme/ │ │ │ │ ├── Color.kt # 颜色定义 │ │ │ │ ├── Theme.kt # 主题配置 │ │ │ │ └── Type.kt # 字体配置 │ │ │ ├── res/ # 资源文件 │ │ │ └── AndroidManifest.xml # 应用清单 │ │ ├── androidTest/ # Android测试 │ │ └── test/ # 单元测试 │ ├── build.gradle.kts # App模块配置 │ └── proguard-rules.pro # 混淆规则 ├── gradle/ │ ├── libs.versions.toml # 依赖版本管理 │ └── wrapper/ # Gradle Wrapper ├── build.gradle.kts # 项目级配置 ├── settings.gradle.kts # 项目设置 ├── gradle.properties # Gradle属性 ├── gradlew / gradlew.bat # Gradle命令 └── .gitignore # Git忽略 ``` -------------------------------- ### Set Linker Options for QuickJS JNI Source: https://github.com/aaswordman/operit/blob/main/quickjs/src/main/cpp/CMakeLists.txt Applies specific linker options to the 'quickjsjni' library, such as setting the maximum page size for memory mapping. ```cmake target_link_options(quickjsjni PRIVATE "-Wl,-z,max-page-size=16384") ```