diff --git a/.eslintrc.json b/.eslintrc.json index b47836b..d8a2a46 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -1,11 +1,8 @@ { "root": true, "parser": "@typescript-eslint/parser", - "plugins": ["@typescript-eslint"], - "extends": [ - "eslint:recommended", - "plugin:@typescript-eslint/recommended" - ], + "plugins": ["@typescript-eslint", "prettier"], + "extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended", "plugin:prettier/recommended"], "env": { "node": true, "es2022": true @@ -18,8 +15,8 @@ "@typescript-eslint/no-explicit-any": "warn", "@typescript-eslint/explicit-function-return-type": "off", "@typescript-eslint/no-unused-vars": ["error", { "argsIgnorePattern": "^_" }], - "no-constant-condition": ["error", { "checkLoops": false }] + "no-constant-condition": ["error", { "checkLoops": false }], + "prettier/prettier": "error" }, "ignorePatterns": ["dist", "node_modules", "*.js"] } - diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index dd84ea7..b5c68e5 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -4,7 +4,6 @@ about: Create a report to help us improve title: '' labels: '' assignees: '' - --- **Describe the bug** @@ -12,6 +11,7 @@ A clear and concise description of what the bug is. **To Reproduce** Steps to reproduce the behavior: + 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' @@ -24,15 +24,17 @@ A clear and concise description of what you expected to happen. If applicable, add screenshots to help explain your problem. **Desktop (please complete the following information):** - - OS: [e.g. iOS] - - Browser [e.g. chrome, safari] - - Version [e.g. 22] + +- OS: [e.g. iOS] +- Browser [e.g. chrome, safari] +- Version [e.g. 22] **Smartphone (please complete the following information):** - - Device: [e.g. iPhone6] - - OS: [e.g. iOS8.1] - - Browser [e.g. stock browser, safari] - - Version [e.g. 22] + +- Device: [e.g. iPhone6] +- OS: [e.g. iOS8.1] +- Browser [e.g. stock browser, safari] +- Version [e.g. 22] **Additional context** Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index bbcbbe7..2f28cea 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -4,7 +4,6 @@ about: Suggest an idea for this project title: '' labels: '' assignees: '' - --- **Is your feature request related to a problem? Please describe.** diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5e9fa2f..0ae986f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,7 +32,7 @@ jobs: run: npm run lint - name: Test (unit tests only) - run: npm run test -- --testPathPattern="unittests" + run: make coverage - name: Build run: npm run build @@ -44,7 +44,7 @@ jobs: steps: - uses: actions/checkout@v4 with: - fetch-depth: 0 # 获取完整历史用于增量覆盖率检查 + fetch-depth: 0 # 获取完整历史用于增量覆盖率检查 - name: Use Node.js 18.x uses: actions/setup-node@v4 diff --git a/.github/workflows/publish.yaml b/.github/workflows/publish.yaml index c7eee90..09b1d01 100644 --- a/.github/workflows/publish.yaml +++ b/.github/workflows/publish.yaml @@ -6,7 +6,7 @@ on: branches: - '**' tags-ignore: - - '**' # 忽略 tag push,避免与 release 事件重复触发 + - '**' # 忽略 tag push,避免与 release 事件重复触发 # GitHub Release 触发正式发布 release: @@ -21,8 +21,8 @@ on: default: 'test' type: choice options: - - official # 正式发布 - - test # 测试发布 + - official # 正式发布 + - test # 测试发布 version: description: '版本号(留空则自动递增)/ Version (leave empty for auto-increment)' required: false @@ -33,9 +33,9 @@ on: default: 'patch' type: choice options: - - patch # 0.0.1 -> 0.0.2 - - minor # 0.0.1 -> 0.1.0 - - major # 0.0.1 -> 1.0.0 + - patch # 0.0.1 -> 0.0.2 + - minor # 0.0.1 -> 0.1.0 + - major # 0.0.1 -> 1.0.0 jobs: # 等待 CI 测试通过(仅 push 触发时) @@ -104,20 +104,20 @@ jobs: # 获取包名 PACKAGE_NAME=$(node -p "require('./package.json').name") echo "PACKAGE_NAME=${PACKAGE_NAME}" >> $GITHUB_OUTPUT - + # 获取基础版本号 BASE_VERSION=$(node -p "require('./package.json').version") - + # 生成唯一标识符:优先使用 run_id,否则使用时间戳 if [ -n "${{ github.run_id }}" ]; then UNIQUE_ID="${{ github.run_id }}" else UNIQUE_ID=$(date +%Y%m%d%H%M%S) fi - + # 生成 prerelease 版本号 VERSION="${BASE_VERSION}-test.${UNIQUE_ID}" - + echo "VERSION=${VERSION}" >> $GITHUB_OUTPUT echo "Test version: ${VERSION}" @@ -148,12 +148,12 @@ jobs: PACKAGE_NAME="${{ steps.version.outputs.PACKAGE_NAME }}" VERSION="${{ steps.version.outputs.VERSION }}" echo "Publishing ${PACKAGE_NAME}@${VERSION} with tag=test" - + # Remove any .npmrc that might interfere with OIDC rm -f ~/.npmrc rm -f .npmrc rm -f /home/runner/work/_temp/.npmrc - + # Publish using Trusted Publishers (OIDC) npm publish --tag test --access public --provenance env: @@ -211,7 +211,7 @@ jobs: run: | PACKAGE_NAME=$(node -p "require('./package.json').name") echo "PACKAGE_NAME=${PACKAGE_NAME}" >> $GITHUB_OUTPUT - + # 确定版本号 if [ "${{ github.event_name }}" = "release" ]; then VERSION="${{ github.event.release.tag_name }}" @@ -254,7 +254,7 @@ jobs: VERSION="${MAJOR}.${MINOR}.${PATCH}" fi fi - + echo "VERSION=${VERSION}" >> $GITHUB_OUTPUT echo "Official version: ${VERSION}" @@ -297,12 +297,12 @@ jobs: PACKAGE_NAME="${{ steps.config.outputs.PACKAGE_NAME }}" VERSION="${{ steps.config.outputs.VERSION }}" echo "Publishing ${PACKAGE_NAME}@${VERSION} with tag=latest" - + # Remove any .npmrc that might interfere with OIDC rm -f ~/.npmrc rm -f .npmrc rm -f /home/runner/work/_temp/.npmrc - + # Publish using Trusted Publishers (OIDC) npm publish --tag latest --access public --provenance env: @@ -357,7 +357,7 @@ jobs: run: | PACKAGE_NAME=$(node -p "require('./package.json').name") echo "PACKAGE_NAME=${PACKAGE_NAME}" >> $GITHUB_OUTPUT - + VERSION="${{ inputs.version }}" if [ -z "$VERSION" ]; then # 自动生成测试版本号 @@ -372,7 +372,7 @@ jobs: VERSION="${BASE_VERSION}-test.${UNIQUE_ID}" fi - + echo "VERSION=${VERSION}" >> $GITHUB_OUTPUT echo "Test version: ${VERSION}" @@ -401,12 +401,12 @@ jobs: PACKAGE_NAME="${{ steps.version.outputs.PACKAGE_NAME }}" VERSION="${{ steps.version.outputs.VERSION }}" echo "Publishing ${PACKAGE_NAME}@${VERSION} with tag=test" - + # Remove any .npmrc that might interfere with OIDC rm -f ~/.npmrc rm -f .npmrc rm -f /home/runner/work/_temp/.npmrc - + # Publish using Trusted Publishers (OIDC) npm publish --tag test --access public --provenance env: diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..1d168c4 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,131 @@ +# Dependencies +node_modules/ +bun.lock + +# Build outputs +dist/ +coverage/ +*.tsbuildinfo + +# Logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Coverage directory used by tools like istanbul +coverage/ +*.lcov + +# nyc test coverage +.nyc_output + +# Dependency directories +node_modules/ +jspm_packages/ + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Microbundle cache +.rpt2_cache/ +.rts2_cache_cjs/ +.rts2_cache_es/ +.rts2_cache_umd/ + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variables file +.env +.env.test + +# parcel-bundler cache (https://parceljs.org/) +.cache +.parcel-cache + +# Next.js build output +.next + +# Nuxt.js build / generate output +.nuxt +dist + +# Gatsby files +.cache/ +public + +# Storybook build outputs +.out +.storybook-out + +# Temporary folders +tmp/ +temp/ + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? + +# OS generated files +Thumbs.db +ehthumbs.db +Desktop.ini + +# Jest coverage +coverage/ + +# TypeScript +*.tsbuildinfo + +# Optional stylelint cache +.stylelintcache + +# VS Code +.vscode/settings.json +.vscode/launch.json + +# Local development +.env.local +.env.development.local +.env.test.local +.env.production.local + +# Testing +.pytest_cache/ +__pycache__/ +*.pyc + +# Build artifacts +build/ +out/ + +# Lock files (keep package-lock.json) +yarn.lock +pnpm-lock.yaml + +# Generated files +codegen/ +scripts/inject-version-check.mjs \ No newline at end of file diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..77e0212 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,29 @@ +{ + "semi": true, + "trailingComma": "es5", + "singleQuote": true, + "printWidth": 100, + "tabWidth": 2, + "useTabs": false, + "bracketSpacing": true, + "bracketSameLine": false, + "arrowParens": "avoid", + "endOfLine": "lf", + "quoteProps": "as-needed", + "jsxSingleQuote": true, + "overrides": [ + { + "files": "*.json", + "options": { + "printWidth": 200 + } + }, + { + "files": "*.md", + "options": { + "printWidth": 80, + "proseWrap": "preserve" + } + } + ] +} diff --git a/AGENTS.md b/AGENTS.md index 1fff574..26cb6cb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,14 +38,14 @@ Agent Runtime 是 AgentRun 中的核心资源,代表一个运行中的 AI Agen #### Agent Runtime 状态 -| 状态 | 说明 | -|-----|------| -| `CREATING` | 创建中 | -| `READY` | 就绪,可正常提供服务 | -| `UPDATING` | 更新中 | -| `DELETING` | 删除中 | -| `FAILED` | 失败 | -| `DELETE_FAILED` | 删除失败 | +| 状态 | 说明 | +| --------------- | -------------------- | +| `CREATING` | 创建中 | +| `READY` | 就绪,可正常提供服务 | +| `UPDATING` | 更新中 | +| `DELETING` | 删除中 | +| `FAILED` | 失败 | +| `DELETE_FAILED` | 删除失败 | ### Agent Runtime Endpoint(访问端点) @@ -61,13 +61,13 @@ Endpoint 是 Agent Runtime 的对外访问入口,每个 Agent Runtime 可以 #### Endpoint 状态 -| 状态 | 说明 | -|-----|------| -| `CREATING` | 创建中 | -| `READY` | 就绪,可正常访问 | -| `UPDATING` | 更新中 | -| `DELETING` | 删除中 | -| `FAILED` | 失败 | +| 状态 | 说明 | +| ---------- | ---------------- | +| `CREATING` | 创建中 | +| `READY` | 就绪,可正常访问 | +| `UPDATING` | 更新中 | +| `DELETING` | 删除中 | +| `FAILED` | 失败 | ### Agent Runtime Version(版本) @@ -200,6 +200,7 @@ AgentRun 支持两种部署方式,满足不同场景需求。 适合快速开发和部署简单应用。 **特点:** + - 直接上传代码文件 - 支持多种编程语言(Node.js、Python、Java 等) - 自动安装依赖 @@ -225,6 +226,7 @@ const agent = await AgentRuntime.create({ ``` **支持的语言:** + - Node.js 18 - Node.js 20 - Python 3.10 @@ -237,6 +239,7 @@ const agent = await AgentRuntime.create({ 适合复杂应用和生产环境。 **特点:** + - 完全自定义运行环境 - 支持任何容器化应用 - 版本管理更清晰 @@ -284,8 +287,8 @@ AgentRun 支持灵活的网络配置,满足不同安全和性能需求。 import { AgentRuntime, NetworkConfig } from '@alicloud/agentrun-sdk'; const networkConfig: NetworkConfig = { - networkMode: 'INTERNET', // 公网模式 - vpcConfig: undefined // 公网模式不需要 VPC 配置 + networkMode: 'INTERNET', // 公网模式 + vpcConfig: undefined, // 公网模式不需要 VPC 配置 }; const agent = await AgentRuntime.create({ @@ -306,15 +309,18 @@ const agent = await AgentRuntime.create({ 配置健康检查确保 Agent 正常运行: ```typescript -import { AgentRuntime, AgentRuntimeHealthCheckConfig } from '@alicloud/agentrun-sdk'; +import { + AgentRuntime, + AgentRuntimeHealthCheckConfig, +} from '@alicloud/agentrun-sdk'; const healthCheckConfig: AgentRuntimeHealthCheckConfig = { - failureThreshold: 3, // 失败阈值 - httpGetUrl: "/health", // 健康检查路径 - initialDelaySeconds: 10, // 初始延迟 - periodSeconds: 30, // 检查间隔 - successThreshold: 1, // 成功阈值 - timeoutSeconds: 5, // 超时时间 + failureThreshold: 3, // 失败阈值 + httpGetUrl: '/health', // 健康检查路径 + initialDelaySeconds: 10, // 初始延迟 + periodSeconds: 30, // 检查间隔 + successThreshold: 1, // 成功阈值 + timeoutSeconds: 5, // 超时时间 }; const agent = await AgentRuntime.create({ @@ -335,10 +341,14 @@ const agent = await AgentRuntime.create({ 支持多种协议类型: ```typescript -import { AgentRuntime, AgentRuntimeProtocolType, AgentRuntimeProtocolConfig } from '@alicloud/agentrun-sdk'; +import { + AgentRuntime, + AgentRuntimeProtocolType, + AgentRuntimeProtocolConfig, +} from '@alicloud/agentrun-sdk'; const protocolConfig: AgentRuntimeProtocolConfig = { - type: AgentRuntimeProtocolType.HTTP, // 协议类型 + type: AgentRuntimeProtocolType.HTTP, // 协议类型 }; const agent = await AgentRuntime.create({ @@ -383,13 +393,13 @@ import { AgentRuntime, Status } from '@alicloud/agentrun-sdk'; // 等待 Agent 就绪 await agent.waitUntilReady({ - beforeCheck: (runtime) => console.log(`当前状态: ${runtime.status}`) + beforeCheck: runtime => console.log(`当前状态: ${runtime.status}`), }); // 检查状态并处理 if (agent.status === Status.FAILED) { - console.log(`部署失败: ${agent.statusReason}`); - // 进行错误处理 + console.log(`部署失败: ${agent.statusReason}`); + // 进行错误处理 } ``` @@ -401,12 +411,14 @@ if (agent.status === Status.FAILED) { import { AgentRuntime } from '@alicloud/agentrun-sdk'; // 删除 Endpoint -const endpoints = await client.listEndpoints({ agentRuntimeId: agent.agentRuntimeId }); +const endpoints = await client.listEndpoints({ + agentRuntimeId: agent.agentRuntimeId, +}); for (const endpoint of endpoints) { - await client.deleteEndpoint({ - agentRuntimeId: agent.agentRuntimeId, - endpointId: endpoint.agentRuntimeEndpointId - }); + await client.deleteEndpoint({ + agentRuntimeId: agent.agentRuntimeId, + endpointId: endpoint.agentRuntimeEndpointId, + }); } // 删除 Agent Runtime @@ -422,27 +434,27 @@ import { AgentRuntime } from '@alicloud/agentrun-sdk'; // 创建新版本 const newAgent = await client.create({ - input: updatedConfig + input: updatedConfig, }); // 配置流量分配 await client.updateEndpoint({ - agentRuntimeId: agent.agentRuntimeId, - endpointId: endpoint.agentRuntimeEndpointId, - input: { - routingConfiguration: { - versionWeights: [ - { - version: oldAgent.agentRuntimeVersion, - weight: 80 // 80% 流量给旧版本 - }, - { - version: newAgent.agentRuntimeVersion, - weight: 20 // 20% 流量给新版本 - } - ] - } - } + agentRuntimeId: agent.agentRuntimeId, + endpointId: endpoint.agentRuntimeEndpointId, + input: { + routingConfiguration: { + versionWeights: [ + { + version: oldAgent.agentRuntimeVersion, + weight: 80, // 80% 流量给旧版本 + }, + { + version: newAgent.agentRuntimeVersion, + weight: 20, // 20% 流量给新版本 + }, + ], + }, + }, }); ``` @@ -451,19 +463,23 @@ await client.updateEndpoint({ 实现健壮的错误处理机制: ```typescript -import { AgentRuntime, ResourceNotExistError, ClientError } from '@alicloud/agentrun-sdk'; +import { + AgentRuntime, + ResourceNotExistError, + ClientError, +} from '@alicloud/agentrun-sdk'; try { - const agent = await client.get({ id: "agent-id" }); + const agent = await client.get({ id: 'agent-id' }); } catch (error) { - if (error instanceof ResourceNotExistError) { - console.log("Agent 不存在"); - } else if (error instanceof ClientError) { - console.log(`API 调用失败: ${error.message}`); - console.log(`错误码: ${error.errorCode}`); - } else { - throw error; - } + if (error instanceof ResourceNotExistError) { + console.log('Agent 不存在'); + } else if (error instanceof ClientError) { + console.log(`API 调用失败: ${error.message}`); + console.log(`错误码: ${error.errorCode}`); + } else { + throw error; + } } ``` @@ -481,8 +497,8 @@ const agent = await AgentRuntime.create({ command: ['node', 'index.js'], }, logConfiguration: { - project: "your-project", // SLS 项目 - logstore: "your-log-store", // SLS 日志库 + project: 'your-project', // SLS 项目 + logstore: 'your-log-store', // SLS 日志库 }, port: 9000, cpu: 2, @@ -495,17 +511,20 @@ const agent = await AgentRuntime.create({ 对于高并发场景,使用异步 API: ```typescript -import { AgentRuntimeClient, AgentRuntimeCreateInput } from '@alicloud/agentrun-sdk'; +import { + AgentRuntimeClient, + AgentRuntimeCreateInput, +} from '@alicloud/agentrun-sdk'; async function deployMultipleAgents() { - const client = new AgentRuntimeClient(); - - // 并发创建多个 Agent - const configs: AgentRuntimeCreateInput[] = [config1, config2, config3]; - const promises = configs.map(config => client.create({ input: config })); - - const agents = await Promise.all(promises); - return agents; + const client = new AgentRuntimeClient(); + + // 并发创建多个 Agent + const configs: AgentRuntimeCreateInput[] = [config1, config2, config3]; + const promises = configs.map(config => client.create({ input: config })); + + const agents = await Promise.all(promises); + return agents; } // 运行 @@ -559,7 +578,9 @@ const credential = await Credential.create({ input: { credentialName: 'my-api-key', description: 'API key for external service', - credentialConfig: CredentialConfig.inboundApiKey({ apiKey: 'your-api-key-here' }), + credentialConfig: CredentialConfig.inboundApiKey({ + apiKey: 'your-api-key-here', + }), }, }); @@ -581,7 +602,13 @@ await credential.delete(); 管理模型服务和代理: ```typescript -import { ModelService, ModelProxy, BackendType, Provider, ModelType } from '@alicloud/agentrun-sdk'; +import { + ModelService, + ModelProxy, + BackendType, + Provider, + ModelType, +} from '@alicloud/agentrun-sdk'; // 创建模型服务 const modelService = await ModelService.create({ @@ -642,7 +669,9 @@ const template = await client.createTemplate({ await template.waitUntilReady(); // 创建沙箱 -const sandbox = await client.createCodeInterpreterSandbox(template.templateName!); +const sandbox = await client.createCodeInterpreterSandbox( + template.templateName! +); await sandbox.waitUntilRunning(); // 执行代码 (需要数据 API 支持) @@ -677,7 +706,11 @@ server.start({ port: 9000 }); 除了通过类方法创建Agent Runtime,还可以使用AgentRuntimeClient进行更灵活的管理: ```typescript -import { AgentRuntimeClient, AgentRuntime, AgentRuntimeLanguage } from '@alicloud/agentrun-sdk'; +import { + AgentRuntimeClient, + AgentRuntime, + AgentRuntimeLanguage, +} from '@alicloud/agentrun-sdk'; // 创建客户端 const client = new AgentRuntimeClient(); @@ -693,7 +726,7 @@ const agent = await client.create({ port: 9000, cpu: 2, memory: 4096, - } + }, }); // 等待就绪 @@ -706,7 +739,7 @@ const existingAgent = await client.get({ id: agent.agentRuntimeId }); const agents = await client.list({ input: { agentRuntimeName: 'my-agent', - } + }, }); // 更新 Agent Runtime @@ -714,7 +747,7 @@ const updatedAgent = await client.update({ id: agent.agentRuntimeId, input: { description: 'Updated description', - } + }, }); // 删除 Agent Runtime @@ -727,14 +760,14 @@ await client.delete({ id: agent.agentRuntimeId }); - **运行命令**:使用项目根目录的 TypeScript 配置运行: - ```bash - npm run typecheck - ``` + ```bash + npm run typecheck + ``` - **必需项**:AI 在每次修改代码并准备提交时,必须: - - 运行上述类型检查命令并等待完成; - - 若检查通过,在提交消息或 PR 描述中写入简短摘要(例如:"类型检查通过"); - - 若检查失败,AI 应在 PR 描述中列出前 30 条错误(或最关键的若干条),并给出优先修复建议或自动修复方案。 + - 运行上述类型检查命令并等待完成; + - 若检查通过,在提交消息或 PR 描述中写入简短摘要(例如:"类型检查通过"); + - 若检查失败,AI 应在 PR 描述中列出前 30 条错误(或最关键的若干条),并给出优先修复建议或自动修复方案。 - **CI 行为**:项目 CI 可根据仓库策略决定是否将类型检查失败作为阻断条件;AI 应遵从仓库当前 CI 策略并在 PR 中说明检查结果。 @@ -755,6 +788,7 @@ await client.delete({ id: agent.agentRuntimeId }); ### Q: Agent Runtime 启动失败怎么办? A: 检查以下几点: + 1. 代码或镜像是否正确 2. 启动命令是否正确 3. 端口配置是否匹配 @@ -763,6 +797,7 @@ A: 检查以下几点: ### Q: 如何实现零停机更新? A: 使用版本管理和流量路由: + 1. 创建新版本 Agent Runtime 2. 等待新版本就绪 3. 配置 Endpoint 路由权重,逐步切换流量 @@ -771,6 +806,7 @@ A: 使用版本管理和流量路由: ### Q: 如何优化 Agent 启动速度? A: 建议: + 1. 使用容器镜像部署,提前构建好环境 2. 优化应用启动逻辑,减少初始化时间 3. 合理配置健康检查参数 @@ -779,6 +815,7 @@ A: 建议: ### Q: 如何控制成本? A: 建议: + 1. 及时删除不用的 Agent Runtime 2. 根据实际负载配置合适的实例规格 3. 使用按量付费,避免资源闲置 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 86934f3..236803b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -19,11 +19,9 @@ It is warmly welcomed if you have interest to hack on Serverless Devs. First, we - [Package contribution](#package-contribution) - [Engage to help anything](#engage-to-help-anything) - - ## Reporting security issues -Security issues are always treated seriously. As our usual principle, we discourage anyone to spread security issues. If you find a security issue of Serverless Devs, please do not discuss it in public and even do not open a public issue. Instead we encourage you to send us a private email to [liuyu@xmail.tech](mailto:liuyu@xmail.tech) to report this. +Security issues are always treated seriously. As our usual principle, we discourage anyone to spread security issues. If you find a security issue of Serverless Devs, please do not discuss it in public and even do not open a public issue. Instead we encourage you to send us a private email to [liuyu@xmail.tech](mailto:liuyu@xmail.tech) to report this. ## Reporting general issues @@ -35,16 +33,16 @@ To make the issue details as standard as possible, we setup an [ISSUE TEMPLATE]( There are a lot of cases when you could open an issue: -* bug report -* feature request -* performance issues -* feature proposal -* feature design -* help wanted -* doc incomplete -* test improvement -* any questions on project -* and so on +- bug report +- feature request +- performance issues +- feature proposal +- feature design +- help wanted +- doc incomplete +- test improvement +- any questions on project +- and so on Also we must remind that when filling a new issue, please remember to remove the sensitive data from your post. Sensitive data could be password, secret key, network locations, private business data and so on. @@ -52,16 +50,16 @@ Also we must remind that when filling a new issue, please remember to remove the Every action to make project Serverless Devs better is encouraged. On GitHub, every improvement for Serverless Devs could be via a PR (short for pull request). -* If you find a typo, try to fix it! -* If you find a bug, try to fix it! -* If you find some redundant codes, try to remove them! -* If you find some test cases missing, try to add them! -* If you could enhance a feature, please **DO NOT** hesitate! -* If you find code implicit, try to add comments to make it clear! -* If you find code ugly, try to refactor that! -* If you can help to improve documents, it could not be better! -* If you find document incorrect, just do it and fix that! -* ... +- If you find a typo, try to fix it! +- If you find a bug, try to fix it! +- If you find some redundant codes, try to remove them! +- If you find some test cases missing, try to add them! +- If you could enhance a feature, please **DO NOT** hesitate! +- If you find code implicit, try to add comments to make it clear! +- If you find code ugly, try to refactor that! +- If you can help to improve documents, it could not be better! +- If you find document incorrect, just do it and fix that! +- ... Actually it is impossible to list them completely. Just remember one principle: @@ -69,10 +67,10 @@ Actually it is impossible to list them completely. Just remember one principle: Since you are ready to improve Serverless Devs with a PR, we suggest you could take a look at the PR rules here. -* [Workspace Preparation](#workspace-preparation) -* [Branch Definition](#branch-definition) -* [Commit Rules](#commit-rules) -* [PR Description](#pr-description) +- [Workspace Preparation](#workspace-preparation) +- [Branch Definition](#branch-definition) +- [Commit Rules](#commit-rules) +- [PR Description](#pr-description) ### Workspace Preparation @@ -107,7 +105,7 @@ Right now we assume every contribution via pull request is for [branch develop]( As a contributor, keep in mind again that every contribution via pull request is for branch develop. While in project Serverless Devs, there are several other branches, we generally call them release branches(such as 0.6.0,0.6.1), feature branches, hotfix branches and master branch. -When officially releasing a version, there will be a release branch and named with the version number. +When officially releasing a version, there will be a release branch and named with the version number. After the release, we will merge the commit of the release branch into the master branch. @@ -115,30 +113,29 @@ When we find that there is a bug in a certain version, we will decide to fix it For larger features, we will pull out the feature branch for development and verification. - ### Commit Rules Actually in Serverless Devs, we take two rules serious when committing: -* [Commit Message](#commit-message) -* [Commit Content](#commit-content) +- [Commit Message](#commit-message) +- [Commit Content](#commit-content) #### Commit Message Commit message could help reviewers better understand what is the purpose of submitted PR. It could help accelerate the code review procedure as well. We encourage contributors to use **EXPLICIT** commit message rather than ambiguous message. In general, we advocate the following commit message type: -* docs: xxxx. For example, "docs: add docs about agentrun-sdk-python cluster installation". -* feature: xxxx.For example, "feature: support oracle in AT mode". -* bugfix: xxxx. For example, "bugfix: fix panic when input nil parameter". -* refactor: xxxx. For example, "refactor: simplify to make codes more readable". -* test: xxx. For example, "test: add unit test case for func InsertIntoArray". -* other readable and explicit expression ways. +- docs: xxxx. For example, "docs: add docs about agentrun-sdk-python cluster installation". +- feature: xxxx.For example, "feature: support oracle in AT mode". +- bugfix: xxxx. For example, "bugfix: fix panic when input nil parameter". +- refactor: xxxx. For example, "refactor: simplify to make codes more readable". +- test: xxx. For example, "test: add unit test case for func InsertIntoArray". +- other readable and explicit expression ways. On the other side, we discourage contributors from committing message like the following ways: -* ~~fix bug~~ -* ~~update~~ -* ~~add doc~~ +- ~~fix bug~~ +- ~~update~~ +- ~~add doc~~ If you get lost, please see [How to Write a Git Commit Message](http://chris.beams.io/posts/git-commit/) for a start. @@ -146,17 +143,15 @@ If you get lost, please see [How to Write a Git Commit Message](http://chris.bea Commit content represents all content changes included in one commit. We had better include things in one single commit which could support reviewer's complete review without any other commits' help. In another word, contents in one single commit can pass the CI to avoid code mess. In brief, there are three minor rules for us to keep in mind: -* avoid very large change in a commit; -* complete and reviewable for each commit. -* check git config(`user.name`, `user.email`) when committing to ensure that it is associated with your github ID. -* when submitting pr, please add a brief description of the current changes to the X.X.X.md file under the 'changes/' folder - +- avoid very large change in a commit; +- complete and reviewable for each commit. +- check git config(`user.name`, `user.email`) when committing to ensure that it is associated with your github ID. +- when submitting pr, please add a brief description of the current changes to the X.X.X.md file under the 'changes/' folder In addition, in the code change part, we suggest that all contributors should read the [code style of agentrun-sdk-python](#code-style). No matter commit message, or commit content, we do take more emphasis on code review. - ### PR Description PR is the only way to make change to Serverless Devs project files. To help reviewers better get your purpose, PR description could not be too detailed. We encourage contributors to follow the [PR template](./.github/PULL_REQUEST_TEMPLATE.md) to finish the pull request. @@ -165,21 +160,20 @@ PR is the only way to make change to Serverless Devs project files. To help revi Any test case would be welcomed. Currently, Serverless Devs function test cases are high priority. -* For unit test, you need to create a test file named `xxx-xxx.test.ts` in the test directory of the same module. Recommend you to use the [Jest](https://jestjs.io/) UT framework +- For unit test, you need to create a test file named `xxx-xxx.test.ts` in the test directory of the same module. Recommend you to use the [Jest](https://jestjs.io/) UT framework -* For integration test, you can put the integration test in the test directory or the Serverless Devs-test module. It is recommended to use mock-related test frameworks. +- For integration test, you can put the integration test in the test directory or the Serverless Devs-test module. It is recommended to use mock-related test frameworks. ## Engage to help anything We choose GitHub as the primary place for agentrun-sdk-python to collaborate. So the latest updates of agentrun-sdk-python are always here. Although contributions via PR is an explicit way to help, we still call for any other ways. -* reply to other's issues if you could; -* help solve other user's problems; -* help review other's PR design; -* help review other's codes in PR; -* discuss about agentrun-sdk-python to make things clearer; -* advocate Serverless Devs technology beyond GitHub; -* write blogs on agentrun-sdk-python and so on. - +- reply to other's issues if you could; +- help solve other user's problems; +- help review other's PR design; +- help review other's codes in PR; +- discuss about agentrun-sdk-python to make things clearer; +- advocate Serverless Devs technology beyond GitHub; +- write blogs on agentrun-sdk-python and so on. In a word, **ANY HELP IS CONTRIBUTION.** diff --git a/Makefile b/Makefile index 47f318d..921124c 100644 --- a/Makefile +++ b/Makefile @@ -47,7 +47,7 @@ clean-all: clean ## 完全清理 / Full clean including node_modules .PHONY: fmt fmt: ## 格式化代码 / Format code @echo "🎨 Formatting code..." - @npm run lint:fix + @npm run format:fix @echo "✅ Code formatted" .PHONY: lint diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md index 5322235..751730d 100644 --- a/PULL_REQUEST_TEMPLATE.md +++ b/PULL_REQUEST_TEMPLATE.md @@ -1,37 +1,43 @@ > Thank you for creating a pull request to contribute to Serverless Devs agentrun-sdk-python code! Before you open the request please answer the following questions to help it be more easily integrated. Please check the boxes "[ ]" with "[x]" when done too. -> Please select one of the PR types below to complete +> Please select one of the PR types below to complete ---------------------- +--- ## Fix bugs **Bug detail** + > The specific manifestation of the bug or the associated issue. **Pull request tasks** + - [ ] Add test cases for the changes - [ ] Passed the CI test ---------------------- +--- ## Update docs **Reason for update** + > Why do you need to update your documentation? **Pull request tasks** + - [ ] Update Chinese documentation - [ ] Update English documentation ---------------------- +--- ## Add contributor **Contributed content** + - [ ] Code - [ ] Document **Content detail** + ``` if content_type == 'code' || content_type == 'document': please tell us `PR url`,like: https://github.com/Serverless-Devs/agentrun-sdk-python/pull/1 @@ -39,9 +45,10 @@ else: please describe your contribution in detail ``` ---------------------- +--- ## Others **Reason for update** + > Why do you need to update your documentation? diff --git a/README.md b/README.md index c2a1b94..23aa137 100644 --- a/README.md +++ b/README.md @@ -88,7 +88,9 @@ const template = await client.createTemplate({ await template.waitUntilReady(); // 创建沙箱 -const sandbox = await client.createCodeInterpreterSandbox(template.templateName!); +const sandbox = await client.createCodeInterpreterSandbox( + template.templateName! +); await sandbox.waitUntilRunning(); // 执行代码 (需要数据 API 支持) @@ -101,12 +103,12 @@ await template.delete(); ## 模块 -| 模块 | 描述 | -|------|------| -| **AgentRuntime** | Agent 运行时管理 | -| **Credential** | 凭证管理 | -| **Model** | 模型服务和代理管理 | -| **Sandbox** | 沙箱环境管理 (代码解释器、浏览器) | +| 模块 | 描述 | +| ---------------- | --------------------------------- | +| **AgentRuntime** | Agent 运行时管理 | +| **Credential** | 凭证管理 | +| **Model** | 模型服务和代理管理 | +| **Sandbox** | 沙箱环境管理 (代码解释器、浏览器) | ## 示例 @@ -144,20 +146,23 @@ npm run build # 类型检查 npm run typecheck -# 代码检查 +# 代码检查和格式化 npm run lint npm run lint:fix +npm run format +npm run format:check +npm run format:fix # 同时运行格式化和lint修复 ``` ## 环境变量 -| 变量 | 描述 | 默认值 | -|------|------|--------| -| `AGENTRUN_ACCESS_KEY_ID` | 阿里云 Access Key ID | - | -| `AGENTRUN_ACCESS_KEY_SECRET` | 阿里云 Access Key Secret | - | -| `AGENTRUN_ACCOUNT_ID` | 阿里云账号 ID | - | -| `AGENTRUN_REGION` | 区域 ID | `cn-hangzhou` | -| `AGENTRUN_TIMEOUT` | API 超时时间 (毫秒) | `600000` | +| 变量 | 描述 | 默认值 | +| ---------------------------- | ------------------------ | ------------- | +| `AGENTRUN_ACCESS_KEY_ID` | 阿里云 Access Key ID | - | +| `AGENTRUN_ACCESS_KEY_SECRET` | 阿里云 Access Key Secret | - | +| `AGENTRUN_ACCOUNT_ID` | 阿里云账号 ID | - | +| `AGENTRUN_REGION` | 区域 ID | `cn-hangzhou` | +| `AGENTRUN_TIMEOUT` | API 超时时间 (毫秒) | `600000` | ## 兼容性 diff --git a/examples/agent-runtime.ts b/examples/agent-runtime.ts index 85e9754..23ef00c 100644 --- a/examples/agent-runtime.ts +++ b/examples/agent-runtime.ts @@ -121,7 +121,7 @@ async function createOrGetAgentRuntime(): Promise { log('等待删除完成 / Waiting for deletion to complete...'); let deleted = false; for (let i = 0; i < 30; i++) { - await new Promise((resolve) => setTimeout(resolve, 2000)); + await new Promise(resolve => setTimeout(resolve, 2000)); try { const runtimes = await client.list({ input: { agentRuntimeName } }); if (runtimes.length === 0) { @@ -168,8 +168,7 @@ async function createOrGetAgentRuntime(): Promise { // Wait for ready or failed log('等待就绪 / Waiting for ready...'); await ar.waitUntilReadyOrFailed({ - callback: (runtime) => - log(` 当前状态 / Current status: ${runtime.status}`), + callback: runtime => log(` 当前状态 / Current status: ${runtime.status}`), }); if (ar.status !== Status.READY) { @@ -197,8 +196,7 @@ async function updateAgentRuntime(ar: AgentRuntime): Promise { }); await ar.waitUntilReadyOrFailed({ - callback: (runtime) => - log(` 当前状态 / Current status: ${runtime.status}`), + callback: runtime => log(` 当前状态 / Current status: ${runtime.status}`), }); if (ar.status !== Status.READY) { @@ -218,7 +216,7 @@ async function listAgentRuntimes(): Promise { const runtimes = await AgentRuntime.listAll(); log( `共有 ${runtimes.length} 个资源 / Total ${runtimes.length} resources:`, - runtimes.map((r) => r.agentRuntimeName) + runtimes.map(r => r.agentRuntimeName) ); } @@ -235,8 +233,7 @@ async function deleteAgentRuntime(ar: AgentRuntime): Promise { log('等待删除完成 / Waiting for deletion...'); try { await ar.waitUntilReadyOrFailed({ - callback: (runtime) => - log(` 当前状态 / Current status: ${runtime.status}`), + callback: runtime => log(` 当前状态 / Current status: ${runtime.status}`), }); } catch (error) { // Expected to fail when resource is deleted @@ -248,9 +245,7 @@ async function deleteAgentRuntime(ar: AgentRuntime): Promise { log('资源仍然存在 / Resource still exists'); } catch (error) { if (error instanceof ResourceNotExistError) { - log( - '得到资源不存在报错,删除成功 / Resource not found, deletion successful' - ); + log('得到资源不存在报错,删除成功 / Resource not found, deletion successful'); } else { throw error; } diff --git a/examples/credential.ts b/examples/credential.ts index 401255f..5da421c 100644 --- a/examples/credential.ts +++ b/examples/credential.ts @@ -42,10 +42,9 @@ async function createOrGetCredential(): Promise { cred = await Credential.create({ input: { credentialName, - description: - '这是通过 Node.js SDK 创建的测试凭证 / Test credential created by Node.js SDK', + description: '这是通过 Node.js SDK 创建的测试凭证 / Test credential created by Node.js SDK', credentialConfig: CredentialConfig.inboundApiKey({ - apiKey: `sk-test-${Date.now()}` + apiKey: `sk-test-${Date.now()}`, }), }, }); @@ -86,7 +85,7 @@ async function listCredentials(): Promise { const credentials = await Credential.listAll(); log( `共有 ${credentials.length} 个资源 / Total ${credentials.length} resources:`, - credentials.map((c) => c.credentialName) + credentials.map(c => c.credentialName) ); } @@ -105,9 +104,7 @@ async function deleteCredential(cred: Credential): Promise { log('资源仍然存在 / Resource still exists'); } catch (error) { if (error instanceof ResourceNotExistError) { - log( - '得到资源不存在报错,删除成功 / Resource not found, deletion successful' - ); + log('得到资源不存在报错,删除成功 / Resource not found, deletion successful'); } else { throw error; } diff --git a/examples/mastra.ts b/examples/mastra.ts index 5a79581..4fc76f0 100644 --- a/examples/mastra.ts +++ b/examples/mastra.ts @@ -1,11 +1,6 @@ import { Agent } from '@mastra/core/agent'; import { AgentRunServer, type AgentRequest } from '../src/server'; -import { - MastraConverter, - type AgentEventItem, - model, - toolset, -} from '../src/integration/mastra'; +import { MastraConverter, type AgentEventItem, model, toolset } from '../src/integration/mastra'; import { logger } from '../src/utils/log'; @@ -21,18 +16,16 @@ const mastraAgent = new Agent({ tools: () => toolset({ name: 'start-mcp-time-ggda' }), }); -async function* invokeAgent( - request: AgentRequest, -): AsyncGenerator { +async function* invokeAgent(request: AgentRequest): AsyncGenerator { const converter = new MastraConverter(); const mastraStream = await mastraAgent.stream( request.messages.map( - (msg) => + msg => ({ role: msg.role, content: msg.content || '', - }) as any, - ), + }) as any + ) ); for await (const chunk of mastraStream.fullStream) { const events = converter.convert(chunk); diff --git a/examples/model.ts b/examples/model.ts index 71c987c..c7ac36d 100644 --- a/examples/model.ts +++ b/examples/model.ts @@ -13,8 +13,21 @@ * npm run example:model */ -import type { ModelProxyCreateInput, ModelServiceCreateInput, ProviderSettings, ProxyConfig } from '../src/index'; -import { ModelClient, ModelProxy, ModelService, ModelType, ResourceAlreadyExistError, ResourceNotExistError, Status } from '../src/index'; +import type { + ModelProxyCreateInput, + ModelServiceCreateInput, + ProviderSettings, + ProxyConfig, +} from '../src/index'; +import { + ModelClient, + ModelProxy, + ModelService, + ModelType, + ResourceAlreadyExistError, + ResourceNotExistError, + Status, +} from '../src/index'; import { Config } from '../src/utils/config'; import { logger } from '../src/utils/log'; @@ -68,8 +81,7 @@ async function createOrGetModelService(): Promise { // 等待就绪 / Wait for ready await ms.waitUntilReadyOrFailed({ - callback: (service) => - log(` 当前状态 / Current status: ${service.status}`), + callback: service => log(` 当前状态 / Current status: ${service.status}`), }); if (ms.status !== Status.READY) { @@ -114,12 +126,12 @@ async function listModelServices(): Promise { const services = await ModelService.list({ input: { - modelType: ModelType.LLM - } + modelType: ModelType.LLM, + }, }); log( `共有 ${services.length} 个资源,分别为 / Total ${services.length} resources:`, - services.map((s) => s.modelServiceName) + services.map(s => s.modelServiceName) ); } @@ -177,7 +189,7 @@ async function createOrGetModelProxy(): Promise { try { const cfg = new Config(); const proxyConfig: ProxyConfig = { - endpoints: MODEL_NAMES.map((modelName) => ({ + endpoints: MODEL_NAMES.map(modelName => ({ modelNames: [modelName], modelServiceName, })), @@ -204,8 +216,7 @@ async function createOrGetModelProxy(): Promise { // 等待就绪 / Wait for ready await mp.waitUntilReadyOrFailed({ - callback: (proxy) => - log(` 当前状态 / Current status: ${proxy.status}`), + callback: proxy => log(` 当前状态 / Current status: ${proxy.status}`), }); if (mp.status !== Status.READY) { @@ -253,7 +264,7 @@ async function listModelProxies(): Promise { const proxies = await ModelProxy.list({}); log( `共有 ${proxies.length} 个资源,分别为 / Total ${proxies.length} resources:`, - proxies.map((p) => p.modelProxyName) + proxies.map(p => p.modelProxyName) ); } @@ -313,7 +324,7 @@ async function main() { await listModelServices(); const ms = await createOrGetModelService(); await updateModelService(ms); - + await invokeModelService(ms); await listModelProxies(); diff --git a/examples/sandbox.ts b/examples/sandbox.ts index 993ca04..6369521 100644 --- a/examples/sandbox.ts +++ b/examples/sandbox.ts @@ -20,7 +20,7 @@ import { CodeLanguage, SandboxClient, Template, - TemplateType + TemplateType, } from '../src/index'; import { logger } from '../src/utils/log'; @@ -41,9 +41,7 @@ async function listTemplates(): Promise { log(`共有 ${templates.length} 个模板 / Total ${templates.length} templates:`); for (const template of templates) { - log( - ` - ${template.templateName} (${template.templateType}) [${template.status}]` - ); + log(` - ${template.templateName} (${template.templateType}) [${template.status}]`); } } @@ -79,7 +77,7 @@ async function codeInterpreterExample(): Promise { templateType: TemplateType.CODE_INTERPRETER, description: 'Test template from Node.js SDK', sandboxIdleTimeoutInSeconds: 600, - } + }, }); log(`✓ 创建模板成功 / Template created: ${template.templateName}`); @@ -89,21 +87,19 @@ async function codeInterpreterExample(): Promise { // 等待模板就绪 / Wait for template to be ready log('\n--- 等待模板就绪 / Waiting for template to be ready ---'); await template.waitUntilReadyOrFailed({ - callback: (t) => log(` 当前状态 / Current status: ${t.status}`), + callback: t => log(` 当前状态 / Current status: ${t.status}`), }); log('✓ 模板已就绪 / Template is ready'); // 创建沙箱 / Create sandbox - log( - '\n--- 创建 Code Interpreter 沙箱 / Creating Code Interpreter sandbox ---' - ); + log('\n--- 创建 Code Interpreter 沙箱 / Creating Code Interpreter sandbox ---'); const sandbox = await CodeInterpreterSandbox.createFromTemplate(templateName); log(`✓ 创建沙箱成功 / Sandbox created: ${sandbox.sandboxId}`); // 等待沙箱运行 / Wait for sandbox to be running log('\n--- 等待沙箱运行 / Waiting for sandbox to be running ---'); await sandbox.waitUntilRunning({ - beforeCheck: (s) => log(` 当前状态 / Current state: ${s.state}`), + beforeCheck: s => log(` 当前状态 / Current state: ${s.state}`), }); log('✓ 沙箱已运行 / Sandbox is running'); @@ -137,9 +133,7 @@ async function codeInterpreterExample(): Promise { log(`✓ 创建文件夹 /home/user/test / Created directory /home/user/test`); await sandbox.fileSystem.mkdir({ path: '/home/user/test-move' }); - log( - `✓ 创建文件夹 /home/user/test-move / Created directory /home/user/test-move` - ); + log(`✓ 创建文件夹 /home/user/test-move / Created directory /home/user/test-move`); // 测试上传下载 / Upload/Download test log('\n--- 测试上传下载 / Testing upload/download ---'); @@ -159,7 +153,7 @@ async function codeInterpreterExample(): Promise { log(`✓ 上传文件成功 / File uploaded successfully`); const filestat = await sandbox.fileSystem.stat({ - path: '/home/user/test-move/test_file.txt' + path: '/home/user/test-move/test_file.txt', }); log(`✓ 上传文件详情 / Uploaded file stat:`, filestat); @@ -172,12 +166,7 @@ async function codeInterpreterExample(): Promise { // 验证下载的文件内容 const downloadedContent = await fs.readFile(downloadPath, 'utf-8'); - log( - `✓ 验证下载文件内容 / Verify downloaded content: ${downloadedContent.slice( - 0, - 50 - )}...` - ); + log(`✓ 验证下载文件内容 / Verify downloaded content: ${downloadedContent.slice(0, 50)}...`); // 测试文件读写 / File read/write test log('\n--- 测试文件读写 / Testing file read/write ---'); @@ -199,7 +188,7 @@ async function codeInterpreterExample(): Promise { log(`✓ 移动文件成功 / File moved successfully`); const movedContent = await sandbox.file.read({ - path: '/home/user/test-move/test2.txt' + path: '/home/user/test-move/test2.txt', }); log(`✓ 读取移动后的文件 / Read moved file:`, movedContent); diff --git a/examples/toolset.ts b/examples/toolset.ts index 7deeafa..5fc0cd3 100644 --- a/examples/toolset.ts +++ b/examples/toolset.ts @@ -39,10 +39,9 @@ async function toolsetExample() { logger.info('Available Tools:', JSON.stringify(tools, null, 2)); // 调用工具 / Call tool - const result = await baiduToolset.callTool( - 'baidu_search', - { body: { search_input: '比特币价格' } } - ); + const result = await baiduToolset.callTool('baidu_search', { + body: { search_input: '比特币价格' }, + }); logger.info('Tool Result:', result); } catch (error) { logger.error('Error with Baidu Search Tool:', error); @@ -66,10 +65,7 @@ async function toolsetExample() { logger.info('Available Tools:', JSON.stringify(tools, null, 2)); // 调用工具 / Call tool - const result = await mcpToolset.callTool( - 'get_current_time', - { timezone: 'Asia/Shanghai' } - ); + const result = await mcpToolset.callTool('get_current_time', { timezone: 'Asia/Shanghai' }); logger.info('Tool Result:', result); } catch (error) { logger.error('Error with MCP Time Tool:', error); diff --git a/jest.config.js b/jest.config.js index 66aecaa..260c44e 100644 --- a/jest.config.js +++ b/jest.config.js @@ -55,4 +55,3 @@ export default { coverageDirectory: 'coverage', coverageReporters: ['text', 'lcov', 'json'], }; - diff --git a/package.json b/package.json index 83f35ba..5f212ff 100644 --- a/package.json +++ b/package.json @@ -58,17 +58,18 @@ "README.md" ], "scripts": { - "prebuild": "npm run generate-exports", - "build": "tsup", + "build": "node scripts/inject-version-check.mjs && tsup", "build:types": "tsc -p tsconfig.types.json", "codegen": "npx tsx scripts/codegen.ts", "generate-exports": "node scripts/generate-exports.mjs", - "format": "prettier --check \"src/**/*.{js,ts,jsx,tsx}\" --write", - "test": "jest", + "inject-version-check": "node scripts/inject-version-check.mjs", "test:watch": "jest --watch", "test:coverage": "jest --coverage", "lint": "eslint src --ext .ts", "lint:fix": "eslint src --ext .ts --fix", + "format": "prettier --write .", + "format:check": "prettier --check .", + "format:fix": "npm run format && npm run lint:fix", "typecheck": "tsc --noEmit", "prepublishOnly": "npm run build", "example:quick-start": "npx tsx examples/quick-start.ts", @@ -127,6 +128,7 @@ "@happy-dom/global-registrator": "^15.0.0", "@mastra/core": "^1.0.0", "@types/archiver": "^7.0.0", + "@types/express": "^5.0.6", "@types/jest": "^29.5.0", "@types/js-yaml": "^4.0.9", "@types/node": "^20.17.0", @@ -134,9 +136,12 @@ "@typescript-eslint/eslint-plugin": "^7.0.0", "@typescript-eslint/parser": "^7.0.0", "eslint": "^8.57.0", + "eslint-config-prettier": "^10.1.8", + "eslint-plugin-prettier": "^5.5.5", "jest": "^29.7.0", "jest-environment-node": "^29.7.0", "playwright": "^1.57.0", + "prettier": "^3.8.1", "ts-jest": "^29.2.0", "tsup": "^8.3.0", "tsx": "^4.19.0", diff --git a/scripts/check-coverage.ts b/scripts/check-coverage.ts index 0b3f3e7..9614035 100644 --- a/scripts/check-coverage.ts +++ b/scripts/check-coverage.ts @@ -121,7 +121,8 @@ function loadConfig(configPath: string): CoverageConfig { : undefined, incremental: override?.incremental ? { - branch_coverage: override.incremental.branch_coverage ?? incremental.branch_coverage, + branch_coverage: + override.incremental.branch_coverage ?? incremental.branch_coverage, line_coverage: override.incremental.line_coverage ?? incremental.line_coverage, } : undefined, @@ -145,7 +146,7 @@ function loadConfig(configPath: string): CoverageConfig { function getThresholdForDirectory( config: CoverageConfig, directory: string, - isIncremental = false, + isIncremental = false ): CoverageThreshold { const defaultThreshold = isIncremental ? config.incremental : config.full; @@ -189,7 +190,7 @@ function calculateFileCoverage(fileData: FileCoverageData): CoverageResult { // 计算语句覆盖率 / Calculate statement coverage const statements = Object.values(fileData.s); const totalStatements = statements.length; - const coveredStatements = statements.filter((hits) => hits > 0).length; + const coveredStatements = statements.filter(hits => hits > 0).length; // 计算分支覆盖率 / Calculate branch coverage // 每个 branchMap 条目可能有多个分支(如 if/else 有两个分支) @@ -217,7 +218,7 @@ function calculateFileCoverage(fileData: FileCoverageData): CoverageResult { function calculateCoverage( coverageData: CoverageFinalJson, - fileFilter?: (filePath: string) => boolean, + fileFilter?: (filePath: string) => boolean ): CoverageResult { let totalStatements = 0; let coveredStatements = 0; @@ -250,12 +251,12 @@ function calculateCoverage( function calculateDirectoryCoverage( coverageData: CoverageFinalJson, directory: string, - projectRoot: string, + projectRoot: string ): CoverageResult { // 将目录转换为绝对路径用于匹配 const dirAbsPath = path.join(projectRoot, directory); - return calculateCoverage(coverageData, (filePath) => filePath.startsWith(dirAbsPath)); + return calculateCoverage(coverageData, filePath => filePath.startsWith(dirAbsPath)); } function discoverDirectories(coverageData: CoverageFinalJson, projectRoot: string): string[] { @@ -281,7 +282,7 @@ function discoverDirectories(coverageData: CoverageFinalJson, projectRoot: strin function printCoverageReport( fullCoverage: CoverageResult, - directoryCoverages: Map, + directoryCoverages: Map ): void { console.log('\n' + '='.repeat(70)); console.log('📊 覆盖率报告 / Coverage Report'); @@ -289,15 +290,19 @@ function printCoverageReport( console.log('\n📈 全量代码覆盖率 / Full Coverage:'); console.log(` 行覆盖率 / Line Coverage: ${fullCoverage.lineCoverage.toFixed(2)}%`); - console.log(` (${fullCoverage.coveredStatements}/${fullCoverage.totalStatements} 语句)`); + console.log( + ` (${fullCoverage.coveredStatements}/${fullCoverage.totalStatements} 语句)` + ); console.log(` 分支覆盖率 / Branch Coverage: ${fullCoverage.branchCoverage.toFixed(2)}%`); - console.log(` (${fullCoverage.coveredBranches}/${fullCoverage.totalBranches} 分支)`); + console.log( + ` (${fullCoverage.coveredBranches}/${fullCoverage.totalBranches} 分支)` + ); if (directoryCoverages.size > 0) { console.log('\n📁 目录覆盖率 / Directory Coverage:'); console.log('-'.repeat(70)); console.log( - `${'目录 / Directory'.padEnd(35)} | ${'行覆盖率'.padStart(10)} | ${'分支覆盖率'.padStart(10)}`, + `${'目录 / Directory'.padEnd(35)} | ${'行覆盖率'.padStart(10)} | ${'分支覆盖率'.padStart(10)}` ); console.log('-'.repeat(70)); @@ -324,7 +329,7 @@ interface CheckResult { function checkCoverageThresholds( config: CoverageConfig, fullCoverage: CoverageResult, - directoryCoverages: Map, + directoryCoverages: Map ): CheckResult { const failures: string[] = []; @@ -339,7 +344,7 @@ function checkCoverageThresholds( failures.push(msg); } else { console.log( - ` ✅ 全量分支覆盖率 ${fullCoverage.branchCoverage.toFixed(2)}% >= ${fullThreshold.branch_coverage}%`, + ` ✅ 全量分支覆盖率 ${fullCoverage.branchCoverage.toFixed(2)}% >= ${fullThreshold.branch_coverage}%` ); } @@ -349,7 +354,7 @@ function checkCoverageThresholds( failures.push(msg); } else { console.log( - ` ✅ 全量行覆盖率 ${fullCoverage.lineCoverage.toFixed(2)}% >= ${fullThreshold.line_coverage}%`, + ` ✅ 全量行覆盖率 ${fullCoverage.lineCoverage.toFixed(2)}% >= ${fullThreshold.line_coverage}%` ); } @@ -363,7 +368,7 @@ function checkCoverageThresholds( failures.push(msg); } else { console.log( - ` ✅ ${directory} 分支覆盖率 ${coverage.branchCoverage.toFixed(2)}% >= ${dirThreshold.branch_coverage}%`, + ` ✅ ${directory} 分支覆盖率 ${coverage.branchCoverage.toFixed(2)}% >= ${dirThreshold.branch_coverage}%` ); } @@ -373,7 +378,7 @@ function checkCoverageThresholds( failures.push(msg); } else { console.log( - ` ✅ ${directory} 行覆盖率 ${coverage.lineCoverage.toFixed(2)}% >= ${dirThreshold.line_coverage}%`, + ` ✅ ${directory} 行覆盖率 ${coverage.lineCoverage.toFixed(2)}% >= ${dirThreshold.line_coverage}%` ); } } @@ -442,7 +447,7 @@ function main(): void { line_coverage: cov.lineCoverage, branch_coverage: cov.branchCoverage, }, - ]), + ]) ), }; console.log(JSON.stringify(result, null, 2)); diff --git a/scripts/codegen.ts b/scripts/codegen.ts index 7668fca..fbebb10 100644 --- a/scripts/codegen.ts +++ b/scripts/codegen.ts @@ -10,16 +10,16 @@ * Usage: bun run codegen */ -import * as fs from "fs"; -import * as path from "path"; -import * as yaml from "yaml"; +import * as fs from 'fs'; +import * as path from 'path'; +import * as yaml from 'yaml'; import { fileURLToPath } from 'node:url'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); -const projectRoot = path.resolve(__dirname, ".."); -const configsDir = path.join(projectRoot, "codegen", "configs"); +const projectRoot = path.resolve(__dirname, '..'); +const configsDir = path.join(projectRoot, 'codegen', 'configs'); const CODE_GEN_HINT = `/** * This file is auto generated by the code generation script. @@ -51,7 +51,7 @@ interface Config { outputPath: string; className: string; description: string; - sdkType?: "agentrun" | "devs"; // Which underlying SDK to use + sdkType?: 'agentrun' | 'devs'; // Which underlying SDK to use methods: Method[]; } @@ -68,13 +68,13 @@ function toCamelCase(str: string): string { function mapType(configType: string, sdkPrefix: string): string { // Basic type mappings (Python-style types in config -> TypeScript) const typeMap: Record = { - str: "string", - int: "number", - float: "number", - bool: "boolean", - string: "string", - number: "number", - boolean: "boolean", + str: 'string', + int: 'number', + float: 'number', + bool: 'boolean', + string: 'string', + number: 'number', + boolean: 'boolean', }; if (typeMap[configType]) { @@ -104,7 +104,7 @@ function mapReturnType(configType: string, sdkPrefix: string): string { */ function generateParamsType( method: Method, - sdkPrefix: string, + sdkPrefix: string ): { typeString: string; paramNames: string[] } { const paramDefs: string[] = []; const paramNames: string[] = []; @@ -112,17 +112,17 @@ function generateParamsType( for (const param of method.params) { const paramName = toCamelCase(param.name); const paramType = mapType(param.type, sdkPrefix); - const optionalMark = param.optional ? "?" : ""; + const optionalMark = param.optional ? '?' : ''; paramDefs.push(`${paramName}${optionalMark}: ${paramType}`); paramNames.push(paramName); } // Always add optional headers and config - paramDefs.push("headers?: Record"); - paramDefs.push("config?: Config"); + paramDefs.push('headers?: Record'); + paramDefs.push('config?: Config'); return { - typeString: `{ ${paramDefs.join("; ")} }`, + typeString: `{ ${paramDefs.join('; ')} }`, paramNames, }; } @@ -132,29 +132,25 @@ function generateParamsType( */ function generateControlApiCode(config: Config, source: string): string { const lines: string[] = []; - const sdkPrefix = config.sdkType === "devs" ? "$DevS" : "$AgentRun"; + const sdkPrefix = config.sdkType === 'devs' ? '$DevS' : '$AgentRun'; const sdkPackage = - config.sdkType === "devs" - ? "@alicloud/devs20230714" - : "@alicloud/agentrun20250910"; + config.sdkType === 'devs' ? '@alicloud/devs20230714' : '@alicloud/agentrun20250910'; // File header lines.push(CODE_GEN_HINT); - lines.push(""); + lines.push(''); lines.push(`// Source: ${source}`); - lines.push(""); + lines.push(''); // Imports lines.push(`import * as ${sdkPrefix} from "${sdkPackage}";`); lines.push(`import * as $Util from "@alicloud/tea-util";`); - lines.push(""); + lines.push(''); lines.push(`import { Config } from "../../utils/config";`); lines.push(`import { ControlAPI } from "../../utils/control-api";`); - lines.push( - `import { ClientError, ServerError } from "../../utils/exception";`, - ); + lines.push(`import { ClientError, ServerError } from "../../utils/exception";`); lines.push(`import { logger } from "../../utils/log";`); - lines.push(""); + lines.push(''); // Class definition lines.push(`/**`); @@ -164,7 +160,7 @@ function generateControlApiCode(config: Config, source: string): string { lines.push(` constructor(config?: Config) {`); lines.push(` super(config);`); lines.push(` }`); - lines.push(""); + lines.push(''); // Generate methods for (const method of config.methods) { @@ -173,10 +169,7 @@ function generateControlApiCode(config: Config, source: string): string { const apiMethodName = toCamelCase(apiName); // Generate params type - const { typeString: paramsType, paramNames } = generateParamsType( - method, - sdkPrefix, - ); + const { typeString: paramsType, paramNames } = generateParamsType(method, sdkPrefix); // Return type const returnType = mapReturnType(method.returnType, sdkPrefix); @@ -187,9 +180,7 @@ function generateControlApiCode(config: Config, source: string): string { lines.push(` *`); lines.push(` * @param params - Method parameters`); for (const param of method.params) { - lines.push( - ` * @param params.${toCamelCase(param.name)} - ${param.description}`, - ); + lines.push(` * @param params.${toCamelCase(param.name)} - ${param.description}`); } lines.push(` * @param params.headers - Custom request headers`); lines.push(` * @param params.config - Optional config override`); @@ -200,128 +191,115 @@ function generateControlApiCode(config: Config, source: string): string { lines.push(` ${methodName} = async (params: ${paramsType}): Promise<${returnType}> => {`); // Destructure params - const destructureList = [...paramNames, "headers", "config"]; - lines.push(` const { ${destructureList.join(", ")} } = params;`); - lines.push(""); + const destructureList = [...paramNames, 'headers', 'config']; + lines.push(` const { ${destructureList.join(', ')} } = params;`); + lines.push(''); // Method body lines.push(` try {`); lines.push(` const client = this.getClient(config);`); lines.push(` const runtime = new $Util.RuntimeOptions({});`); - lines.push(""); + lines.push(''); // Build request call const callParams: string[] = []; for (const param of method.params) { const paramName = toCamelCase(param.name); if (param.wrapperType) { - callParams.push( - `new ${sdkPrefix}.${param.wrapperType}({ body: ${paramName} })`, - ); - } else if ( - param.optional && - param.type.charAt(0) === param.type.charAt(0).toUpperCase() - ) { + callParams.push(`new ${sdkPrefix}.${param.wrapperType}({ body: ${paramName} })`); + } else if (param.optional && param.type.charAt(0) === param.type.charAt(0).toUpperCase()) { // Optional model type parameter - create empty object if undefined callParams.push(`${paramName} ?? new ${sdkPrefix}.${param.type}({})`); } else { callParams.push(paramName); } } - callParams.push("headers ?? {}"); - callParams.push("runtime"); + callParams.push('headers ?? {}'); + callParams.push('runtime'); - lines.push( - ` const response = await client.${apiMethodName}WithOptions(`, - ); + lines.push(` const response = await client.${apiMethodName}WithOptions(`); for (let i = 0; i < callParams.length; i++) { - const comma = i < callParams.length - 1 ? "," : ""; + const comma = i < callParams.length - 1 ? ',' : ''; lines.push(` ${callParams[i]}${comma}`); } lines.push(` );`); - lines.push(""); - + lines.push(''); + // Build request params array for logging const requestParamsList: string[] = []; for (const param of method.params) { const paramName = toCamelCase(param.name); requestParamsList.push(paramName); } - + lines.push(` logger.debug(`); lines.push( - ` \`request api ${apiMethodName}, request Request ID: \${response.body?.requestId}\\n request: \${JSON.stringify([${requestParamsList.join(", ")}])}\\n response: \${JSON.stringify(response.body?.data)}\`,`, + ` \`request api ${apiMethodName}, request Request ID: \${response.body?.requestId}\\n request: \${JSON.stringify([${requestParamsList.join(', ')}])}\\n response: \${JSON.stringify(response.body?.data)}\`,` ); lines.push(` );`); - lines.push(""); + lines.push(''); lines.push(` return response.body?.data as ${returnType};`); lines.push(` } catch (error: unknown) {`); + lines.push(` if (error && typeof error === "object" && "statusCode" in error) {`); lines.push( - ` if (error && typeof error === "object" && "statusCode" in error) {`, - ); - lines.push( - ` const e = error as { statusCode: number; message: string; data?: { requestId?: string } };`, + ` const e = error as { statusCode: number; message: string; data?: { requestId?: string } };` ); lines.push(` const statusCode = e.statusCode;`); lines.push(` const message = e.message || "Unknown error";`); lines.push(` const requestId = e.data?.requestId;`); - lines.push(""); + lines.push(''); lines.push(` if (statusCode >= 400 && statusCode < 500) {`); - lines.push( - ` throw new ClientError(statusCode, message, { requestId });`, - ); + lines.push(` throw new ClientError(statusCode, message, { requestId });`); lines.push(` } else if (statusCode >= 500) {`); - lines.push( - ` throw new ServerError(statusCode, message, { requestId });`, - ); + lines.push(` throw new ServerError(statusCode, message, { requestId });`); lines.push(` }`); lines.push(` }`); lines.push(` throw error;`); lines.push(` }`); lines.push(` };`); - lines.push(""); + lines.push(''); } lines.push(`}`); - lines.push(""); + lines.push(''); - return lines.join("\n"); + return lines.join('\n'); } /** * Main function */ function main(): void { - console.log("🚀 AgentRun SDK Code Generation"); - console.log("================================"); + console.log('🚀 AgentRun SDK Code Generation'); + console.log('================================'); console.log(`Project root: ${projectRoot}`); console.log(`Configs dir: ${configsDir}`); - console.log(""); + console.log(''); // Check if configs directory exists if (!fs.existsSync(configsDir)) { - console.log("❌ No configs directory found, skipping codegen"); + console.log('❌ No configs directory found, skipping codegen'); return; } // Process all YAML config files const configFiles = fs .readdirSync(configsDir) - .filter((f) => f.endsWith(".yaml") || f.endsWith(".yml")); + .filter(f => f.endsWith('.yaml') || f.endsWith('.yml')); if (configFiles.length === 0) { - console.log("❌ No YAML config files found"); + console.log('❌ No YAML config files found'); return; } console.log(`Found ${configFiles.length} config file(s)`); - console.log(""); + console.log(''); for (const configFile of configFiles) { const configPath = path.join(configsDir, configFile); console.log(`📄 Processing: ${configFile}`); - const configContent = fs.readFileSync(configPath, "utf-8"); + const configContent = fs.readFileSync(configPath, 'utf-8'); const config = yaml.parse(configContent) as Config; // Get output path directly from config (already in TypeScript format) @@ -338,12 +316,12 @@ function main(): void { const code = generateControlApiCode(config, configFile); // Write output - fs.writeFileSync(fullOutputPath, code, "utf-8"); + fs.writeFileSync(fullOutputPath, code, 'utf-8'); console.log(` ✅ Generated: ${outputPath}`); } - console.log(""); - console.log("✨ Code generation complete!"); + console.log(''); + console.log('✨ Code generation complete!'); } main(); diff --git a/scripts/generate-exports.mjs b/scripts/generate-exports.mjs index 553a86c..57905e9 100644 --- a/scripts/generate-exports.mjs +++ b/scripts/generate-exports.mjs @@ -70,15 +70,15 @@ function generateExports(modules) { '.': { types: './dist/index.d.ts', import: './dist/index.js', - require: './dist/index.cjs' - } + require: './dist/index.cjs', + }, }; for (const module of modules) { exports[`./${module}`] = { types: `./dist/${module}/index.d.ts`, import: `./dist/${module}/index.js`, - require: `./dist/${module}/index.cjs` + require: `./dist/${module}/index.cjs`, }; } @@ -112,4 +112,4 @@ function main() { } } -main(); \ No newline at end of file +main(); diff --git a/scripts/inject-version-check.mjs b/scripts/inject-version-check.mjs new file mode 100644 index 0000000..7eb7ed9 --- /dev/null +++ b/scripts/inject-version-check.mjs @@ -0,0 +1,130 @@ +#!/usr/bin/env node + +/** + * Auto-inject version check import into all index.ts files + * + * This script automatically scans the src directory for index.ts files + * and adds the version check import at the top of each file (after comments) + * + * Usage: node scripts/inject-version-check.mjs + */ + +import { readdirSync, statSync, readFileSync, writeFileSync } from 'fs'; +import { join, resolve, dirname } from 'path'; +import { fileURLToPath } from 'url'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +const projectRoot = resolve(__dirname, '..'); + +// 要注入的导入语句 +const VERSION_CHECK_IMPORT = 'import "@/utils/version-check";'; + +// 扫描 src 目录下的所有 index.ts 文件 +function getIndexFiles(srcDir) { + const indexFiles = []; + const basePath = resolve(srcDir); + + function scanDir(dir, relativePath = '') { + const items = readdirSync(dir); + + for (const item of items) { + const fullPath = join(dir, item); + const stat = statSync(fullPath); + + if (stat.isDirectory()) { + // 检查是否有 index.ts 文件 + const indexPath = join(fullPath, 'index.ts'); + try { + if (statSync(indexPath).isFile()) { + const filePath = relativePath ? `${relativePath}/${item}/index.ts` : `${item}/index.ts`; + indexFiles.push(join(srcDir, filePath)); + } + } catch { + // index.ts 不存在,继续递归扫描子目录 + } + + // 递归扫描子目录 + const newRelativePath = relativePath ? `${relativePath}/${item}` : item; + scanDir(fullPath, newRelativePath); + } + } + } + + // 总是包含根目录的 index.ts + indexFiles.unshift(join(srcDir, 'index.ts')); + + // 扫描 src 目录 + scanDir(basePath); + + return indexFiles; +} + +// 检查文件是否已经包含版本检查导入 +function hasVersionCheckImport(content) { + return content.includes('import "@/utils/version-check";') || + content.includes("import '@/utils/version-check';"); +} + +// 为文件添加版本检查导入 +function injectVersionCheck(filePath) { + const content = readFileSync(filePath, 'utf-8'); + + // 如果已经包含了导入,跳过 + if (hasVersionCheckImport(content)) { + console.log(`✓ ${filePath} already has version check import`); + return false; + } + + const lines = content.split('\n'); + let insertIndex = 0; + + // 找到第一个非注释行 + for (let i = 0; i < lines.length; i++) { + const line = lines[i].trim(); + // 如果是空行、注释行或 JSDoc 注释,继续 + if (line === '' || + line.startsWith('//') || + line.startsWith('/*') || + line.startsWith('*') || + line.startsWith('*/') || + line.startsWith('/**')) { + continue; + } + // 找到第一个代码行 + insertIndex = i; + break; + } + + // 在第一个代码行之前插入导入 + lines.splice(insertIndex, 0, '', VERSION_CHECK_IMPORT, ''); + + const newContent = lines.join('\n'); + writeFileSync(filePath, newContent, 'utf-8'); + + console.log(`✓ Injected version check import into ${filePath}`); + return true; +} + +// 主函数 +function main() { + console.log('🔍 Scanning for index.ts files...'); + + const indexFiles = getIndexFiles('src'); + console.log(`📁 Found ${indexFiles.length} index.ts files:`); + indexFiles.forEach(file => console.log(` - ${file}`)); + + console.log('\n🔧 Injecting version check imports...'); + + let injectedCount = 0; + for (const filePath of indexFiles) { + if (injectVersionCheck(filePath)) { + injectedCount++; + } + } + + console.log(`\n✅ Done! Injected version check into ${injectedCount} files.`); +} + +// 运行主函数 +main(); diff --git a/src/agent-runtime/api/control.ts b/src/agent-runtime/api/control.ts index 3394df2..be4c321 100644 --- a/src/agent-runtime/api/control.ts +++ b/src/agent-runtime/api/control.ts @@ -9,13 +9,13 @@ // Source: agent_runtime_control_api.yaml -import * as $AgentRun from "@alicloud/agentrun20250910"; -import * as $Util from "@alicloud/tea-util"; +import * as $AgentRun from '@alicloud/agentrun20250910'; +import * as $Util from '@alicloud/tea-util'; -import { Config } from "../../utils/config"; -import { ControlAPI } from "../../utils/control-api"; -import { ClientError, ServerError } from "../../utils/exception"; -import { logger } from "../../utils/log"; +import { Config } from '../../utils/config'; +import { ControlAPI } from '../../utils/control-api'; +import { ClientError, ServerError } from '../../utils/exception'; +import { logger } from '../../utils/log'; /** * Agent Runtime Control API @@ -34,7 +34,11 @@ export class AgentRuntimeControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns Created Runtime object */ - createAgentRuntime = async (params: { input: $AgentRun.CreateAgentRuntimeInput; headers?: Record; config?: Config }): Promise<$AgentRun.AgentRuntime> => { + createAgentRuntime = async (params: { + input: $AgentRun.CreateAgentRuntimeInput; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.AgentRuntime> => { const { input, headers, config } = params; try { @@ -48,15 +52,15 @@ export class AgentRuntimeControlAPI extends ControlAPI { ); logger.debug( - `request api createAgentRuntime, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([input])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api createAgentRuntime, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([input])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.AgentRuntime; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -78,29 +82,29 @@ export class AgentRuntimeControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns Deleted Runtime object */ - deleteAgentRuntime = async (params: { agentId: string; headers?: Record; config?: Config }): Promise<$AgentRun.AgentRuntime> => { + deleteAgentRuntime = async (params: { + agentId: string; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.AgentRuntime> => { const { agentId, headers, config } = params; try { const client = this.getClient(config); const runtime = new $Util.RuntimeOptions({}); - const response = await client.deleteAgentRuntimeWithOptions( - agentId, - headers ?? {}, - runtime - ); + const response = await client.deleteAgentRuntimeWithOptions(agentId, headers ?? {}, runtime); logger.debug( - `request api deleteAgentRuntime, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([agentId])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api deleteAgentRuntime, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([agentId])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.AgentRuntime; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -123,7 +127,12 @@ export class AgentRuntimeControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns Updated Runtime object */ - updateAgentRuntime = async (params: { agentId: string; input: $AgentRun.UpdateAgentRuntimeInput; headers?: Record; config?: Config }): Promise<$AgentRun.AgentRuntime> => { + updateAgentRuntime = async (params: { + agentId: string; + input: $AgentRun.UpdateAgentRuntimeInput; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.AgentRuntime> => { const { agentId, input, headers, config } = params; try { @@ -138,15 +147,15 @@ export class AgentRuntimeControlAPI extends ControlAPI { ); logger.debug( - `request api updateAgentRuntime, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([agentId, input])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api updateAgentRuntime, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([agentId, input])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.AgentRuntime; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -169,7 +178,12 @@ export class AgentRuntimeControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns Runtime object */ - getAgentRuntime = async (params: { agentId: string; request?: $AgentRun.GetAgentRuntimeRequest; headers?: Record; config?: Config }): Promise<$AgentRun.AgentRuntime> => { + getAgentRuntime = async (params: { + agentId: string; + request?: $AgentRun.GetAgentRuntimeRequest; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.AgentRuntime> => { const { agentId, request, headers, config } = params; try { @@ -184,15 +198,15 @@ export class AgentRuntimeControlAPI extends ControlAPI { ); logger.debug( - `request api getAgentRuntime, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([agentId, request])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api getAgentRuntime, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([agentId, request])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.AgentRuntime; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -214,29 +228,29 @@ export class AgentRuntimeControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns List of Runtime objects */ - listAgentRuntimes = async (params: { input: $AgentRun.ListAgentRuntimesRequest; headers?: Record; config?: Config }): Promise<$AgentRun.ListAgentRuntimesOutput> => { + listAgentRuntimes = async (params: { + input: $AgentRun.ListAgentRuntimesRequest; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.ListAgentRuntimesOutput> => { const { input, headers, config } = params; try { const client = this.getClient(config); const runtime = new $Util.RuntimeOptions({}); - const response = await client.listAgentRuntimesWithOptions( - input, - headers ?? {}, - runtime - ); + const response = await client.listAgentRuntimesWithOptions(input, headers ?? {}, runtime); logger.debug( - `request api listAgentRuntimes, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([input])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api listAgentRuntimes, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([input])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.ListAgentRuntimesOutput; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -259,7 +273,12 @@ export class AgentRuntimeControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns Created Endpoint object */ - createAgentRuntimeEndpoint = async (params: { agentId: string; input: $AgentRun.CreateAgentRuntimeEndpointInput; headers?: Record; config?: Config }): Promise<$AgentRun.AgentRuntimeEndpoint> => { + createAgentRuntimeEndpoint = async (params: { + agentId: string; + input: $AgentRun.CreateAgentRuntimeEndpointInput; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.AgentRuntimeEndpoint> => { const { agentId, input, headers, config } = params; try { @@ -274,15 +293,15 @@ export class AgentRuntimeControlAPI extends ControlAPI { ); logger.debug( - `request api createAgentRuntimeEndpoint, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([agentId, input])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api createAgentRuntimeEndpoint, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([agentId, input])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.AgentRuntimeEndpoint; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -305,7 +324,12 @@ export class AgentRuntimeControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns Deleted Endpoint object */ - deleteAgentRuntimeEndpoint = async (params: { agentId: string; endpointId: string; headers?: Record; config?: Config }): Promise<$AgentRun.AgentRuntimeEndpoint> => { + deleteAgentRuntimeEndpoint = async (params: { + agentId: string; + endpointId: string; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.AgentRuntimeEndpoint> => { const { agentId, endpointId, headers, config } = params; try { @@ -320,15 +344,15 @@ export class AgentRuntimeControlAPI extends ControlAPI { ); logger.debug( - `request api deleteAgentRuntimeEndpoint, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([agentId, endpointId])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api deleteAgentRuntimeEndpoint, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([agentId, endpointId])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.AgentRuntimeEndpoint; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -352,7 +376,13 @@ export class AgentRuntimeControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns Updated Endpoint object */ - updateAgentRuntimeEndpoint = async (params: { agentId: string; endpointId: string; input: $AgentRun.UpdateAgentRuntimeEndpointInput; headers?: Record; config?: Config }): Promise<$AgentRun.AgentRuntimeEndpoint> => { + updateAgentRuntimeEndpoint = async (params: { + agentId: string; + endpointId: string; + input: $AgentRun.UpdateAgentRuntimeEndpointInput; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.AgentRuntimeEndpoint> => { const { agentId, endpointId, input, headers, config } = params; try { @@ -368,15 +398,15 @@ export class AgentRuntimeControlAPI extends ControlAPI { ); logger.debug( - `request api updateAgentRuntimeEndpoint, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([agentId, endpointId, input])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api updateAgentRuntimeEndpoint, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([agentId, endpointId, input])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.AgentRuntimeEndpoint; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -399,7 +429,12 @@ export class AgentRuntimeControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns Endpoint object */ - getAgentRuntimeEndpoint = async (params: { agentId: string; endpointId: string; headers?: Record; config?: Config }): Promise<$AgentRun.AgentRuntimeEndpoint> => { + getAgentRuntimeEndpoint = async (params: { + agentId: string; + endpointId: string; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.AgentRuntimeEndpoint> => { const { agentId, endpointId, headers, config } = params; try { @@ -414,15 +449,15 @@ export class AgentRuntimeControlAPI extends ControlAPI { ); logger.debug( - `request api getAgentRuntimeEndpoint, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([agentId, endpointId])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api getAgentRuntimeEndpoint, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([agentId, endpointId])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.AgentRuntimeEndpoint; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -445,7 +480,12 @@ export class AgentRuntimeControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns List of Endpoint objects */ - listAgentRuntimeEndpoints = async (params: { agentId: string; input: $AgentRun.ListAgentRuntimeEndpointsRequest; headers?: Record; config?: Config }): Promise<$AgentRun.ListAgentRuntimeEndpointsOutput> => { + listAgentRuntimeEndpoints = async (params: { + agentId: string; + input: $AgentRun.ListAgentRuntimeEndpointsRequest; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.ListAgentRuntimeEndpointsOutput> => { const { agentId, input, headers, config } = params; try { @@ -460,15 +500,15 @@ export class AgentRuntimeControlAPI extends ControlAPI { ); logger.debug( - `request api listAgentRuntimeEndpoints, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([agentId, input])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api listAgentRuntimeEndpoints, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([agentId, input])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.ListAgentRuntimeEndpointsOutput; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -491,7 +531,12 @@ export class AgentRuntimeControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns List of Version objects */ - listAgentRuntimeVersions = async (params: { agentId: string; input: $AgentRun.ListAgentRuntimeVersionsRequest; headers?: Record; config?: Config }): Promise<$AgentRun.ListAgentRuntimeVersionsOutput> => { + listAgentRuntimeVersions = async (params: { + agentId: string; + input: $AgentRun.ListAgentRuntimeVersionsRequest; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.ListAgentRuntimeVersionsOutput> => { const { agentId, input, headers, config } = params; try { @@ -506,15 +551,15 @@ export class AgentRuntimeControlAPI extends ControlAPI { ); logger.debug( - `request api listAgentRuntimeVersions, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([agentId, input])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api listAgentRuntimeVersions, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([agentId, input])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.ListAgentRuntimeVersionsOutput; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -526,5 +571,4 @@ export class AgentRuntimeControlAPI extends ControlAPI { throw error; } }; - } diff --git a/src/agent-runtime/api/data.ts b/src/agent-runtime/api/data.ts index 7316dad..2b0645e 100644 --- a/src/agent-runtime/api/data.ts +++ b/src/agent-runtime/api/data.ts @@ -5,9 +5,9 @@ * This module defines the Data API for Agent Runtime, used to invoke Agent Runtime instances. */ -import type { ChatCompletionMessageParam } from "openai/resources"; -import { Config } from "../../utils/config"; -import { DataAPI, ResourceType } from "../../utils/data-api"; +import type { ChatCompletionMessageParam } from 'openai/resources'; +import { Config } from '../../utils/config'; +import { DataAPI, ResourceType } from '../../utils/data-api'; /** * Invoke arguments for OpenAI-compatible API @@ -27,14 +27,14 @@ export interface InvokeArgs { export class AgentRuntimeDataAPI extends DataAPI { constructor( agentRuntimeName: string, - agentRuntimeEndpointName: string = "Default", - config?: Config, + agentRuntimeEndpointName: string = 'Default', + config?: Config ) { super( agentRuntimeName, ResourceType.Runtime, config, - `agent-runtimes/${agentRuntimeName}/endpoints/${agentRuntimeEndpointName}/invocations`, + `agent-runtimes/${agentRuntimeName}/endpoints/${agentRuntimeEndpointName}/invocations` ); } @@ -46,17 +46,17 @@ export class AgentRuntimeDataAPI extends DataAPI { // Merge configs const cfg = Config.withConfigs(this.getConfig(), config); - const apiBase = this.withPath("openai/v1"); + const apiBase = this.withPath('openai/v1'); // Get authenticated headers const [, headers] = await this.getAuthHeaders(apiBase, {}, cfg); // Use dynamic import to avoid bundling OpenAI SDK if not used - const { default: OpenAI } = await import("openai"); + const { default: OpenAI } = await import('openai'); // Create OpenAI client with custom base URL and auth headers const client = new OpenAI({ - apiKey: "", // Empty API key, we use custom headers for auth + apiKey: '', // Empty API key, we use custom headers for auth baseURL: apiBase, defaultHeaders: headers, timeout: cfg.timeout, @@ -81,14 +81,9 @@ export class AgentRuntimeDataAPI extends DataAPI { private async getAuthHeaders( url: string, headers: Record, - config?: Config, + config?: Config ): Promise<[string, Record]> { - const [authUrl, authHeaders] = await (this as any).auth( - url, - headers, - undefined, - config, - ); + const [authUrl, authHeaders] = await (this as any).auth(url, headers, undefined, config); return [authUrl, authHeaders]; } } diff --git a/src/agent-runtime/api/index.ts b/src/agent-runtime/api/index.ts index 4dd5dc7..f8b0c79 100644 --- a/src/agent-runtime/api/index.ts +++ b/src/agent-runtime/api/index.ts @@ -2,4 +2,6 @@ * Agent Runtime API exports */ -export { AgentRuntimeControlAPI } from "./control"; +import '@/utils/version-check'; + +export { AgentRuntimeControlAPI } from './control'; diff --git a/src/agent-runtime/client.ts b/src/agent-runtime/client.ts index ca01370..5d2132a 100644 --- a/src/agent-runtime/client.ts +++ b/src/agent-runtime/client.ts @@ -64,9 +64,7 @@ export class AgentRuntimeClient { } else if (input.containerConfiguration) { input.artifactType = AgentRuntimeArtifact.CONTAINER; } else { - throw new Error( - 'Either codeConfiguration or containerConfiguration must be provided' - ); + throw new Error('Either codeConfiguration or containerConfiguration must be provided'); } } @@ -85,8 +83,7 @@ export class AgentRuntimeClient { : undefined, networkConfiguration: input.networkConfiguration ? new $AgentRun.NetworkConfiguration({ - networkMode: - input.networkConfiguration.networkMode || NetworkMode.PUBLIC, + networkMode: input.networkConfiguration.networkMode || NetworkMode.PUBLIC, securityGroupId: input.networkConfiguration.securityGroupId, vpcId: input.networkConfiguration.vpcId, vswitchIds: input.networkConfiguration.vSwitchIds, @@ -108,10 +105,7 @@ export class AgentRuntimeClient { /** * Delete an Agent Runtime */ - delete = async (params: { - id: string; - config?: Config; - }): Promise => { + delete = async (params: { id: string; config?: Config }): Promise => { const { id, config } = params; const cfg = Config.withConfigs(this.config, config); @@ -131,7 +125,7 @@ export class AgentRuntimeClient { config: cfg, }); while (remaining.length > 0) { - await new Promise((resolve) => setTimeout(resolve, 1000)); + await new Promise(resolve => setTimeout(resolve, 1000)); remaining = await this.listEndpoints({ agentRuntimeId: id, config: cfg, @@ -194,10 +188,7 @@ export class AgentRuntimeClient { /** * Get an Agent Runtime */ - get = async (params: { - id: string; - config?: Config; - }): Promise => { + get = async (params: { id: string; config?: Config }): Promise => { const { id, config } = params; const cfg = Config.withConfigs(this.config, config); @@ -231,7 +222,7 @@ export class AgentRuntimeClient { input: request, config: cfg, }); - return (result.items || []).map((item) => new AgentRuntime(item, cfg)); + return (result.items || []).map(item => new AgentRuntime(item, cfg)); }; // /** @@ -305,10 +296,7 @@ export class AgentRuntimeClient { return new AgentRuntimeEndpoint(result, cfg); } catch (error) { if (error instanceof HTTPError) { - throw error.toResourceError( - 'AgentRuntimeEndpoint', - `${agentRuntimeId}/${endpointId}` - ); + throw error.toResourceError('AgentRuntimeEndpoint', `${agentRuntimeId}/${endpointId}`); } throw error; } @@ -338,10 +326,7 @@ export class AgentRuntimeClient { return new AgentRuntimeEndpoint(result, cfg); } catch (error) { if (error instanceof HTTPError) { - throw error.toResourceError( - 'AgentRuntimeEndpoint', - `${agentRuntimeId}/${endpointId}` - ); + throw error.toResourceError('AgentRuntimeEndpoint', `${agentRuntimeId}/${endpointId}`); } throw error; } @@ -367,10 +352,7 @@ export class AgentRuntimeClient { return new AgentRuntimeEndpoint(result, cfg); } catch (error) { if (error instanceof HTTPError) { - throw error.toResourceError( - 'AgentRuntimeEndpoint', - `${agentRuntimeId}/${endpointId}` - ); + throw error.toResourceError('AgentRuntimeEndpoint', `${agentRuntimeId}/${endpointId}`); } throw error; } @@ -396,9 +378,7 @@ export class AgentRuntimeClient { input: request, config: cfg, }); - return (result.items || []).map( - (item) => new AgentRuntimeEndpoint(item, cfg) - ); + return (result.items || []).map(item => new AgentRuntimeEndpoint(item, cfg)); } catch (error) { if (error instanceof HTTPError) { throw error.toResourceError('AgentRuntime', agentRuntimeId); @@ -455,7 +435,7 @@ export class AgentRuntimeClient { // Deduplicate const seen = new Set(); - return versions.filter((v) => { + return versions.filter(v => { if (!v.agentRuntimeVersion || seen.has(v.agentRuntimeVersion)) { return false; } @@ -501,11 +481,7 @@ export class AgentRuntimeClient { const cfg = Config.withConfigs(this.config, config); // Create Data API client - const dataApi = new AgentRuntimeDataAPI( - agentRuntimeName, - agentRuntimeEndpointName, - cfg - ); + const dataApi = new AgentRuntimeDataAPI(agentRuntimeName, agentRuntimeEndpointName, cfg); return dataApi.invokeOpenai({ messages, diff --git a/src/agent-runtime/endpoint.ts b/src/agent-runtime/endpoint.ts index dfdb884..514070b 100644 --- a/src/agent-runtime/endpoint.ts +++ b/src/agent-runtime/endpoint.ts @@ -6,11 +6,7 @@ */ import { Config } from '../utils/config'; -import { - listAllResourcesFunction, - ResourceBase, - updateObjectProperties, -} from '../utils/resource'; +import { listAllResourcesFunction, ResourceBase, updateObjectProperties } from '../utils/resource'; import { PageableInput, Status } from '../utils/model'; import { AgentRuntimeDataAPI, InvokeArgs } from './api/data'; @@ -26,10 +22,7 @@ import { KeyOf } from 'zod/v4/core/util.cjs'; /** * Agent Runtime Endpoint resource class */ -export class AgentRuntimeEndpoint - extends ResourceBase - implements AgentRuntimeEndpointData -{ +export class AgentRuntimeEndpoint extends ResourceBase implements AgentRuntimeEndpointData { // System properties agentRuntimeEndpointArn?: string; agentRuntimeEndpointId?: string; @@ -171,9 +164,7 @@ export class AgentRuntimeEndpoint /** * Delete this endpoint */ - delete = async (params?: { - config?: Config; - }): Promise => { + delete = async (params?: { config?: Config }): Promise => { const config = params?.config; if (!this.agentRuntimeId || !this.agentRuntimeEndpointId) { throw new Error( @@ -219,9 +210,7 @@ export class AgentRuntimeEndpoint /** * Refresh this endpoint's data */ - refresh = async (params?: { - config?: Config; - }): Promise => { + refresh = async (params?: { config?: Config }): Promise => { const config = params?.config; if (!this.agentRuntimeId || !this.agentRuntimeEndpointId) { throw new Error( @@ -279,9 +268,7 @@ export class AgentRuntimeEndpoint } if (!this._agentRuntimeName) { - throw new Error( - 'Unable to determine agent runtime name for this endpoint' - ); + throw new Error('Unable to determine agent runtime name for this endpoint'); } this._dataApi = new AgentRuntimeDataAPI( diff --git a/src/agent-runtime/index.ts b/src/agent-runtime/index.ts index 89b07a2..9d8319c 100644 --- a/src/agent-runtime/index.ts +++ b/src/agent-runtime/index.ts @@ -2,11 +2,13 @@ * Agent Runtime module exports */ -export { AgentRuntimeClient } from "./client"; -export { AgentRuntime } from "./runtime"; -export { AgentRuntimeEndpoint } from "./endpoint"; -export { AgentRuntimeControlAPI } from "./api/control"; -export { AgentRuntimeDataAPI } from "./api/data"; +import '@/utils/version-check'; + +export { AgentRuntimeClient } from './client'; +export { AgentRuntime } from './runtime'; +export { AgentRuntimeEndpoint } from './endpoint'; +export { AgentRuntimeControlAPI } from './api/control'; +export { AgentRuntimeDataAPI } from './api/data'; export { AgentRuntimeArtifact, @@ -15,7 +17,7 @@ export { codeFromFile, codeFromOss, codeFromZipFile, -} from "./model"; +} from './model'; export type { AgentRuntimeCode, @@ -35,6 +37,6 @@ export type { AgentRuntimeVersionListInput, AgentRuntimeData, AgentRuntimeEndpointData, -} from "./model"; +} from './model'; -export type { InvokeArgs } from "./api/data"; +export type { InvokeArgs } from './api/data'; diff --git a/src/agent-runtime/model.ts b/src/agent-runtime/model.ts index 6507960..c5ee34c 100644 --- a/src/agent-runtime/model.ts +++ b/src/agent-runtime/model.ts @@ -5,51 +5,51 @@ * This module defines all data models, enums, and input/output objects related to Agent Runtime. */ -import * as fs from "fs"; -import * as path from "path"; -import * as crc64Lib from "crc64-ecma182.js"; +import * as fs from 'fs'; +import * as path from 'path'; +import * as crc64Lib from 'crc64-ecma182.js'; -import { Status } from "../utils/model"; -import type { NetworkConfig, PageableInput } from "../utils/model"; +import { Status } from '../utils/model'; +import type { NetworkConfig, PageableInput } from '../utils/model'; /** * Agent Runtime artifact type */ -export type AgentRuntimeArtifact = "Code" | "Container"; +export type AgentRuntimeArtifact = 'Code' | 'Container'; export const AgentRuntimeArtifact = { - CODE: "Code" as AgentRuntimeArtifact, - CONTAINER: "Container" as AgentRuntimeArtifact, + CODE: 'Code' as AgentRuntimeArtifact, + CONTAINER: 'Container' as AgentRuntimeArtifact, }; /** * Agent Runtime language */ export type AgentRuntimeLanguage = - | "python3.10" - | "python3.12" - | "nodejs18" - | "nodejs20" - | "java8" - | "java11"; + | 'python3.10' + | 'python3.12' + | 'nodejs18' + | 'nodejs20' + | 'java8' + | 'java11'; export const AgentRuntimeLanguage = { - PYTHON310: "python3.10" as AgentRuntimeLanguage, - PYTHON312: "python3.12" as AgentRuntimeLanguage, - NODEJS18: "nodejs18" as AgentRuntimeLanguage, - NODEJS20: "nodejs20" as AgentRuntimeLanguage, - JAVA8: "java8" as AgentRuntimeLanguage, - JAVA11: "java11" as AgentRuntimeLanguage, + PYTHON310: 'python3.10' as AgentRuntimeLanguage, + PYTHON312: 'python3.12' as AgentRuntimeLanguage, + NODEJS18: 'nodejs18' as AgentRuntimeLanguage, + NODEJS20: 'nodejs20' as AgentRuntimeLanguage, + JAVA8: 'java8' as AgentRuntimeLanguage, + JAVA11: 'java11' as AgentRuntimeLanguage, }; /** * Agent Runtime protocol type */ -export type AgentRuntimeProtocolType = "HTTP" | "MCP"; +export type AgentRuntimeProtocolType = 'HTTP' | 'MCP'; export const AgentRuntimeProtocolType = { - HTTP: "HTTP" as AgentRuntimeProtocolType, - MCP: "MCP" as AgentRuntimeProtocolType, + HTTP: 'HTTP' as AgentRuntimeProtocolType, + MCP: 'MCP' as AgentRuntimeProtocolType, }; /** @@ -76,7 +76,7 @@ export interface AgentRuntimeCode { export async function codeFromZipFile( language: AgentRuntimeLanguage, command: string[], - zipFilePath: string, + zipFilePath: string ): Promise { const data = await fs.promises.readFile(zipFilePath); @@ -86,7 +86,7 @@ export async function codeFromZipFile( return { language, command, - zipFile: data.toString("base64"), + zipFile: data.toString('base64'), checksum: checksum, }; } @@ -98,7 +98,7 @@ export function codeFromOss( language: AgentRuntimeLanguage, command: string[], bucket: string, - object: string, + object: string ): AgentRuntimeCode { return { language, @@ -114,13 +114,13 @@ export function codeFromOss( export async function codeFromFile( language: AgentRuntimeLanguage, command: string[], - filePath: string, + filePath: string ): Promise { - const archiver = await import("archiver").catch(() => null); + const archiver = await import('archiver').catch(() => null); if (!archiver) { throw new Error( - "archiver package is required for codeFromFile. Install it with: npm install archiver", + 'archiver package is required for codeFromFile. Install it with: npm install archiver' ); } @@ -129,11 +129,11 @@ export async function codeFromFile( // Create ZIP archive const output = fs.createWriteStream(zipFilePath); - const archive = archiver.default("zip", { zlib: { level: 9 } }); + const archive = archiver.default('zip', { zlib: { level: 9 } }); await new Promise((resolve, reject) => { - output.on("close", resolve); - archive.on("error", reject); + output.on('close', resolve); + archive.on('error', reject); archive.pipe(output); if (stats.isDirectory()) { diff --git a/src/agent-runtime/runtime.ts b/src/agent-runtime/runtime.ts index 4bd37d6..a921e7f 100644 --- a/src/agent-runtime/runtime.ts +++ b/src/agent-runtime/runtime.ts @@ -7,11 +7,7 @@ import { Config } from '../utils/config'; import { Status } from '../utils/model'; -import { - listAllResourcesFunction, - ResourceBase, - updateObjectProperties, -} from '../utils/resource'; +import { listAllResourcesFunction, ResourceBase, updateObjectProperties } from '../utils/resource'; import type { NetworkConfig } from '../utils/model'; import { AgentRuntimeDataAPI, InvokeArgs } from './api/data'; @@ -98,10 +94,7 @@ export class AgentRuntime extends ResourceBase implements AgentRuntimeData { /** * Delete an Agent Runtime by ID */ - static async delete(params: { - id: string; - config?: Config; - }): Promise { + static async delete(params: { id: string; config?: Config }): Promise { const { id, config } = params; return await AgentRuntime.getClient().delete({ id, config }); } @@ -121,10 +114,7 @@ export class AgentRuntime extends ResourceBase implements AgentRuntimeData { /** * Get an Agent Runtime by ID */ - static async get(params: { - id: string; - config?: Config; - }): Promise { + static async get(params: { id: string; config?: Config }): Promise { const { id, config } = params; return await AgentRuntime.getClient().get({ id, config }); } @@ -291,9 +281,7 @@ export class AgentRuntime extends ResourceBase implements AgentRuntimeData { /** * List endpoints of this runtime */ - listEndpoints = async (params?: { - config?: Config; - }): Promise => { + listEndpoints = async (params?: { config?: Config }): Promise => { const config = params?.config; if (!this.agentRuntimeId) { throw new Error('agentRuntimeId is required to list endpoints'); @@ -308,9 +296,7 @@ export class AgentRuntime extends ResourceBase implements AgentRuntimeData { /** * List versions of this runtime */ - listVersions = async (params?: { - config?: Config; - }): Promise => { + listVersions = async (params?: { config?: Config }): Promise => { const config = params?.config; if (!this.agentRuntimeId) { throw new Error('agentRuntimeId is required to list versions'); @@ -322,7 +308,6 @@ export class AgentRuntime extends ResourceBase implements AgentRuntimeData { }); }; - /** * Invoke agent runtime using OpenAI-compatible API * @@ -342,15 +327,8 @@ export class AgentRuntime extends ResourceBase implements AgentRuntimeData { * }); * ``` */ - invokeOpenai = async ( - args: InvokeArgs & { agentRuntimeEndpointName?: string } - ) => { - const { - agentRuntimeEndpointName = 'Default', - messages, - stream, - config, - } = args; + invokeOpenai = async (args: InvokeArgs & { agentRuntimeEndpointName?: string }) => { + const { agentRuntimeEndpointName = 'Default', messages, stream, config } = args; if (!this.agentRuntimeName) { throw new Error('agentRuntimeName is required to invoke OpenAI'); diff --git a/src/credential/api/control.ts b/src/credential/api/control.ts index 29e335a..128ed11 100644 --- a/src/credential/api/control.ts +++ b/src/credential/api/control.ts @@ -9,13 +9,13 @@ // Source: credential_control_api.yaml -import * as $AgentRun from "@alicloud/agentrun20250910"; -import * as $Util from "@alicloud/tea-util"; +import * as $AgentRun from '@alicloud/agentrun20250910'; +import * as $Util from '@alicloud/tea-util'; -import { Config } from "../../utils/config"; -import { ControlAPI } from "../../utils/control-api"; -import { ClientError, ServerError } from "../../utils/exception"; -import { logger } from "../../utils/log"; +import { Config } from '../../utils/config'; +import { ControlAPI } from '../../utils/control-api'; +import { ClientError, ServerError } from '../../utils/exception'; +import { logger } from '../../utils/log'; /** * Credential Control API @@ -34,7 +34,11 @@ export class CredentialControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns Created credential object */ - createCredential = async (params: { input: $AgentRun.CreateCredentialInput; headers?: Record; config?: Config }): Promise<$AgentRun.Credential> => { + createCredential = async (params: { + input: $AgentRun.CreateCredentialInput; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.Credential> => { const { input, headers, config } = params; try { @@ -48,15 +52,15 @@ export class CredentialControlAPI extends ControlAPI { ); logger.debug( - `request api createCredential, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([input])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api createCredential, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([input])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.Credential; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -78,7 +82,11 @@ export class CredentialControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns Deleted credential object */ - deleteCredential = async (params: { credentialName: string; headers?: Record; config?: Config }): Promise<$AgentRun.Credential> => { + deleteCredential = async (params: { + credentialName: string; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.Credential> => { const { credentialName, headers, config } = params; try { @@ -92,15 +100,15 @@ export class CredentialControlAPI extends ControlAPI { ); logger.debug( - `request api deleteCredential, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([credentialName])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api deleteCredential, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([credentialName])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.Credential; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -123,7 +131,12 @@ export class CredentialControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns Updated credential object */ - updateCredential = async (params: { credentialName: string; input: $AgentRun.UpdateCredentialInput; headers?: Record; config?: Config }): Promise<$AgentRun.Credential> => { + updateCredential = async (params: { + credentialName: string; + input: $AgentRun.UpdateCredentialInput; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.Credential> => { const { credentialName, input, headers, config } = params; try { @@ -138,15 +151,15 @@ export class CredentialControlAPI extends ControlAPI { ); logger.debug( - `request api updateCredential, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([credentialName, input])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api updateCredential, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([credentialName, input])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.Credential; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -168,7 +181,11 @@ export class CredentialControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns Credential object */ - getCredential = async (params: { credentialName: string; headers?: Record; config?: Config }): Promise<$AgentRun.Credential> => { + getCredential = async (params: { + credentialName: string; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.Credential> => { const { credentialName, headers, config } = params; try { @@ -182,15 +199,15 @@ export class CredentialControlAPI extends ControlAPI { ); logger.debug( - `request api getCredential, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([credentialName])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api getCredential, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([credentialName])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.Credential; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -212,29 +229,29 @@ export class CredentialControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns List of credential objects */ - listCredentials = async (params: { input: $AgentRun.ListCredentialsRequest; headers?: Record; config?: Config }): Promise<$AgentRun.ListCredentialsOutput> => { + listCredentials = async (params: { + input: $AgentRun.ListCredentialsRequest; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.ListCredentialsOutput> => { const { input, headers, config } = params; try { const client = this.getClient(config); const runtime = new $Util.RuntimeOptions({}); - const response = await client.listCredentialsWithOptions( - input, - headers ?? {}, - runtime - ); + const response = await client.listCredentialsWithOptions(input, headers ?? {}, runtime); logger.debug( - `request api listCredentials, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([input])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api listCredentials, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([input])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.ListCredentialsOutput; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -246,5 +263,4 @@ export class CredentialControlAPI extends ControlAPI { throw error; } }; - } diff --git a/src/credential/api/index.ts b/src/credential/api/index.ts index dda619d..87b43e5 100644 --- a/src/credential/api/index.ts +++ b/src/credential/api/index.ts @@ -2,4 +2,6 @@ * Credential API exports */ -export { CredentialControlAPI } from "./control"; +import '@/utils/version-check'; + +export { CredentialControlAPI } from './control'; diff --git a/src/credential/client.ts b/src/credential/client.ts index f444090..1fab832 100644 --- a/src/credential/client.ts +++ b/src/credential/client.ts @@ -49,10 +49,8 @@ export class CredentialClient { const normalized = { ...input, credentialAuthType: credCfg?.credentialAuthType ?? credCfg?.authType, - credentialSourceType: - credCfg?.credentialSourceType ?? credCfg?.sourceType, - credentialPublicConfig: - credCfg?.credentialPublicConfig ?? credCfg?.publicConfig, + credentialSourceType: credCfg?.credentialSourceType ?? credCfg?.sourceType, + credentialPublicConfig: credCfg?.credentialPublicConfig ?? credCfg?.publicConfig, credentialSecret: credCfg?.credentialSecret ?? credCfg?.secret, }; @@ -89,10 +87,7 @@ export class CredentialClient { return new Credential(result); } catch (error) { if (error instanceof HTTPError) { - throw error.toResourceError( - 'Credential', - params?.input?.credentialName - ); + throw error.toResourceError('Credential', params?.input?.credentialName); } throw error; @@ -102,10 +97,7 @@ export class CredentialClient { /** * Delete a Credential */ - delete = async (params: { - name: string; - config?: Config; - }): Promise => { + delete = async (params: { name: string; config?: Config }): Promise => { try { const { name, config } = params; const cfg = Config.withConfigs(this.config, config); @@ -138,14 +130,11 @@ export class CredentialClient { const credCfg = input.credentialConfig as any | undefined; const normalized: any = { ...input }; if (credCfg) { - normalized.credentialAuthType = - credCfg?.credentialAuthType ?? credCfg?.authType; - normalized.credentialSourceType = - credCfg?.credentialSourceType ?? credCfg?.sourceType; + normalized.credentialAuthType = credCfg?.credentialAuthType ?? credCfg?.authType; + normalized.credentialSourceType = credCfg?.credentialSourceType ?? credCfg?.sourceType; normalized.credentialPublicConfig = credCfg?.credentialPublicConfig ?? credCfg?.publicConfig; - normalized.credentialSecret = - credCfg?.credentialSecret ?? credCfg?.secret; + normalized.credentialSecret = credCfg?.credentialSecret ?? credCfg?.secret; // Ensure users field is always present in credentialPublicConfig if (normalized.credentialPublicConfig) { @@ -189,10 +178,7 @@ export class CredentialClient { /** * Get a Credential */ - get = async (params: { - name: string; - config?: Config; - }): Promise => { + get = async (params: { name: string; config?: Config }): Promise => { try { const { name, config } = params; const cfg = Config.withConfigs(this.config, config); @@ -226,10 +212,7 @@ export class CredentialClient { config: cfg, }); - return ( - results.items?.map((item) => new CredentialListOutput(item as any)) ?? - [] - ); + return results.items?.map(item => new CredentialListOutput(item as any)) ?? []; } catch (error) { if (error instanceof HTTPError) { throw error.toResourceError('Credential'); diff --git a/src/credential/credential.ts b/src/credential/credential.ts index 416cc34..73c972a 100644 --- a/src/credential/credential.ts +++ b/src/credential/credential.ts @@ -6,10 +6,7 @@ */ import { Config } from '../utils/config'; -import { - listAllResourcesFunction, - updateObjectProperties, -} from '../utils/resource'; +import { listAllResourcesFunction, updateObjectProperties } from '../utils/resource'; import { ResourceBase } from '../utils/resource'; import { CredentialClient } from './client'; @@ -19,7 +16,7 @@ import { CredentialInterface, CredentialSourceType, CredentialUpdateInput, - RelatedResource + RelatedResource, } from './model'; export class Credential extends ResourceBase implements CredentialInterface { @@ -60,12 +57,8 @@ export class Credential extends ResourceBase implements CredentialInterface { static create = async (paramsOrInput: any) => { // Backwards compatibility: allow calling Credential.create(input) const hasInputProp = paramsOrInput && paramsOrInput.input !== undefined; - const input: CredentialCreateInput = hasInputProp - ? paramsOrInput.input - : paramsOrInput; - const config: Config | undefined = hasInputProp - ? paramsOrInput.config - : undefined; + const input: CredentialCreateInput = hasInputProp ? paramsOrInput.input : paramsOrInput; + const config: Config | undefined = hasInputProp ? paramsOrInput.config : undefined; return await Credential.getClient().create({ input, config }); }; @@ -76,9 +69,7 @@ export class Credential extends ResourceBase implements CredentialInterface { // Accept either (name: string) or ({ name, config }) const isString = typeof paramsOrName === 'string'; const name: string = isString ? paramsOrName : paramsOrName.name; - const config: Config | undefined = isString - ? undefined - : paramsOrName.config; + const config: Config | undefined = isString ? undefined : paramsOrName.config; return await Credential.getClient().delete({ name, config }); }; @@ -100,9 +91,7 @@ export class Credential extends ResourceBase implements CredentialInterface { // Accept either name string or { name, config } const isString = typeof paramsOrName === 'string'; const name: string = isString ? paramsOrName : paramsOrName.name; - const config: Config | undefined = isString - ? undefined - : paramsOrName.config; + const config: Config | undefined = isString ? undefined : paramsOrName.config; return await Credential.getClient().get({ name, config }); }; diff --git a/src/credential/index.ts b/src/credential/index.ts index b1e2bf0..f240daf 100644 --- a/src/credential/index.ts +++ b/src/credential/index.ts @@ -2,6 +2,8 @@ * Credential module exports */ +import '@/utils/version-check'; + export { CredentialClient } from './client'; export { Credential } from './credential'; export { CredentialControlAPI } from './api/control'; diff --git a/src/credential/model.ts b/src/credential/model.ts index 3d86396..ddae60b 100644 --- a/src/credential/model.ts +++ b/src/credential/model.ts @@ -10,18 +10,10 @@ import { updateObjectProperties } from '../utils/resource'; import { Config } from '../utils/config'; /** 凭证认证类型 / Credential Authentication Types */ -export type CredentialAuthType = - | 'jwt' - | 'api_key' - | 'basic' - | 'aksk' - | 'custom_header'; +export type CredentialAuthType = 'jwt' | 'api_key' | 'basic' | 'aksk' | 'custom_header'; /** 凭证来源类型 / Credential Source Types */ -export type CredentialSourceType = - | 'external_llm' - | 'external_tool' - | 'internal'; +export type CredentialSourceType = 'external_llm' | 'external_tool' | 'internal'; /** * Credential basic authentication configuration @@ -142,9 +134,7 @@ export class CredentialConfig implements CredentialConfigInterface { } /** 配置访问第三方工具的自定义凭证 */ - static outboundToolAKSKCustom(params: { - authConfig: Record; - }) { + static outboundToolAKSKCustom(params: { authConfig: Record }) { const { authConfig } = params; return new CredentialConfig({ credentialSourceType: 'external_tool', @@ -185,9 +175,7 @@ export interface CredentialSystemProps { relatedResources?: RelatedResource[]; } -export interface CredentialCreateInput - extends CredentialMutableProps, - CredentialImmutableProps { +export interface CredentialCreateInput extends CredentialMutableProps, CredentialImmutableProps { credentialConfig?: CredentialConfig; } @@ -238,7 +226,8 @@ export class CredentialListOutput { */ export interface CredentialInterface - extends CredentialMutableProps, + extends + CredentialMutableProps, CredentialImmutableProps, CredentialSystemProps, CredentialConfigInterface {} diff --git a/src/index.ts b/src/index.ts index 91bf004..b6c8ae4 100644 --- a/src/index.ts +++ b/src/index.ts @@ -8,11 +8,12 @@ * @packageDocumentation */ +import '@/utils/version-check'; + // Version is injected at build time from package.json declare const __VERSION__: string; -export const VERSION = - typeof __VERSION__ !== 'undefined' ? __VERSION__ : '0.0.0-dev'; +export const VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : '0.0.0-dev'; // Config export { Config, type ConfigOptions } from './utils/config'; @@ -60,12 +61,7 @@ export { } from './agent-runtime'; // Credential -export { - CredentialClient, - Credential, - CredentialControlAPI, - CredentialConfig, -} from './credential'; +export { CredentialClient, Credential, CredentialControlAPI, CredentialConfig } from './credential'; export type { CredentialCreateInput, CredentialUpdateInput, @@ -115,12 +111,7 @@ export type { } from './sandbox'; // Model -export { - ModelClient, - ModelService, - ModelProxy, - ModelControlAPI, -} from './model'; +export { ModelClient, ModelService, ModelProxy, ModelControlAPI } from './model'; export type { ModelServiceCreateInput, ModelServiceUpdateInput, @@ -189,23 +180,3 @@ export type { RouteDefinition, ExpressAdapterOptions, } from './server'; - -// Logger -import { logger } from './utils/log'; - -// Breaking changes warning -if (!process.env.DISABLE_BREAKING_CHANGES_WARNING) { - logger.warn( - `当前您正在使用 AgentRun Node.js SDK 版本 ${VERSION}。` + - '早期版本通常包含许多新功能,这些功能\x1b[1;33m 可能引入不兼容的变更 \x1b[0m。' + - '为避免潜在问题,我们强烈建议\x1b[1;32m 将依赖锁定为此版本 \x1b[0m。\n' + - `You are currently using AgentRun Node.js SDK version ${VERSION}. ` + - 'Early versions often include many new features, which\x1b[1;33m may introduce breaking changes\x1b[0m. ' + - 'To avoid potential issues, we strongly recommend \x1b[1;32mpinning the dependency to this version\x1b[0m.\n' + - `\x1b[2;3m npm install '@agentrun/sdk@${VERSION}' \x1b[0m\n` + - `\x1b[2;3m bun add '@agentrun/sdk@${VERSION}' \x1b[0m\n\n` + - '增加\x1b[2;3m DISABLE_BREAKING_CHANGES_WARNING=1 \x1b[0m到您的环境变量以关闭此警告。\n' + - 'Add\x1b[2;3m DISABLE_BREAKING_CHANGES_WARNING=1 \x1b[0mto your environment variables to disable this warning.\n\n' + - 'Releases:\x1b[2;3m https://github.com/Serverless-Devs/agentrun-sdk-nodejs/releases \x1b[0m', - ); -} diff --git a/src/integration/adapter.ts b/src/integration/adapter.ts index 2a1f6b2..3ebe6b1 100644 --- a/src/integration/adapter.ts +++ b/src/integration/adapter.ts @@ -88,11 +88,11 @@ export class MastraMessageAdapter { toCanonical(messages: Array>): CanonicalMessage[] { if (!Array.isArray(messages)) return []; - return messages.map((msg) => { + return messages.map(msg => { const role = msg.role as CanonicalMessageRole; const content = (msg.content ?? null) as string | null; const toolCalls = this.normalizeToolCalls( - (msg.tool_calls ?? msg.toolCalls) as Array>, + (msg.tool_calls ?? msg.toolCalls) as Array> ); return { @@ -108,7 +108,7 @@ export class MastraMessageAdapter { fromCanonical(messages: CanonicalMessage[]): Array> { if (!Array.isArray(messages)) return []; - return messages.map((msg) => ({ + return messages.map(msg => ({ role: msg.role, content: msg.content ?? null, name: msg.name, @@ -118,20 +118,18 @@ export class MastraMessageAdapter { } private normalizeToolCalls( - toolCalls?: Array>, + toolCalls?: Array> ): CanonicalToolCall[] | undefined { if (!toolCalls || !Array.isArray(toolCalls) || toolCalls.length === 0) { return undefined; } - return toolCalls.map((tc) => ({ + return toolCalls.map(tc => ({ id: String(tc.id ?? ''), type: (tc.type as string) ?? 'function', function: { name: String((tc.function as Record)?.name ?? ''), - arguments: String( - (tc.function as Record)?.arguments ?? '', - ), + arguments: String((tc.function as Record)?.arguments ?? ''), }, })); } @@ -143,7 +141,7 @@ export class MastraMessageAdapter { export class MastraToolAdapter { fromCanonical(tools: CanonicalTool[]): MastraToolShape[] { if (!Array.isArray(tools)) return []; - return tools.map((tool) => ({ + return tools.map(tool => ({ name: tool.name, description: tool.description, inputSchema: tool.parameters, @@ -152,16 +150,14 @@ export class MastraToolAdapter { toCanonical(tools: MastraToolShape[]): CanonicalTool[] { if (!Array.isArray(tools)) return []; - return tools.map((tool) => ({ + return tools.map(tool => ({ name: tool.name, description: tool.description ?? '', parameters: this.normalizeSchema(tool.inputSchema), })); } - private normalizeSchema( - schema?: ToolParametersSchema - ): ToolParametersSchema { + private normalizeSchema(schema?: ToolParametersSchema): ToolParametersSchema { if (schema && schema.type === 'object' && schema.properties) { return schema; } @@ -220,4 +216,4 @@ export function wrapTools(tools: CanonicalTool[]): MastraToolShape[] { export function wrapModel(config: CommonModelConfig): MastraModelConfig { return new MastraModelAdapter().createModel(config); -} \ No newline at end of file +} diff --git a/src/integration/builtin/index.ts b/src/integration/builtin/index.ts index 4d1618e..7e3cd0c 100644 --- a/src/integration/builtin/index.ts +++ b/src/integration/builtin/index.ts @@ -6,6 +6,8 @@ * 提供内置的集成函数,用于快速创建模型和工具。 */ +import '@/utils/version-check'; + // Tool definitions export { Tool, @@ -20,12 +22,7 @@ export { } from './tool'; // Sandbox toolsets -export { - SandboxToolSet, - CodeInterpreterToolSet, - BrowserToolSet, - sandboxToolset, -} from './sandbox'; +export { SandboxToolSet, CodeInterpreterToolSet, BrowserToolSet, sandboxToolset } from './sandbox'; // ToolSet integration export { toolset } from './toolset'; diff --git a/src/integration/builtin/sandbox.ts b/src/integration/builtin/sandbox.ts index 36c4c8a..5cdcd2e 100644 --- a/src/integration/builtin/sandbox.ts +++ b/src/integration/builtin/sandbox.ts @@ -16,12 +16,7 @@ import { CodeLanguage, } from '@/sandbox'; -import { - Tool, - CommonToolSet, - type ToolParametersSchema, - type ToolFunction, -} from './tool'; +import { Tool, CommonToolSet, type ToolParametersSchema, type ToolFunction } from './tool'; // Import Playwright types from optional dependency declaration import type { Browser, Page } from 'playwright'; @@ -66,8 +61,7 @@ export abstract class SandboxToolSet extends CommonToolSet { this.client = new SandboxClient(options.config); this.templateName = options.templateName; this.templateType = options.templateType; - this.sandboxIdleTimeoutSeconds = - options.sandboxIdleTimeoutSeconds ?? 5 * 60; + this.sandboxIdleTimeoutSeconds = options.sandboxIdleTimeoutSeconds ?? 5 * 60; } /** @@ -235,8 +229,7 @@ export class CodeInterpreterToolSet extends SandboxToolSet { createTool({ name: 'delete_context', - description: - 'Delete a specific execution context and release related resources.', + description: 'Delete a specific execution context and release related resources.', parameters: { type: 'object', properties: { @@ -256,8 +249,7 @@ export class CodeInterpreterToolSet extends SandboxToolSet { // File Operations createTool({ name: 'read_file', - description: - 'Read the content of a file at the specified path in the sandbox.', + description: 'Read the content of a file at the specified path in the sandbox.', parameters: { type: 'object', properties: { @@ -273,8 +265,7 @@ export class CodeInterpreterToolSet extends SandboxToolSet { createTool({ name: 'write_file', - description: - 'Write content to a file at the specified path in the sandbox.', + description: 'Write content to a file at the specified path in the sandbox.', parameters: { type: 'object', properties: { @@ -471,25 +462,17 @@ export class CodeInterpreterToolSet extends SandboxToolSet { // Tool implementations checkHealth = async () => { - return this.runInSandbox(async (sb) => { + return this.runInSandbox(async sb => { const ciSandbox = sb as CodeInterpreterSandbox; return ciSandbox.checkHealth(); }); }; - runCode = async ( - code: string, - language?: string, - timeout?: number, - contextId?: string, - ) => { - return this.runInSandbox(async (sb) => { + runCode = async (code: string, language?: string, timeout?: number, contextId?: string) => { + return this.runInSandbox(async sb => { const ciSandbox = sb as CodeInterpreterSandbox; - const lang = - language === 'javascript' ? - CodeLanguage.JAVASCRIPT - : CodeLanguage.PYTHON; + const lang = language === 'javascript' ? CodeLanguage.JAVASCRIPT : CodeLanguage.PYTHON; if (contextId) { const result = await ciSandbox.context.execute({ @@ -530,7 +513,7 @@ export class CodeInterpreterToolSet extends SandboxToolSet { }; listContexts = async () => { - return this.runInSandbox(async (sb) => { + return this.runInSandbox(async sb => { const ciSandbox = sb as CodeInterpreterSandbox; const contexts = await ciSandbox.context.list(); return { contexts }; @@ -538,12 +521,9 @@ export class CodeInterpreterToolSet extends SandboxToolSet { }; createContext = async (language?: string, cwd?: string) => { - return this.runInSandbox(async (sb) => { + return this.runInSandbox(async sb => { const ciSandbox = sb as CodeInterpreterSandbox; - const lang = - language === 'javascript' ? - CodeLanguage.JAVASCRIPT - : CodeLanguage.PYTHON; + const lang = language === 'javascript' ? CodeLanguage.JAVASCRIPT : CodeLanguage.PYTHON; const ctx = await ciSandbox.context.create({ language: lang, cwd: cwd ?? '/home/user', @@ -557,7 +537,7 @@ export class CodeInterpreterToolSet extends SandboxToolSet { }; deleteContext = async (contextId: string) => { - return this.runInSandbox(async (sb) => { + return this.runInSandbox(async sb => { const ciSandbox = sb as CodeInterpreterSandbox; const result = await ciSandbox.context.delete({ contextId }); return { success: true, result }; @@ -565,20 +545,15 @@ export class CodeInterpreterToolSet extends SandboxToolSet { }; readFile = async (path: string) => { - return this.runInSandbox(async (sb) => { + return this.runInSandbox(async sb => { const ciSandbox = sb as CodeInterpreterSandbox; const content = await ciSandbox.file.read({ path }); return { path, content }; }); }; - writeFile = async ( - path: string, - content: string, - mode?: string, - encoding?: string, - ) => { - return this.runInSandbox(async (sb) => { + writeFile = async (path: string, content: string, mode?: string, encoding?: string) => { + return this.runInSandbox(async sb => { const ciSandbox = sb as CodeInterpreterSandbox; const result = await ciSandbox.file.write({ path, @@ -591,7 +566,7 @@ export class CodeInterpreterToolSet extends SandboxToolSet { }; fileSystemList = async (path?: string, depth?: number) => { - return this.runInSandbox(async (sb) => { + return this.runInSandbox(async sb => { const ciSandbox = sb as CodeInterpreterSandbox; const entries = await ciSandbox.fileSystem.list({ path: path ?? '/', @@ -602,7 +577,7 @@ export class CodeInterpreterToolSet extends SandboxToolSet { }; fileSystemStat = async (path: string) => { - return this.runInSandbox(async (sb) => { + return this.runInSandbox(async sb => { const ciSandbox = sb as CodeInterpreterSandbox; const stat = await ciSandbox.fileSystem.stat({ path }); return { path, stat }; @@ -610,7 +585,7 @@ export class CodeInterpreterToolSet extends SandboxToolSet { }; fileSystemMkdir = async (path: string, parents?: boolean, mode?: string) => { - return this.runInSandbox(async (sb) => { + return this.runInSandbox(async sb => { const ciSandbox = sb as CodeInterpreterSandbox; const result = await ciSandbox.fileSystem.mkdir({ path, @@ -622,7 +597,7 @@ export class CodeInterpreterToolSet extends SandboxToolSet { }; fileSystemMove = async (source: string, destination: string) => { - return this.runInSandbox(async (sb) => { + return this.runInSandbox(async sb => { const ciSandbox = sb as CodeInterpreterSandbox; const result = await ciSandbox.fileSystem.move({ source, destination }); return { source, destination, success: true, result }; @@ -630,7 +605,7 @@ export class CodeInterpreterToolSet extends SandboxToolSet { }; fileSystemRemove = async (path: string) => { - return this.runInSandbox(async (sb) => { + return this.runInSandbox(async sb => { const ciSandbox = sb as CodeInterpreterSandbox; const result = await ciSandbox.fileSystem.remove({ path }); return { path, success: true, result }; @@ -638,7 +613,7 @@ export class CodeInterpreterToolSet extends SandboxToolSet { }; processExecCmd = async (command: string, cwd?: string, timeout?: number) => { - return this.runInSandbox(async (sb) => { + return this.runInSandbox(async sb => { const ciSandbox = sb as CodeInterpreterSandbox; const result = await ciSandbox.process.cmd({ command, @@ -656,7 +631,7 @@ export class CodeInterpreterToolSet extends SandboxToolSet { }; processList = () => { - return this.runInSandbox(async (sb) => { + return this.runInSandbox(async sb => { const ciSandbox = sb as CodeInterpreterSandbox; const processes = await ciSandbox.process.list(); return { processes }; @@ -664,7 +639,7 @@ export class CodeInterpreterToolSet extends SandboxToolSet { }; processKill = async (pid: string) => { - return this.runInSandbox(async (sb) => { + return this.runInSandbox(async sb => { const ciSandbox = sb as CodeInterpreterSandbox; const result = await ciSandbox.process.kill({ pid }); return { pid, success: true, result }; @@ -708,7 +683,7 @@ export class BrowserToolSet extends SandboxToolSet { return await import('playwright'); } catch { throw new Error( - 'Playwright is not installed. Please install it with: npm install playwright', + 'Playwright is not installed. Please install it with: npm install playwright' ); } } @@ -761,7 +736,7 @@ export class BrowserToolSet extends SandboxToolSet { */ override close() { if (this.playwrightBrowser) { - this.playwrightBrowser.close().catch((e) => { + this.playwrightBrowser.close().catch(e => { logger.debug('Failed to close Playwright browser:', e); }); this.playwrightBrowser = null; @@ -785,8 +760,7 @@ export class BrowserToolSet extends SandboxToolSet { // Navigation createTool({ name: 'browser_navigate', - description: - 'Navigate to the specified URL. This is the first step in browser automation.', + description: 'Navigate to the specified URL. This is the first step in browser automation.', parameters: { type: 'object', properties: { @@ -819,8 +793,7 @@ export class BrowserToolSet extends SandboxToolSet { createTool({ name: 'browser_take_screenshot', - description: - 'Capture a screenshot of the current page, returns base64 encoded image data.', + description: 'Capture a screenshot of the current page, returns base64 encoded image data.', parameters: { type: 'object', properties: { @@ -868,8 +841,7 @@ export class BrowserToolSet extends SandboxToolSet { createTool({ name: 'browser_fill', - description: - 'Fill a form input with a value. Clears existing content first.', + description: 'Fill a form input with a value. Clears existing content first.', parameters: { type: 'object', properties: { @@ -940,8 +912,7 @@ export class BrowserToolSet extends SandboxToolSet { // Advanced createTool({ name: 'browser_evaluate', - description: - 'Execute JavaScript code in the page context and return the result.', + description: 'Execute JavaScript code in the page context and return the result.', parameters: { type: 'object', properties: { @@ -1027,7 +998,7 @@ export class BrowserToolSet extends SandboxToolSet { // Tool implementations using Playwright checkHealth = async () => { - return this.runInSandbox(async (sb) => { + return this.runInSandbox(async sb => { const browserSandbox = sb as BrowserSandbox; return browserSandbox.checkHealth(); }); @@ -1293,17 +1264,14 @@ export async function sandboxToolset( templateType?: TemplateType; config?: Config; sandboxIdleTimeoutSeconds?: number; - }, + } ) { const client = new SandboxClient(); const template = await client.getTemplate({ name: templateName }); const templateType = template.templateType; - if ( - templateType === TemplateType.BROWSER || - templateType === TemplateType.AIO - ) + if (templateType === TemplateType.BROWSER || templateType === TemplateType.AIO) return new BrowserToolSet({ templateName, config: options?.config, diff --git a/src/integration/builtin/tool.ts b/src/integration/builtin/tool.ts index 2aa52b1..c697f51 100644 --- a/src/integration/builtin/tool.ts +++ b/src/integration/builtin/tool.ts @@ -142,8 +142,7 @@ export class Tool implements ToolDefinition { } const originalFunc = this.func; - const boundFunc = (...args: unknown[]) => - originalFunc.call(instance, ...args); + const boundFunc = (...args: unknown[]) => originalFunc.call(instance, ...args); return new Tool({ name: this.name, @@ -225,19 +224,19 @@ export class CommonToolSet { // Apply filter if (options?.filterByName) { - tools = tools.filter((t) => options.filterByName!(t.name)); + tools = tools.filter(t => options.filterByName!(t.name)); } // Apply prefix const prefix = options?.prefix || this.name; tools = tools.map( - (t) => + t => new Tool({ name: `${prefix}_${t.name}`, description: t.description, parameters: t.parameters, func: t.func, - }), + }) ); // Apply modification @@ -245,7 +244,7 @@ export class CommonToolSet { tools = tools.map(options.modifyTool); } - return tools.map((tool) => ({ + return tools.map(tool => ({ name: tool.name, description: tool.description, parameters: tool.getParametersSchema(), @@ -256,10 +255,7 @@ export class CommonToolSet { /** * Create CommonToolSet from AgentRun ToolSet */ - static async fromAgentRunToolSet( - toolset: ToolSet, - config?: Config, - ): Promise { + static async fromAgentRunToolSet(toolset: ToolSet, config?: Config): Promise { const toolsMeta = (await toolset.listTools(config)) || []; const tools: Tool[] = []; const seenNames = new Set(); @@ -268,9 +264,7 @@ export class CommonToolSet { const tool = buildToolFromMeta(toolset, meta, config); if (tool) { if (seenNames.has(tool.name)) { - logger.warn( - `Duplicate tool name '${tool.name}' detected, skipping second occurrence`, - ); + logger.warn(`Duplicate tool name '${tool.name}' detected, skipping second occurrence`); continue; } seenNames.add(tool.name); @@ -288,7 +282,7 @@ export class CommonToolSet { prefix?: string; filterByName?: (name: string) => boolean; }): Record[] { - return this.tools(options).map((tool) => ({ + return this.tools(options).map(tool => ({ name: tool.name, description: tool.description, parameters: tool.parameters, @@ -302,7 +296,7 @@ export class CommonToolSet { prefix?: string; filterByName?: (name: string) => boolean; }): Record[] { - return this.tools(options).map((tool) => ({ + return this.tools(options).map(tool => ({ name: tool.name, description: tool.description, input_schema: tool.parameters, @@ -323,12 +317,10 @@ export class CommonToolSet { function buildToolFromMeta( toolset: ToolSet, meta: Record, - config?: Config, + config?: Config ): Tool | null { const toolName = - (meta.name as string) || - (meta.operationId as string) || - (meta.tool_id as string); + (meta.name as string) || (meta.operationId as string) || (meta.tool_id as string); if (!toolName) { return null; @@ -344,11 +336,7 @@ function buildToolFromMeta( const func = async (args: unknown) => { logger.debug(`Invoking tool ${toolName} with arguments:`, args); - const result = await toolset.callTool( - toolName, - args as Record, - config, - ); + const result = await toolset.callTool(toolName, args as Record, config); logger.debug(`Tool ${toolName} returned:`, result); return result; }; @@ -364,9 +352,7 @@ function buildToolFromMeta( /** * Build parameters schema from metadata */ -function buildParametersSchema( - meta: Record, -): ToolParametersSchema { +function buildParametersSchema(meta: Record): ToolParametersSchema { // Handle ToolSchema format (from ToolInfo) if (meta.parameters && typeof meta.parameters === 'object') { const params = meta.parameters as Record; @@ -403,8 +389,7 @@ function buildParametersSchema( const schema = (p.schema as Record) || {}; properties[name] = { ...schema, - description: - (p.description as string) || (schema.description as string) || '', + description: (p.description as string) || (schema.description as string) || '', }; if (p.required) { @@ -431,15 +416,11 @@ export function tool(options: { name?: string; description?: string; parameters?: ToolParametersSchema; -}): ( - target: unknown, - propertyKey: string, - descriptor: PropertyDescriptor, -) => PropertyDescriptor { +}): (target: unknown, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor { return function ( _target: unknown, propertyKey: string, - descriptor: PropertyDescriptor, + descriptor: PropertyDescriptor ): PropertyDescriptor { const originalMethod = descriptor.value; const toolName = options.name || propertyKey; diff --git a/src/integration/builtin/toolset.ts b/src/integration/builtin/toolset.ts index c4cc21b..cd42049 100644 --- a/src/integration/builtin/toolset.ts +++ b/src/integration/builtin/toolset.ts @@ -38,14 +38,9 @@ import { CommonToolSet } from './tool'; * const mastraTools = await ts.toMastra(); * ``` */ -export async function toolset( - input: string | ToolSet, - config?: Config -): Promise { +export async function toolset(input: string | ToolSet, config?: Config): Promise { const toolsetInstance = - input instanceof ToolSet - ? input - : await new ToolSetClient(config).get({ name: input, config }); + input instanceof ToolSet ? input : await new ToolSetClient(config).get({ name: input, config }); return CommonToolSet.fromAgentRunToolSet(toolsetInstance, config); } diff --git a/src/integration/index.ts b/src/integration/index.ts index 7efa2e9..404cb52 100644 --- a/src/integration/index.ts +++ b/src/integration/index.ts @@ -1,3 +1,5 @@ +import '@/utils/version-check'; + // Mastra integration export * from './mastra'; export * from './adapter'; diff --git a/src/integration/mastra/README.md b/src/integration/mastra/README.md index ed589d6..09b9636 100644 --- a/src/integration/mastra/README.md +++ b/src/integration/mastra/README.md @@ -50,10 +50,10 @@ const mastraAgent = new Agent({ async function* invokeAgent(request: AgentRequest) { const converter = new MastraConverter(); const userMessage = request.messages[request.messages.length - 1]?.content; - + // 获取 Mastra stream const mastraStream = await mastraAgent.stream(userMessage); - + // 转换并输出事件 for await (const chunk of mastraStream.fullStream) { const events = converter.convert(chunk); @@ -73,7 +73,10 @@ server.start({ port: 9000 }); ```typescript import { Agent } from '@mastra/core/agent'; import { openai } from '@ai-sdk/openai'; -import { MastraConverter, toolset } from '@alicloud/agentrun-sdk/integration/mastra'; +import { + MastraConverter, + toolset, +} from '@alicloud/agentrun-sdk/integration/mastra'; import { AgentRunServer } from '@alicloud/agentrun-sdk'; // 从 AgentRun 获取 Mastra 兼容的工具 @@ -92,7 +95,7 @@ const agent = new Agent({ async function* invokeAgent(request) { const converter = new MastraConverter(); const stream = await agent.stream(request.messages); - + for await (const chunk of stream.fullStream) { for (const event of converter.convert(chunk)) { yield event; @@ -103,15 +106,15 @@ async function* invokeAgent(request) { ## 事件映射 Event Mapping -| Mastra Event | AgentRun Event | 说明 Description | -|-------------|----------------|------------------| -| `text-delta` | 字符串 string | 文本增量输出 Text delta output | -| `tool-call` | `TOOL_CALL_CHUNK` | 工具调用 Tool call with id, name, args | -| `tool-result` | `TOOL_RESULT` | 工具结果 Tool execution result | -| `error` | `ERROR` | 错误信息 Error message | +| Mastra Event | AgentRun Event | 说明 Description | +| ----------------- | -------------------- | --------------------------------------------- | +| `text-delta` | 字符串 string | 文本增量输出 Text delta output | +| `tool-call` | `TOOL_CALL_CHUNK` | 工具调用 Tool call with id, name, args | +| `tool-result` | `TOOL_RESULT` | 工具结果 Tool execution result | +| `error` | `ERROR` | 错误信息 Error message | | `reasoning-delta` | 标记文本 Marked text | 推理过程(可选) Reasoning process (optional) | -| `finish` | - | 日志记录 Logged for debugging | -| `step-*` | - | 日志记录 Logged for debugging | +| `finish` | - | 日志记录 Logged for debugging | +| `step-*` | - | 日志记录 Logged for debugging | ## API 参考 API Reference @@ -127,9 +130,11 @@ async function* invokeAgent(request) { Convert a single Mastra chunk to AgentRun events **参数 Parameters:** + - `chunk`: Mastra stream chunk (包含 type, runId, from, payload) **返回 Returns:** + - Generator of `AgentEventItem` (strings or `AgentEvent` objects) **示例 Example:** @@ -148,12 +153,12 @@ for await (const chunk of mastraStream.fullStream) { ## 与 Python 版本的对比 Comparison with Python Version -| Feature | Python LangChain Converter | Node.js Mastra Converter | -|---------|---------------------------|-------------------------| -| 状态管理 State | 需要维护 tool_call_id 映射 | 不需要(Mastra events 更完整) | -| 事件源 Source | LangChain/LangGraph | Mastra | -| 复杂度 Complexity | 较高(需要处理流式工具调用的 ID 分配) | 较低(事件已包含完整信息) | -| 类型安全 Type Safety | 基于 Python typing | 基于 TypeScript | +| Feature | Python LangChain Converter | Node.js Mastra Converter | +| -------------------- | -------------------------------------- | ------------------------------ | +| 状态管理 State | 需要维护 tool_call_id 映射 | 不需要(Mastra events 更完整) | +| 事件源 Source | LangChain/LangGraph | Mastra | +| 复杂度 Complexity | 较高(需要处理流式工具调用的 ID 分配) | 较低(事件已包含完整信息) | +| 类型安全 Type Safety | 基于 Python typing | 基于 TypeScript | ## 高级用法 Advanced Usage @@ -167,10 +172,10 @@ class CustomMastraConverter extends MastraConverter { *convert(chunk) { // 添加自定义日志 console.log(`Processing: ${chunk.type}`); - + // 调用父类转换 yield* super.convert(chunk); - + // 添加自定义事件 if (chunk.type === 'finish') { yield { diff --git a/src/integration/mastra/converter.ts b/src/integration/mastra/converter.ts index d26ab0a..e196d45 100644 --- a/src/integration/mastra/converter.ts +++ b/src/integration/mastra/converter.ts @@ -66,9 +66,7 @@ export class MastraConverter { * ``` */ - *convert, U = undefined>( - chunk: T, - ): Generator { + *convert, U = undefined>(chunk: T): Generator { logger.debug(`[MastraConverter] Processing chunk type: ${chunk.type}`); // Handle text delta - direct text output @@ -206,10 +204,7 @@ export class MastraConverter { * Extract tool result information from chunk payload * 从 chunk payload 提取工具结果信息 */ - private extractToolResultFromPayload(payload?: { - result: any; - toolCallId: string; - }): { + private extractToolResultFromPayload(payload?: { result: any; toolCallId: string }): { id: string; result: string; } | null { @@ -240,9 +235,7 @@ export class MastraConverter { * Extract error message from chunk payload * 从 chunk payload 提取错误信息 */ - private extractErrorFromPayload( - payload?: Record, - ): string | null { + private extractErrorFromPayload(payload?: Record): string | null { if (!payload) return null; // Mastra error payload: { error: string | Error, ... } diff --git a/src/integration/mastra/index.ts b/src/integration/mastra/index.ts index 2a1aa78..4a905ea 100644 --- a/src/integration/mastra/index.ts +++ b/src/integration/mastra/index.ts @@ -9,6 +9,8 @@ * 本模块处理所有 Mastra 特定的转换,避免在 builtin 模块中引入依赖。 */ +import '@/utils/version-check'; + import { TemplateType } from '@/sandbox'; import type { Config } from '@/utils/config'; import { logger } from '@/utils/log'; @@ -45,7 +47,7 @@ async function convertToolSetToMastra( options?: { prefix?: string; filterByName?: (name: string) => boolean; - }, + } ): Promise { const tools = toolSet.tools(options); const mastraTools: ToolsInput = {}; @@ -55,10 +57,7 @@ async function convertToolSetToMastra( const mastraTool = await convertToolToMastra(tool); mastraTools[tool.name] = mastraTool; } catch (error) { - logger.warn( - `Failed to convert tool '${tool.name}' to Mastra format:`, - error, - ); + logger.warn(`Failed to convert tool '${tool.name}' to Mastra format:`, error); } } @@ -135,13 +134,13 @@ export async function createMastraTool< TSchemaOut = unknown, TSuspend = unknown, TResume = unknown, - TContext extends ToolExecutionContext = - ToolExecutionContext, + TContext extends ToolExecutionContext = ToolExecutionContext< + TSuspend, + TResume + >, >( - params: ToolAction, -): Promise< - ToolAction -> { + params: ToolAction +): Promise> { const { createTool } = await import('@mastra/core/tools'); return await createTool(params); } @@ -158,10 +157,7 @@ export async function createMastraTool< * const agent = new Agent({ tools }); * ``` */ -export async function toolset(params: { - name: string; - config?: Config; -}): Promise { +export async function toolset(params: { name: string; config?: Config }): Promise { const { name, config } = params; // Use builtin toolset to get CommonToolSet @@ -209,8 +205,7 @@ export async function sandbox(params: { sandboxIdleTimeoutSeconds?: number; config?: Config; }): Promise { - const { templateName, templateType, sandboxIdleTimeoutSeconds, config } = - params; + const { templateName, templateType, sandboxIdleTimeoutSeconds, config } = params; // Use builtin sandboxToolset const toolsetInstance = await sandboxToolset(templateName, { @@ -283,4 +278,3 @@ export async function browser(params: { // Export converter for event conversion export { MastraConverter, type AgentEventItem } from './converter'; - diff --git a/src/model/api/control.ts b/src/model/api/control.ts index 8044699..684eed3 100644 --- a/src/model/api/control.ts +++ b/src/model/api/control.ts @@ -9,13 +9,13 @@ // Source: model_control_api.yaml -import * as $AgentRun from "@alicloud/agentrun20250910"; -import * as $Util from "@alicloud/tea-util"; +import * as $AgentRun from '@alicloud/agentrun20250910'; +import * as $Util from '@alicloud/tea-util'; -import { Config } from "../../utils/config"; -import { ControlAPI } from "../../utils/control-api"; -import { ClientError, ServerError } from "../../utils/exception"; -import { logger } from "../../utils/log"; +import { Config } from '../../utils/config'; +import { ControlAPI } from '../../utils/control-api'; +import { ClientError, ServerError } from '../../utils/exception'; +import { logger } from '../../utils/log'; /** * Model Control API @@ -34,7 +34,11 @@ export class ModelControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns Created model service object */ - createModelService = async (params: { input: $AgentRun.CreateModelServiceInput; headers?: Record; config?: Config }): Promise<$AgentRun.ModelService> => { + createModelService = async (params: { + input: $AgentRun.CreateModelServiceInput; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.ModelService> => { const { input, headers, config } = params; try { @@ -48,15 +52,15 @@ export class ModelControlAPI extends ControlAPI { ); logger.debug( - `request api createModelService, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([input])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api createModelService, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([input])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.ModelService; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -78,7 +82,11 @@ export class ModelControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns Deleted model service object */ - deleteModelService = async (params: { modelServiceName: string; headers?: Record; config?: Config }): Promise<$AgentRun.ModelService> => { + deleteModelService = async (params: { + modelServiceName: string; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.ModelService> => { const { modelServiceName, headers, config } = params; try { @@ -92,15 +100,15 @@ export class ModelControlAPI extends ControlAPI { ); logger.debug( - `request api deleteModelService, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([modelServiceName])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api deleteModelService, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([modelServiceName])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.ModelService; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -123,7 +131,12 @@ export class ModelControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns Updated model service object */ - updateModelService = async (params: { modelServiceName: string; input: $AgentRun.UpdateModelServiceInput; headers?: Record; config?: Config }): Promise<$AgentRun.ModelService> => { + updateModelService = async (params: { + modelServiceName: string; + input: $AgentRun.UpdateModelServiceInput; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.ModelService> => { const { modelServiceName, input, headers, config } = params; try { @@ -138,15 +151,15 @@ export class ModelControlAPI extends ControlAPI { ); logger.debug( - `request api updateModelService, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([modelServiceName, input])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api updateModelService, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([modelServiceName, input])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.ModelService; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -168,7 +181,11 @@ export class ModelControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns Model service object */ - getModelService = async (params: { modelServiceName: string; headers?: Record; config?: Config }): Promise<$AgentRun.ModelService> => { + getModelService = async (params: { + modelServiceName: string; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.ModelService> => { const { modelServiceName, headers, config } = params; try { @@ -182,15 +199,15 @@ export class ModelControlAPI extends ControlAPI { ); logger.debug( - `request api getModelService, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([modelServiceName])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api getModelService, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([modelServiceName])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.ModelService; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -212,29 +229,29 @@ export class ModelControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns List of model service objects */ - listModelServices = async (params: { input: $AgentRun.ListModelServicesRequest; headers?: Record; config?: Config }): Promise<$AgentRun.ListModelServicesOutput> => { + listModelServices = async (params: { + input: $AgentRun.ListModelServicesRequest; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.ListModelServicesOutput> => { const { input, headers, config } = params; try { const client = this.getClient(config); const runtime = new $Util.RuntimeOptions({}); - const response = await client.listModelServicesWithOptions( - input, - headers ?? {}, - runtime - ); + const response = await client.listModelServicesWithOptions(input, headers ?? {}, runtime); logger.debug( - `request api listModelServices, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([input])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api listModelServices, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([input])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.ListModelServicesOutput; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -256,7 +273,11 @@ export class ModelControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns Created model proxy object */ - createModelProxy = async (params: { input: $AgentRun.CreateModelProxyInput; headers?: Record; config?: Config }): Promise<$AgentRun.ModelProxy> => { + createModelProxy = async (params: { + input: $AgentRun.CreateModelProxyInput; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.ModelProxy> => { const { input, headers, config } = params; try { @@ -270,15 +291,15 @@ export class ModelControlAPI extends ControlAPI { ); logger.debug( - `request api createModelProxy, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([input])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api createModelProxy, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([input])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.ModelProxy; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -300,7 +321,11 @@ export class ModelControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns Deleted model proxy object */ - deleteModelProxy = async (params: { modelProxyName: string; headers?: Record; config?: Config }): Promise<$AgentRun.ModelProxy> => { + deleteModelProxy = async (params: { + modelProxyName: string; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.ModelProxy> => { const { modelProxyName, headers, config } = params; try { @@ -314,15 +339,15 @@ export class ModelControlAPI extends ControlAPI { ); logger.debug( - `request api deleteModelProxy, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([modelProxyName])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api deleteModelProxy, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([modelProxyName])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.ModelProxy; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -345,7 +370,12 @@ export class ModelControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns Updated model proxy object */ - updateModelProxy = async (params: { modelProxyName: string; input: $AgentRun.UpdateModelProxyInput; headers?: Record; config?: Config }): Promise<$AgentRun.ModelProxy> => { + updateModelProxy = async (params: { + modelProxyName: string; + input: $AgentRun.UpdateModelProxyInput; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.ModelProxy> => { const { modelProxyName, input, headers, config } = params; try { @@ -360,15 +390,15 @@ export class ModelControlAPI extends ControlAPI { ); logger.debug( - `request api updateModelProxy, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([modelProxyName, input])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api updateModelProxy, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([modelProxyName, input])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.ModelProxy; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -390,7 +420,11 @@ export class ModelControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns Model proxy object */ - getModelProxy = async (params: { modelProxyName: string; headers?: Record; config?: Config }): Promise<$AgentRun.ModelProxy> => { + getModelProxy = async (params: { + modelProxyName: string; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.ModelProxy> => { const { modelProxyName, headers, config } = params; try { @@ -404,15 +438,15 @@ export class ModelControlAPI extends ControlAPI { ); logger.debug( - `request api getModelProxy, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([modelProxyName])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api getModelProxy, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([modelProxyName])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.ModelProxy; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -434,29 +468,29 @@ export class ModelControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns List of model proxy objects */ - listModelProxies = async (params: { input: $AgentRun.ListModelProxiesRequest; headers?: Record; config?: Config }): Promise<$AgentRun.ListModelProxiesOutput> => { + listModelProxies = async (params: { + input: $AgentRun.ListModelProxiesRequest; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.ListModelProxiesOutput> => { const { input, headers, config } = params; try { const client = this.getClient(config); const runtime = new $Util.RuntimeOptions({}); - const response = await client.listModelProxiesWithOptions( - input, - headers ?? {}, - runtime - ); + const response = await client.listModelProxiesWithOptions(input, headers ?? {}, runtime); logger.debug( - `request api listModelProxies, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([input])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api listModelProxies, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([input])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.ListModelProxiesOutput; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -468,5 +502,4 @@ export class ModelControlAPI extends ControlAPI { throw error; } }; - } diff --git a/src/model/api/model-api.ts b/src/model/api/model-api.ts index 8f768a8..3c20cee 100644 --- a/src/model/api/model-api.ts +++ b/src/model/api/model-api.ts @@ -37,9 +37,7 @@ export class ModelAPI { return provider(model); }; - private getEmbeddingModel = async ( - params: Parameters[0] - ) => { + private getEmbeddingModel = async (params: Parameters[0]) => { const { provider, model } = await this.getProvider(params); return provider.embeddingModel(model); }; diff --git a/src/model/client.ts b/src/model/client.ts index 4a234a5..065f0a9 100644 --- a/src/model/client.ts +++ b/src/model/client.ts @@ -5,14 +5,22 @@ * This module provides the client API for model services and model proxies. */ -import * as $AgentRun from "@alicloud/agentrun20250910"; +import * as $AgentRun from '@alicloud/agentrun20250910'; import * as _ from 'lodash'; import { Config } from '../utils/config'; import { HTTPError } from '../utils/exception'; import { ModelControlAPI } from './api/control'; -import { BackendType, ModelProxyCreateInput, ModelProxyListInput, ModelProxyUpdateInput, ModelServiceCreateInput, ModelServiceListInput, ModelServiceUpdateInput } from './model'; +import { + BackendType, + ModelProxyCreateInput, + ModelProxyListInput, + ModelProxyUpdateInput, + ModelServiceCreateInput, + ModelServiceListInput, + ModelServiceUpdateInput, +} from './model'; import { ModelProxy } from './model-proxy'; import { ModelService } from './model-service'; @@ -39,19 +47,22 @@ export class ModelClient { /** * 创建模型服务 * Create model service - * + * * @param params - 参数 / Parameters * @returns 创建的对象 / Created object */ - create = async (params: { input: ModelServiceCreateInput | ModelProxyCreateInput; config?: Config }): Promise => { + create = async (params: { + input: ModelServiceCreateInput | ModelProxyCreateInput; + config?: Config; + }): Promise => { const { input, config } = params; const cfg = Config.withConfigs(this.config, config); - + try { if ('modelProxyName' in input) { // 处理 ModelProxyCreateInput const modelProxyInput = input as ModelProxyCreateInput; - + // 如果没有设置 proxyModel,根据 endpoints 数量自动判断 if (!modelProxyInput.proxyModel) { const endpoints = _.get(modelProxyInput, 'proxyConfig.endpoints', []); @@ -75,7 +86,7 @@ export class ModelClient { } else { // 处理 ModelServiceCreateInput const modelServiceInput = input as ModelServiceCreateInput; - + const createInput = new $AgentRun.CreateModelServiceInput({ ...modelServiceInput, }); @@ -90,9 +101,10 @@ export class ModelClient { } } catch (e) { if (e instanceof HTTPError) { - const name = 'modelProxyName' in input - ? (input as ModelProxyCreateInput).modelProxyName - : (input as ModelServiceCreateInput).modelServiceName; + const name = + 'modelProxyName' in input + ? (input as ModelProxyCreateInput).modelProxyName + : (input as ModelServiceCreateInput).modelServiceName; throw e.toResourceError('Model', name); } throw e; @@ -102,17 +114,21 @@ export class ModelClient { /** * 删除模型服务 * Delete model service - * + * * @param params - 参数 / Parameters * @returns 删除的对象 / Deleted object - * + * * @throws ResourceNotExistError - 模型服务不存在 / Model service does not exist */ - delete = async (params: { name: string; backendType?: BackendType; config?: Config }): Promise => { + delete = async (params: { + name: string; + backendType?: BackendType; + config?: Config; + }): Promise => { const { name, backendType, config } = params; const cfg = Config.withConfigs(this.config, config); let error: HTTPError | null = null; - + // 如果是 proxy 或未指定类型,先尝试删除 proxy if (backendType === 'proxy' || backendType === undefined) { try { @@ -157,32 +173,36 @@ export class ModelClient { /** * 更新模型服务 * Update model service - * + * * @param params - 参数 / Parameters * @returns 更新后的模型服务对象 / Updated model service object - * + * * @throws ResourceNotExistError - 模型服务不存在 / Model service does not exist */ - update = async (params: { name: string; input: ModelServiceUpdateInput | ModelProxyUpdateInput; config?: Config }): Promise => { + update = async (params: { + name: string; + input: ModelServiceUpdateInput | ModelProxyUpdateInput; + config?: Config; + }): Promise => { const { name, input, config } = params; const cfg = Config.withConfigs(this.config, config); - + if ('proxyModel' in input || 'executionRoleArn' in input) { // 处理 ModelProxyUpdateInput const modelProxyInput = input as ModelProxyUpdateInput; - + try { // 如果没有设置 proxyModel,根据 endpoints 数量自动判断 if (!modelProxyInput.proxyModel && modelProxyInput.proxyModel !== undefined) { const endpoints = _.get(modelProxyInput, 'proxyConfig.endpoints', []); modelProxyInput.proxyModel = endpoints.length > 1 ? 'multi' : 'single'; } - + const updateInput = new $AgentRun.UpdateModelProxyInput({ ...modelProxyInput, proxyMode: modelProxyInput.proxyModel, }); - + const result = await this.controlApi.updateModelProxy({ modelProxyName: name, input: updateInput, @@ -200,12 +220,12 @@ export class ModelClient { } else { // 处理 ModelServiceUpdateInput const modelServiceInput = input as ModelServiceUpdateInput; - + try { const updateInput = new $AgentRun.UpdateModelServiceInput({ ...modelServiceInput, }); - + const result = await this.controlApi.updateModelService({ modelServiceName: name, input: updateInput, @@ -226,17 +246,21 @@ export class ModelClient { /** * 获取模型服务 * Get model service - * + * * @param params - 参数 / Parameters * @returns 模型服务对象 / Model service object - * + * * @throws ResourceNotExistError - 模型服务不存在 / Model service does not exist */ - get = async (params: { name: string; backendType?: BackendType; config?: Config }): Promise => { + get = async (params: { + name: string; + backendType?: BackendType; + config?: Config; + }): Promise => { const { name, backendType, config } = params; const cfg = Config.withConfigs(this.config, config); let error: HTTPError | null = null; - + // 如果是 proxy 或未指定类型,先尝试获取 proxy if (backendType === 'proxy' || backendType === undefined) { try { @@ -281,22 +305,25 @@ export class ModelClient { /** * 列出模型服务 * List model services - * + * * @param params - 参数 / Parameters * @returns 模型服务列表 / Model service list */ - list = async (params?: { input?: ModelServiceListInput | ModelProxyListInput; config?: Config }): Promise => { + list = async (params?: { + input?: ModelServiceListInput | ModelProxyListInput; + config?: Config; + }): Promise => { const { input, config } = params ?? {}; const cfg = Config.withConfigs(this.config, config); - + if (input && 'modelProxyName' in input) { // 处理 ModelProxyListInput const modelProxyInput = input as ModelProxyListInput; - + const request = new $AgentRun.ListModelProxiesRequest({ ...modelProxyInput, }); - + const result = await this.controlApi.listModelProxies({ input: request, config: cfg, @@ -309,11 +336,11 @@ export class ModelClient { } else { // 处理 ModelServiceListInput 或无参数(默认列出 ModelService) const modelServiceInput = (input ?? {}) as ModelServiceListInput; - + const request = new $AgentRun.ListModelServicesRequest({ ...modelServiceInput, }); - + const result = await this.controlApi.listModelServices({ input: request, config: cfg, diff --git a/src/model/index.ts b/src/model/index.ts index c97d007..ab4924a 100644 --- a/src/model/index.ts +++ b/src/model/index.ts @@ -2,14 +2,16 @@ * Model module exports */ -export { ModelClient } from "./client"; -export { ModelService } from "./model-service"; -export { ModelProxy } from "./model-proxy"; +import '@/utils/version-check'; + +export { ModelClient } from './client'; +export { ModelService } from './model-service'; +export { ModelProxy } from './model-proxy'; // Re-export ControlAPI for advanced usage -export { ControlAPI as ModelControlAPI } from "../utils/control-api"; +export { ControlAPI as ModelControlAPI } from '../utils/control-api'; -export { BackendType, ModelType, Provider } from "./model"; +export { BackendType, ModelType, Provider } from './model'; export type { ProviderSettings, @@ -29,4 +31,4 @@ export type { ModelProxyUpdateInput, ModelProxyListInput, ModelProxyData, -} from "./model"; +} from './model'; diff --git a/src/model/model-proxy.ts b/src/model/model-proxy.ts index 1d40df8..54a93ec 100644 --- a/src/model/model-proxy.ts +++ b/src/model/model-proxy.ts @@ -27,10 +27,7 @@ import { */ export class ModelProxy extends ResourceBase - implements - ModelProxyImmutableProps, - ModelProxyMutableProps, - ModelProxySystemProps + implements ModelProxyImmutableProps, ModelProxyMutableProps, ModelProxySystemProps { // ImmutableProps modelType?: ModelProxyImmutableProps['modelType']; @@ -103,10 +100,7 @@ export class ModelProxy * @param params - 参数 / Parameters * @returns 删除的模型代理对象 / Deleted model proxy object */ - static async delete(params: { - name: string; - config?: Config; - }): Promise { + static async delete(params: { name: string; config?: Config }): Promise { const { name, config } = params; return await this.getClient().delete({ name, @@ -136,10 +130,7 @@ export class ModelProxy * @param params - 参数 / Parameters * @returns 模型代理对象 / Model proxy object */ - static async get(params: { - name: string; - config?: Config; - }): Promise { + static async get(params: { name: string; config?: Config }): Promise { const { name, config } = params; return await this.getClient().get({ name, diff --git a/src/model/model-service.ts b/src/model/model-service.ts index e0d627d..18b5b4f 100644 --- a/src/model/model-service.ts +++ b/src/model/model-service.ts @@ -16,7 +16,7 @@ import { ModelServiceListInput, ModelServiceMutableProps, ModelServiceSystemProps, - ModelServiceUpdateInput + ModelServiceUpdateInput, } from './model'; /** @@ -24,10 +24,7 @@ import { */ export class ModelService extends ResourceBase - implements - ModelServiceImmutableProps, - ModelServiceMutableProps, - ModelServiceSystemProps + implements ModelServiceImmutableProps, ModelServiceMutableProps, ModelServiceSystemProps { // ImmutableProps modelInfoConfigs?: ModelServiceImmutableProps['modelInfoConfigs']; @@ -95,10 +92,7 @@ export class ModelService * @param params - 参数 / Parameters * @returns 删除的模型服务对象 / Deleted model service object */ - static async delete(params: { - name: string; - config?: Config; - }): Promise { + static async delete(params: { name: string; config?: Config }): Promise { const { name, config } = params; return await this.getClient().delete({ name, @@ -128,10 +122,7 @@ export class ModelService * @param params - 参数 / Parameters * @returns 模型服务对象 / Model service object */ - static async get(params: { - name: string; - config?: Config; - }): Promise { + static async get(params: { name: string; config?: Config }): Promise { const { name, config } = params; return await this.getClient().get({ name, @@ -265,8 +256,7 @@ export class ModelService } const defaultModel = - this.providerSettings.modelNames && - this.providerSettings.modelNames.length > 0 + this.providerSettings.modelNames && this.providerSettings.modelNames.length > 0 ? this.providerSettings.modelNames[0] : undefined; diff --git a/src/model/model.ts b/src/model/model.ts index 7501b32..d4c5f97 100644 --- a/src/model/model.ts +++ b/src/model/model.ts @@ -20,13 +20,7 @@ export const BackendType = { /** * Model type enum */ -export type ModelType = - | 'llm' - | 'text-embedding' - | 'speech2text' - | 'tts' - | 'rerank' - | 'moderation'; +export type ModelType = 'llm' | 'text-embedding' | 'speech2text' | 'tts' | 'rerank' | 'moderation'; export const ModelType = { LLM: 'llm' as ModelType, @@ -235,8 +229,7 @@ export interface ModelProxySystemProps extends CommonModelSystemProps { } export interface ModelServiceCreateInput - extends ModelServiceImmutableProps, - ModelServiceMutableProps {} + extends ModelServiceImmutableProps, ModelServiceMutableProps {} export interface ModelServiceUpdateInput extends ModelServiceMutableProps {} @@ -249,9 +242,7 @@ export interface ModelServiceListInput extends PageableInput { /** * Model proxy create input */ -export interface ModelProxyCreateInput - extends ModelServiceImmutableProps, - ModelProxyMutableProps {} +export interface ModelProxyCreateInput extends ModelServiceImmutableProps, ModelProxyMutableProps {} /** * Model proxy update input @@ -271,13 +262,9 @@ export interface ModelProxyListInput extends PageableInput { } export interface ModelProxyInterface - extends ModelProxyMutableProps, - ModelProxyImmutableProps, - ModelProxySystemProps {} + extends ModelProxyMutableProps, ModelProxyImmutableProps, ModelProxySystemProps {} export interface ModelServiceInterface - extends ModelServiceMutableProps, - ModelServiceImmutableProps, - ModelServiceSystemProps {} + extends ModelServiceMutableProps, ModelServiceImmutableProps, ModelServiceSystemProps {} /** * Model service data type (complete data structure) @@ -288,4 +275,3 @@ export type ModelServiceData = ModelServiceInterface; * Model proxy data type (complete data structure) */ export type ModelProxyData = ModelProxyInterface; - diff --git a/src/sandbox/aio-sandbox.ts b/src/sandbox/aio-sandbox.ts index 424ca50..46ff40b 100644 --- a/src/sandbox/aio-sandbox.ts +++ b/src/sandbox/aio-sandbox.ts @@ -10,13 +10,7 @@ import { logger } from '../utils/log'; import { ServerError } from '../utils/exception'; import { AioDataAPI } from './api/aio-data'; -import { - CodeLanguage, - NASConfig, - OSSMountConfig, - PolarFsConfig, - TemplateType, -} from './model'; +import { CodeLanguage, NASConfig, OSSMountConfig, PolarFsConfig, TemplateType } from './model'; import { Sandbox } from './sandbox'; /** @@ -70,10 +64,7 @@ export class AioFileSystemOperations { /** * Move a file or directory */ - move = async (params: { - source: string; - destination: string; - }): Promise => { + move = async (params: { source: string; destination: string }): Promise => { return this.sandbox.dataApi.moveFile(params); }; @@ -94,21 +85,14 @@ export class AioFileSystemOperations { /** * Create a directory */ - mkdir = async (params: { - path: string; - parents?: boolean; - mode?: string; - }): Promise => { + mkdir = async (params: { path: string; parents?: boolean; mode?: string }): Promise => { return this.sandbox.dataApi.mkdir(params); }; /** * Upload a file to the sandbox */ - upload = async (params: { - localFilePath: string; - targetFilePath: string; - }): Promise => { + upload = async (params: { localFilePath: string; targetFilePath: string }): Promise => { return this.sandbox.dataApi.uploadFile(params); }; @@ -136,11 +120,7 @@ export class AioProcessOperations { /** * Execute a command in the sandbox */ - cmd = async (params: { - command: string; - cwd: string; - timeout?: number; - }): Promise => { + cmd = async (params: { command: string; cwd: string; timeout?: number }): Promise => { return this.sandbox.dataApi.cmd(params); }; @@ -221,9 +201,7 @@ export class AioContextOperations { /** * Get a specific context by ID */ - get = async (params?: { - contextId?: string; - }): Promise => { + get = async (params?: { contextId?: string }): Promise => { const id = params?.contextId || this._contextId; if (!id) { logger.error('context id is not set'); @@ -439,10 +417,7 @@ export class AioSandbox extends Sandbox { /** * Delete a recording */ - deleteRecording = async (params: { - filename: string; - config?: Config; - }): Promise => { + deleteRecording = async (params: { filename: string; config?: Config }): Promise => { return this.dataApi.deleteRecording(params); }; diff --git a/src/sandbox/api/aio-data.ts b/src/sandbox/api/aio-data.ts index 5c4aa2a..54ca458 100644 --- a/src/sandbox/api/aio-data.ts +++ b/src/sandbox/api/aio-data.ts @@ -6,9 +6,9 @@ * 此模块提供包含代码解释器和浏览器沙箱功能的组合数据 API。 */ -import { Config } from "../../utils/config"; -import { BrowserDataAPI } from "./browser-data"; -import { CodeInterpreterDataAPI } from "./code-interpreter-data"; +import { Config } from '../../utils/config'; +import { BrowserDataAPI } from './browser-data'; +import { CodeInterpreterDataAPI } from './code-interpreter-data'; /** * AIO Data API diff --git a/src/sandbox/api/browser-data.ts b/src/sandbox/api/browser-data.ts index 50ad5bc..ececba7 100644 --- a/src/sandbox/api/browser-data.ts +++ b/src/sandbox/api/browser-data.ts @@ -5,13 +5,13 @@ * 此模块提供浏览器沙箱的数据 API 方法。 */ -import * as fs from "fs"; +import * as fs from 'fs'; -import { Config } from "../../utils/config"; -import { ClientError } from "../../utils/exception"; -import { logger } from "../../utils/log"; +import { Config } from '../../utils/config'; +import { ClientError } from '../../utils/exception'; +import { logger } from '../../utils/log'; -import { SandboxDataAPI } from "./sandbox-data"; +import { SandboxDataAPI } from './sandbox-data'; /** * Browser Data API @@ -35,12 +35,12 @@ export class BrowserDataAPI extends SandboxDataAPI { * Generate the WebSocket URL for Chrome DevTools Protocol (CDP) connection */ getCdpUrl(record?: boolean): string { - const cdpUrl = this.withPath("/ws/automation").replace("http", "ws"); + const cdpUrl = this.withPath('/ws/automation').replace('http', 'ws'); const url = new URL(cdpUrl); - url.searchParams.set("tenantId", this.config.accountId); + url.searchParams.set('tenantId', this.config.accountId); if (record) { - url.searchParams.set("recording", "true"); + url.searchParams.set('recording', 'true'); } return url.toString(); @@ -50,23 +50,22 @@ export class BrowserDataAPI extends SandboxDataAPI { * Generate the WebSocket URL for VNC (Virtual Network Computing) live view connection */ getVncUrl(record?: boolean): string { - const vncUrl = this.withPath("/ws/liveview").replace("http", "ws"); + const vncUrl = this.withPath('/ws/liveview').replace('http', 'ws'); const url = new URL(vncUrl); - url.searchParams.set("tenantId", this.config.accountId); + url.searchParams.set('tenantId', this.config.accountId); if (record) { - url.searchParams.set("recording", "true"); + url.searchParams.set('recording', 'true'); } return url.toString(); } - /** * List all recordings */ listRecordings = async (params?: { config?: Config }): Promise => { - return this.get({ path: "/recordings", config: params?.config }); + return this.get({ path: '/recordings', config: params?.config }); }; /** @@ -107,7 +106,7 @@ export class BrowserDataAPI extends SandboxDataAPI { try { const response = await fetch(url, { - method: "GET", + method: 'GET', headers: reqHeaders, signal: AbortSignal.timeout(cfg.timeout), }); diff --git a/src/sandbox/api/code-interpreter-data.ts b/src/sandbox/api/code-interpreter-data.ts index 423bce8..823bda5 100644 --- a/src/sandbox/api/code-interpreter-data.ts +++ b/src/sandbox/api/code-interpreter-data.ts @@ -5,15 +5,15 @@ * 此模块提供代码解释器沙箱的数据 API 方法。 */ -import * as fs from "fs"; -import * as path from "path"; +import * as fs from 'fs'; +import * as path from 'path'; -import { Config } from "../../utils/config"; -import { ClientError } from "../../utils/exception"; -import { logger } from "../../utils/log"; -import { CodeLanguage } from "../model"; +import { Config } from '../../utils/config'; +import { ClientError } from '../../utils/exception'; +import { logger } from '../../utils/log'; +import { CodeLanguage } from '../model'; -import { SandboxDataAPI } from "./sandbox-data"; +import { SandboxDataAPI } from './sandbox-data'; /** * Code Interpreter Data API @@ -33,11 +33,7 @@ export class CodeInterpreterDataAPI extends SandboxDataAPI { /** * List directory contents */ - async listDirectory(params?: { - path?: string; - depth?: number; - config?: Config; - }): Promise { + async listDirectory(params?: { path?: string; depth?: number; config?: Config }): Promise { const query: Record = {}; if (params?.path !== undefined) { query.path = params.path; @@ -46,7 +42,7 @@ export class CodeInterpreterDataAPI extends SandboxDataAPI { query.depth = params.depth; } - return this.get({ path: "/filesystem", query, config: params?.config }); + return this.get({ path: '/filesystem', query, config: params?.config }); } /** @@ -56,7 +52,7 @@ export class CodeInterpreterDataAPI extends SandboxDataAPI { const query = { path: params.path, }; - return this.get({ path: "/filesystem/stat", query, config: params.config }); + return this.get({ path: '/filesystem/stat', query, config: params.config }); } /** @@ -71,24 +67,20 @@ export class CodeInterpreterDataAPI extends SandboxDataAPI { const data = { path: params.path, parents: params.parents !== undefined ? params.parents : true, - mode: params.mode || "0755", + mode: params.mode || '0755', }; - return this.post({ path: "/filesystem/mkdir", data, config: params.config }); + return this.post({ path: '/filesystem/mkdir', data, config: params.config }); } /** * Move file or directory */ - async moveFile(params: { - source: string; - destination: string; - config?: Config; - }): Promise { + async moveFile(params: { source: string; destination: string; config?: Config }): Promise { const data = { source: params.source, destination: params.destination, }; - return this.post({ path: "/filesystem/move", data, config: params.config }); + return this.post({ path: '/filesystem/move', data, config: params.config }); } /** @@ -98,14 +90,14 @@ export class CodeInterpreterDataAPI extends SandboxDataAPI { const data = { path: params.path, }; - return this.post({ path: "/filesystem/remove", data, config: params.config }); + return this.post({ path: '/filesystem/remove', data, config: params.config }); } /** * List code execution contexts */ async listContexts(params?: { config?: Config }): Promise { - return this.get({ path: "/contexts", config: params?.config }); + return this.get({ path: '/contexts', config: params?.config }); } /** @@ -117,20 +109,18 @@ export class CodeInterpreterDataAPI extends SandboxDataAPI { config?: Config; }): Promise { const language = params?.language || CodeLanguage.PYTHON; - const cwd = params?.cwd || "/home/user"; + const cwd = params?.cwd || '/home/user'; // Validate language parameter - if (language !== "python" && language !== "javascript") { - throw new Error( - `language must be 'python' or 'javascript', got: ${language}`, - ); + if (language !== 'python' && language !== 'javascript') { + throw new Error(`language must be 'python' or 'javascript', got: ${language}`); } const data: Record = { cwd, language, }; - return this.post({ path: "/contexts", data, config: params?.config }); + return this.post({ path: '/contexts', data, config: params?.config }); } /** @@ -152,10 +142,8 @@ export class CodeInterpreterDataAPI extends SandboxDataAPI { }): Promise { const { code, contextId, language, timeout = 30, config } = params; - if (language && language !== "python" && language !== "javascript") { - throw new Error( - `language must be 'python' or 'javascript', got: ${language}`, - ); + if (language && language !== 'python' && language !== 'javascript') { + throw new Error(`language must be 'python' or 'javascript', got: ${language}`); } const data: Record = { @@ -172,7 +160,7 @@ export class CodeInterpreterDataAPI extends SandboxDataAPI { data.contextId = contextId; } - return this.post({ path: "/contexts/execute", data, config }); + return this.post({ path: '/contexts/execute', data, config }); } /** @@ -189,7 +177,7 @@ export class CodeInterpreterDataAPI extends SandboxDataAPI { const query = { path: params.path, }; - return this.get({ path: "/files", query, config: params.config }); + return this.get({ path: '/files', query, config: params.config }); } /** @@ -206,11 +194,11 @@ export class CodeInterpreterDataAPI extends SandboxDataAPI { const data = { path: params.path, content: params.content, - mode: params.mode || "644", - encoding: params.encoding || "utf-8", + mode: params.mode || '644', + encoding: params.encoding || 'utf-8', createDir: params.createDir !== undefined ? params.createDir : true, }; - return this.post({ path: "/files", data, config: params.config }); + return this.post({ path: '/files', data, config: params.config }); } /** @@ -222,7 +210,7 @@ export class CodeInterpreterDataAPI extends SandboxDataAPI { config?: Config; }): Promise { return this.postFile({ - path: "/filesystem/upload", + path: '/filesystem/upload', localFilePath: params.localFilePath, targetFilePath: params.targetFilePath, config: params.config, @@ -239,7 +227,7 @@ export class CodeInterpreterDataAPI extends SandboxDataAPI { }): Promise<{ savedPath: string; size: number }> { const query = { path: params.path }; return this.getFile({ - path: "/filesystem/download", + path: '/filesystem/download', savePath: params.savePath, query, config: params.config, @@ -264,14 +252,14 @@ export class CodeInterpreterDataAPI extends SandboxDataAPI { data.timeout = params.timeout; } - return this.post({ path: "/processes/cmd", data, config: params.config }); + return this.post({ path: '/processes/cmd', data, config: params.config }); } /** * List running processes */ async listProcesses(params?: { config?: Config }): Promise { - return this.get({ path: "/processes", config: params?.config }); + return this.get({ path: '/processes', config: params?.config }); } /** @@ -304,17 +292,13 @@ export class CodeInterpreterDataAPI extends SandboxDataAPI { const url = this.withPath(params.path, params.query); const reqHeaders = this.prepareHeaders({ headers: params.headers, config: params.config }); - delete reqHeaders["Content-Type"]; // Let fetch set it with boundary + delete reqHeaders['Content-Type']; // Let fetch set it with boundary try { const fileContent = await fs.promises.readFile(params.localFilePath); const formData = new FormData(); - formData.append( - "file", - new Blob([fileContent]), - filename, - ); + formData.append('file', new Blob([fileContent]), filename); const data = params.formData || {}; data.path = params.targetFilePath; @@ -325,7 +309,7 @@ export class CodeInterpreterDataAPI extends SandboxDataAPI { const cfg = Config.withConfigs(this.config, params.config); const response = await fetch(url, { - method: "POST", + method: 'POST', headers: reqHeaders, body: formData, signal: AbortSignal.timeout(cfg.timeout), @@ -362,7 +346,7 @@ export class CodeInterpreterDataAPI extends SandboxDataAPI { try { const cfg = Config.withConfigs(this.config, params.config); const response = await fetch(url, { - method: "GET", + method: 'GET', headers: reqHeaders, signal: AbortSignal.timeout(cfg.timeout), }); diff --git a/src/sandbox/api/control.ts b/src/sandbox/api/control.ts index 8040ce6..91bfe1c 100644 --- a/src/sandbox/api/control.ts +++ b/src/sandbox/api/control.ts @@ -9,13 +9,13 @@ // Source: sandbox_control_api.yaml -import * as $AgentRun from "@alicloud/agentrun20250910"; -import * as $Util from "@alicloud/tea-util"; +import * as $AgentRun from '@alicloud/agentrun20250910'; +import * as $Util from '@alicloud/tea-util'; -import { Config } from "../../utils/config"; -import { ControlAPI } from "../../utils/control-api"; -import { ClientError, ServerError } from "../../utils/exception"; -import { logger } from "../../utils/log"; +import { Config } from '../../utils/config'; +import { ControlAPI } from '../../utils/control-api'; +import { ClientError, ServerError } from '../../utils/exception'; +import { logger } from '../../utils/log'; /** * Sandbox Control API @@ -34,7 +34,11 @@ export class SandboxControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns Created Template object */ - createTemplate = async (params: { input: $AgentRun.CreateTemplateInput; headers?: Record; config?: Config }): Promise<$AgentRun.Template> => { + createTemplate = async (params: { + input: $AgentRun.CreateTemplateInput; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.Template> => { const { input, headers, config } = params; try { @@ -48,15 +52,15 @@ export class SandboxControlAPI extends ControlAPI { ); logger.debug( - `request api createTemplate, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([input])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api createTemplate, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([input])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.Template; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -78,29 +82,29 @@ export class SandboxControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns Deleted Template object */ - deleteTemplate = async (params: { templateName: string; headers?: Record; config?: Config }): Promise<$AgentRun.Template> => { + deleteTemplate = async (params: { + templateName: string; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.Template> => { const { templateName, headers, config } = params; try { const client = this.getClient(config); const runtime = new $Util.RuntimeOptions({}); - const response = await client.deleteTemplateWithOptions( - templateName, - headers ?? {}, - runtime - ); + const response = await client.deleteTemplateWithOptions(templateName, headers ?? {}, runtime); logger.debug( - `request api deleteTemplate, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([templateName])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api deleteTemplate, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([templateName])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.Template; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -123,7 +127,12 @@ export class SandboxControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns Updated Template object */ - updateTemplate = async (params: { templateName: string; input: $AgentRun.UpdateTemplateInput; headers?: Record; config?: Config }): Promise<$AgentRun.Template> => { + updateTemplate = async (params: { + templateName: string; + input: $AgentRun.UpdateTemplateInput; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.Template> => { const { templateName, input, headers, config } = params; try { @@ -138,15 +147,15 @@ export class SandboxControlAPI extends ControlAPI { ); logger.debug( - `request api updateTemplate, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([templateName, input])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api updateTemplate, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([templateName, input])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.Template; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -168,29 +177,29 @@ export class SandboxControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns Template object */ - getTemplate = async (params: { templateName: string; headers?: Record; config?: Config }): Promise<$AgentRun.Template> => { + getTemplate = async (params: { + templateName: string; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.Template> => { const { templateName, headers, config } = params; try { const client = this.getClient(config); const runtime = new $Util.RuntimeOptions({}); - const response = await client.getTemplateWithOptions( - templateName, - headers ?? {}, - runtime - ); + const response = await client.getTemplateWithOptions(templateName, headers ?? {}, runtime); logger.debug( - `request api getTemplate, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([templateName])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api getTemplate, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([templateName])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.Template; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -212,29 +221,29 @@ export class SandboxControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns List of Template objects */ - listTemplates = async (params: { input: $AgentRun.ListTemplatesRequest; headers?: Record; config?: Config }): Promise<$AgentRun.ListTemplatesOutput> => { + listTemplates = async (params: { + input: $AgentRun.ListTemplatesRequest; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.ListTemplatesOutput> => { const { input, headers, config } = params; try { const client = this.getClient(config); const runtime = new $Util.RuntimeOptions({}); - const response = await client.listTemplatesWithOptions( - input, - headers ?? {}, - runtime - ); + const response = await client.listTemplatesWithOptions(input, headers ?? {}, runtime); logger.debug( - `request api listTemplates, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([input])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api listTemplates, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([input])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.ListTemplatesOutput; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -256,7 +265,11 @@ export class SandboxControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns Created Sandbox object */ - createSandbox = async (params: { input: $AgentRun.CreateSandboxInput; headers?: Record; config?: Config }): Promise<$AgentRun.Sandbox> => { + createSandbox = async (params: { + input: $AgentRun.CreateSandboxInput; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.Sandbox> => { const { input, headers, config } = params; try { @@ -270,15 +283,15 @@ export class SandboxControlAPI extends ControlAPI { ); logger.debug( - `request api createSandbox, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([input])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api createSandbox, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([input])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.Sandbox; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -300,29 +313,29 @@ export class SandboxControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns Deleted Sandbox object */ - deleteSandbox = async (params: { sandboxId: string; headers?: Record; config?: Config }): Promise<$AgentRun.Sandbox> => { + deleteSandbox = async (params: { + sandboxId: string; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.Sandbox> => { const { sandboxId, headers, config } = params; try { const client = this.getClient(config); const runtime = new $Util.RuntimeOptions({}); - const response = await client.deleteSandboxWithOptions( - sandboxId, - headers ?? {}, - runtime - ); + const response = await client.deleteSandboxWithOptions(sandboxId, headers ?? {}, runtime); logger.debug( - `request api deleteSandbox, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([sandboxId])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api deleteSandbox, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([sandboxId])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.Sandbox; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -344,29 +357,29 @@ export class SandboxControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns Stopped Sandbox object */ - stopSandbox = async (params: { sandboxId: string; headers?: Record; config?: Config }): Promise<$AgentRun.Sandbox> => { + stopSandbox = async (params: { + sandboxId: string; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.Sandbox> => { const { sandboxId, headers, config } = params; try { const client = this.getClient(config); const runtime = new $Util.RuntimeOptions({}); - const response = await client.stopSandboxWithOptions( - sandboxId, - headers ?? {}, - runtime - ); + const response = await client.stopSandboxWithOptions(sandboxId, headers ?? {}, runtime); logger.debug( - `request api stopSandbox, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([sandboxId])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api stopSandbox, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([sandboxId])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.Sandbox; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -388,29 +401,29 @@ export class SandboxControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns Sandbox object */ - getSandbox = async (params: { sandboxId: string; headers?: Record; config?: Config }): Promise<$AgentRun.Sandbox> => { + getSandbox = async (params: { + sandboxId: string; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.Sandbox> => { const { sandboxId, headers, config } = params; try { const client = this.getClient(config); const runtime = new $Util.RuntimeOptions({}); - const response = await client.getSandboxWithOptions( - sandboxId, - headers ?? {}, - runtime - ); + const response = await client.getSandboxWithOptions(sandboxId, headers ?? {}, runtime); logger.debug( - `request api getSandbox, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([sandboxId])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api getSandbox, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([sandboxId])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.Sandbox; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -432,29 +445,29 @@ export class SandboxControlAPI extends ControlAPI { * @param params.config - Optional config override * @returns List of Sandbox objects */ - listSandboxes = async (params: { input: $AgentRun.ListSandboxesRequest; headers?: Record; config?: Config }): Promise<$AgentRun.ListSandboxesOutput> => { + listSandboxes = async (params: { + input: $AgentRun.ListSandboxesRequest; + headers?: Record; + config?: Config; + }): Promise<$AgentRun.ListSandboxesOutput> => { const { input, headers, config } = params; try { const client = this.getClient(config); const runtime = new $Util.RuntimeOptions({}); - const response = await client.listSandboxesWithOptions( - input, - headers ?? {}, - runtime - ); + const response = await client.listSandboxesWithOptions(input, headers ?? {}, runtime); logger.debug( - `request api listSandboxes, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([input])}\n response: ${JSON.stringify(response.body?.data)}`, + `request api listSandboxes, request Request ID: ${response.body?.requestId}\n request: ${JSON.stringify([input])}\n response: ${JSON.stringify(response.body?.data)}` ); return response.body?.data as $AgentRun.ListSandboxesOutput; } catch (error: unknown) { - if (error && typeof error === "object" && "statusCode" in error) { + if (error && typeof error === 'object' && 'statusCode' in error) { const e = error as { statusCode: number; message: string; data?: { requestId?: string } }; const statusCode = e.statusCode; - const message = e.message || "Unknown error"; + const message = e.message || 'Unknown error'; const requestId = e.data?.requestId; if (statusCode >= 400 && statusCode < 500) { @@ -466,5 +479,4 @@ export class SandboxControlAPI extends ControlAPI { throw error; } }; - } diff --git a/src/sandbox/api/sandbox-data.ts b/src/sandbox/api/sandbox-data.ts index 9d6f84f..1f11f92 100644 --- a/src/sandbox/api/sandbox-data.ts +++ b/src/sandbox/api/sandbox-data.ts @@ -5,23 +5,23 @@ * 此模块提供用于与 AgentRun Sandbox Data API 交互的 HTTP 客户端。 */ -import * as $AgentRun from "@alicloud/agentrun20250910"; -import * as $Util from "@alicloud/tea-util"; +import * as $AgentRun from '@alicloud/agentrun20250910'; +import * as $Util from '@alicloud/tea-util'; -import { Config } from "../../utils/config"; -import { ControlAPI } from "../../utils/control-api"; -import { ClientError } from "../../utils/exception"; -import { logger } from "../../utils/log"; +import { Config } from '../../utils/config'; +import { ControlAPI } from '../../utils/control-api'; +import { ClientError } from '../../utils/exception'; +import { logger } from '../../utils/log'; /** * Resource type enum */ export enum ResourceType { - Runtime = "runtime", - LiteLLM = "litellm", - Tool = "tool", - Template = "template", - Sandbox = "sandbox", + Runtime = 'runtime', + LiteLLM = 'litellm', + Tool = 'tool', + Template = 'template', + Sandbox = 'sandbox', } /** @@ -43,9 +43,9 @@ export class SandboxDataAPI { config?: Config; namespace?: string; }) { - const { config, namespace = "sandboxes" } = params; + const { config, namespace = 'sandboxes' } = params; - this.resourceName = ""; + this.resourceName = ''; this.resourceType = ResourceType.Template; this.namespace = namespace; this.config = config || new Config(); @@ -75,7 +75,7 @@ export class SandboxDataAPI { } else if (templateName) { this.resourceName = templateName; this.resourceType = ResourceType.Template; - this.namespace = "sandboxes"; + this.namespace = 'sandboxes'; } if (cachedToken) { @@ -101,25 +101,20 @@ export class SandboxDataAPI { /** * Construct full URL with path and query parameters */ - protected withPath( - path: string, - query?: Record, - ): string { + protected withPath(path: string, query?: Record): string { // Remove leading slash - path = path.replace(/^\//, ""); + path = path.replace(/^\//, ''); // Build base URL - const parts = [this.getBaseUrl(), this.namespace, path].filter( - (p) => p && p.length > 0, - ); - let url = parts.join("/").replace(/\/+/g, "/").replace(/:\//g, "://"); + const parts = [this.getBaseUrl(), this.namespace, path].filter(p => p && p.length > 0); + let url = parts.join('/').replace(/\/+/g, '/').replace(/:\//g, '://'); // Add query parameters if (query && Object.keys(query).length > 0) { const urlObj = new URL(url); Object.entries(query).forEach(([key, value]) => { if (Array.isArray(value)) { - value.forEach((v) => urlObj.searchParams.append(key, String(v))); + value.forEach(v => urlObj.searchParams.append(key, String(v))); } else if (value !== undefined && value !== null) { urlObj.searchParams.append(key, String(value)); } @@ -138,20 +133,13 @@ export class SandboxDataAPI { // If token is provided in config, use it directly if (cfg.token) { - logger.debug( - `Using provided access token from config: ${this.maskToken(cfg.token)}`, - ); + logger.debug(`Using provided access token from config: ${this.maskToken(cfg.token)}`); this.accessToken = cfg.token; return; } // Fetch access token from control API if needed - if ( - !this.accessToken && - this.resourceName && - this.resourceType && - !cfg.token - ) { + if (!this.accessToken && this.resourceName && this.resourceType && !cfg.token) { try { const controlApi = new ControlAPI(cfg); const client = (controlApi as any).getClient(cfg); @@ -173,11 +161,11 @@ export class SandboxDataAPI { this.accessToken = response.body?.data?.accessToken; logger.debug( - `Fetched access token for resource ${this.resourceName} of type ${this.resourceType}: ${this.maskToken(this.accessToken || "")}`, + `Fetched access token for resource ${this.resourceName} of type ${this.resourceType}: ${this.maskToken(this.accessToken || '')}` ); } catch (error) { logger.warn( - `Failed to get access token for ${this.resourceType}(${this.resourceName}): ${error}`, + `Failed to get access token for ${this.resourceType}(${this.resourceName}): ${error}` ); } } @@ -188,7 +176,7 @@ export class SandboxDataAPI { */ protected maskToken(token: string): string { if (!token || token.length <= 8) { - return "***"; + return '***'; } return `${token.substring(0, 4)}...${token.substring(token.length - 4)}`; } @@ -203,9 +191,9 @@ export class SandboxDataAPI { const cfg = Config.withConfigs(this.config, params.config); const reqHeaders: Record = { - "Content-Type": "application/json", - "User-Agent": "AgentRunDataClient-Node/1.0", - "Agentrun-Access-Token": cfg.token || this.accessToken || "", + 'Content-Type': 'application/json', + 'User-Agent': 'AgentRunDataClient-Node/1.0', + 'Agentrun-Access-Token': cfg.token || this.accessToken || '', ...cfg.headers, ...(params.headers || {}), }; @@ -236,7 +224,7 @@ export class SandboxDataAPI { Object.entries(query).forEach(([key, value]) => { if (value !== undefined && value !== null) { if (Array.isArray(value)) { - value.forEach((v) => urlObj.searchParams.append(key, String(v))); + value.forEach(v => urlObj.searchParams.append(key, String(v))); } else { urlObj.searchParams.append(key, String(value)); } @@ -246,7 +234,7 @@ export class SandboxDataAPI { } logger.debug( - `${method} ${finalUrl} headers=${JSON.stringify(reqHeaders)} data=${JSON.stringify(data)}`, + `${method} ${finalUrl} headers=${JSON.stringify(reqHeaders)} data=${JSON.stringify(data)}` ); try { @@ -269,8 +257,8 @@ export class SandboxDataAPI { const errorMsg = `Failed to parse JSON response: ${error}`; logger.error(errorMsg); - if (response.status === 502 && responseText.includes("502 Bad Gateway")) { - throw new ClientError(response.status, "502 Bad Gateway"); + if (response.status === 502 && responseText.includes('502 Bad Gateway')) { + throw new ClientError(response.status, '502 Bad Gateway'); } throw new ClientError(response.status, errorMsg); @@ -299,7 +287,7 @@ export class SandboxDataAPI { }): Promise { const url = this.withPath(params.path, params.query); return this.makeRequest({ - method: "GET", + method: 'GET', url, headers: params.headers, config: params.config, @@ -318,7 +306,7 @@ export class SandboxDataAPI { }): Promise { const url = this.withPath(params.path, params.query); return this.makeRequest({ - method: "POST", + method: 'POST', url, data: params.data, headers: params.headers, @@ -338,7 +326,7 @@ export class SandboxDataAPI { }): Promise { const url = this.withPath(params.path, params.query); return this.makeRequest({ - method: "PUT", + method: 'PUT', url, data: params.data, headers: params.headers, @@ -358,7 +346,7 @@ export class SandboxDataAPI { }): Promise { const url = this.withPath(params.path, params.query); return this.makeRequest({ - method: "PATCH", + method: 'PATCH', url, data: params.data, headers: params.headers, @@ -377,7 +365,7 @@ export class SandboxDataAPI { }): Promise { const url = this.withPath(params.path, params.query); return this.makeRequest({ - method: "DELETE", + method: 'DELETE', url, headers: params.headers, config: params.config, @@ -387,16 +375,16 @@ export class SandboxDataAPI { /** * Check sandbox health */ - checkHealth = async (params: { + checkHealth = async (params: { sandboxId: string; - config?: Config + config?: Config; }): Promise<{ status: string; [key: string]: any }> => { await this.refreshAccessToken({ sandboxId: params.sandboxId, config: params.config, }); - - return this.get({ path: "/health", config: params.config }); + + return this.get({ path: '/health', config: params.config }); }; /** @@ -434,7 +422,7 @@ export class SandboxDataAPI { } return this.post({ - path: "/", + path: '/', data, }); }; @@ -442,45 +430,36 @@ export class SandboxDataAPI { /** * Delete sandbox */ - deleteSandbox = async (params: { - sandboxId: string; - config?: Config; - }): Promise => { + deleteSandbox = async (params: { sandboxId: string; config?: Config }): Promise => { await this.refreshAccessToken({ sandboxId: params.sandboxId, config: params.config, }); - return this.delete({ path: "/" }); + return this.delete({ path: '/' }); }; /** * Stop sandbox */ - stopSandbox = async (params: { - sandboxId: string; - config?: Config; - }): Promise => { + stopSandbox = async (params: { sandboxId: string; config?: Config }): Promise => { await this.refreshAccessToken({ sandboxId: params.sandboxId, config: params.config, }); - return this.post({ path: "/stop" }); + return this.post({ path: '/stop' }); }; /** * Get sandbox info */ - getSandbox = async (params: { - sandboxId: string; - config?: Config; - }): Promise => { + getSandbox = async (params: { sandboxId: string; config?: Config }): Promise => { await this.refreshAccessToken({ sandboxId: params.sandboxId, config: params.config, }); - return this.get({ path: "/" }); + return this.get({ path: '/' }); }; } diff --git a/src/sandbox/browser-sandbox.ts b/src/sandbox/browser-sandbox.ts index 09058f9..81b3528 100644 --- a/src/sandbox/browser-sandbox.ts +++ b/src/sandbox/browser-sandbox.ts @@ -8,12 +8,7 @@ import { Config } from '../utils/config'; import { BrowserDataAPI } from './api/browser-data'; -import { - NASConfig, - OSSMountConfig, - PolarFsConfig, - TemplateType, -} from './model'; +import { NASConfig, OSSMountConfig, PolarFsConfig, TemplateType } from './model'; import { Sandbox } from './sandbox'; /** @@ -122,10 +117,7 @@ export class BrowserSandbox extends Sandbox { /** * Delete a recording */ - deleteRecording = async (params: { - filename: string; - config?: Config; - }): Promise => { + deleteRecording = async (params: { filename: string; config?: Config }): Promise => { return this.dataApi.deleteRecording(params); }; } diff --git a/src/sandbox/client.ts b/src/sandbox/client.ts index 01c345c..74bd8b0 100644 --- a/src/sandbox/client.ts +++ b/src/sandbox/client.ts @@ -51,15 +51,12 @@ export class SandboxClient { * Create a Template */ createTemplate: { - (params: { - input: TemplateCreateInput; - config?: Config; - }): Promise