@ computesdk/ aws (帮助)
计算SDK的AWS供应商,每个子路径一个产品:
| 导入 | 产品 |
|---|---|
@computesdk/aws/agentcore | Bedrock Agent Core 代码口译会话 |
@computesdk/aws/ec2 | EC2 实例( 点播或点播), 对 SSM 的命令 |
欧共体2
AWS EC2 计算SDK的提供者. 每个沙盒都是从您的发射模板上推出的 EC2 实例,按需
默认或选择加入时的 Spot。 运行的命令
SSM 运行命令 (单位:千美元)AWS-RunShellScript) (中文(简体) ).
盒子上没有代理或网关,也没有入境端口:预先安装的SSM代理拨出.
安装
npm install @computesdk/aws
使用量
import { ec2 } from '@computesdk/aws/ec2';
// On-demand, everything else comes from the launch template
const compute = ec2({ launchTemplate: 'my-template' }); // region from AWS_REGION
const sandbox = await compute.instances.create();
const result = await sandbox.runCommand('node -v', { env: { CI: '1' }, cwd: '/tmp', timeout: 60_000 });
console.log(result.exitCode, result.stdout);
await sandbox.destroy();
点
import { ec2, isEc2CapacityError } from '@computesdk/aws/ec2';
const compute = ec2({
region: 'us-east-2',
launchTemplate: 'computesdk-market-medium',
instanceType: [
'c5d.large', 'm7a.large', 'c6in.large', 'r5a.large', 'm5a.large', 'r5ad.large', 'r5b.large',
'r5n.large', 'c5a.large', 'r6a.large', 'm5ad.large', 'r6in.large', 'm6in.large',
],
spot: { maxPricePerHour: '0.05' },
});
try {
const sandbox = await compute.instances.create({ name: 'bench-1', metadata: { listing: 'lst_42' } });
} catch (error) {
if (isEc2CapacityError(error)) console.log('No Spot capacity right now:', error.codes);
else throw error;
}
配置
| 选项 | 需求 | 说明 |
|---|---|---|
launchTemplate | 对 | 启动模板名称或 id (lt-...(中文(简体) ) |
region | 没有 | AWS 区域; 返回 AWS_REGION |
instanceType | 没有 | 一个类型,或者一个要倒回去的列表。 默认: 发射模板的 |
subnetIds | 没有 | 子网回倒过去,每AZ一个. 默认: 发射模板的 |
spot | 没有 | true 或者说 { maxPricePerHour } 点。默认值:按需 |
credentials | 没有 | AwsCredentialIdentity 或者说 AwsCredentialIdentityProvider默认: AWS SDK 证书链 |
launchTemplateVersion | 没有 | 默认 $Default |
高级 : readyTimeoutMs (默认) 120000, (中文(简体) ), pollIntervalMs (默认) 2000, (中文(简体) ),
maxOutputBytes (默认 4 MiB), outputS3Bucket 编号 : outputS3KeyPrefix (见下文大产出).
发射模板拥有 AMI, IMDS 设置, root 音量, 安全组, 网络, 以及实例配置 允许 SSM。 供货商从来不放这些.
一次简单的点播(最多一次) instanceType,没有 subnetIds)是单人 RunInstances 电话 点点,
多个实例类型,或 subnetIds 使用即时 EC2 船队在每类 X 子网对上
(单位:千美元)price-capacity-optimized 用于点.
如果你的发射模板没有锁定子网,请通过 subnetIds;否则AWS会倒回默认的VPC.
全权证书
配置中没有 API 密钥 。 通过一个短寿命证书的认证提供者,例如,在Vercel上与OIDC:
import { awsCredentialsProvider } from '@vercel/functions/oidc';
ec2({ launchTemplate: 'my-template', credentials: awsCredentialsProvider({ roleArn: process.env.AWS_ROLE_ARN! }) });
行为
- 沙盒标识 是 EC2 实例 ID.
- 标记: 实例和卷被标记
computesdk:managed=true(IAM政策可以以此为条件),computesdk:sandbox-name何时name设置, 每个字符串metadata值(已解密为EC2标记限制,最大为50标记). - 能力:没有因容量、价格或配额错误而发射实例,
create掷出Ec2CapacityError(单位:千美元)code: 'AWS_EC2_CAPACITY_UNAVAILABLE', (中文(简体) ),codes, (中文(简体) ),errors) (中文(简体) ). 其他舰队故障Ec2FleetError。 。 。 . - 准备情况数字 :
create当实例出现时返回Online(原始内容存档于2019-03-29). In SSM. 超时( E)Ec2ReadyTimeoutError或任意 丢弃前终止实例出错 .create({ timeout })覆盖readyTimeoutMs。 。 。 . - 以根运行的命令 通过
AWS-RunShellScript。 。 。 .env导出和cwd以相同的脚本输入;timeout地图到 SSMexecutionTimeout(秒,四舍五入). 超时命令返回退出代码124。 。 。 . - 大型产出: SSM 最多返回24000个字符 stdout和8000个 stderr inline. 更大的输出写入
/tmp/computesdk-ssm/在实例中,并在 ~17 KB 块中读取(少数 SSM 调用平行,然后被删除), 大约是15-30 s / MB。 每条溪流保留最后一道maxOutputBytes(默认) 4 MiB)和 Stderr 注意到任何切口。 对于大输出, 设置outputS3Bucket(实例简介需要)s3:PutObject和召唤者s3:GetObject: SSM 在那里写入全部输出, 在一个请求中获取 . getById返回时null用于未知、已终止/已关闭或未标记的情况.list已管理返回pending编号 :running实例.destroy并拒绝终止未标记的事件.getInstance()编号 :getInfo().metadata曝光实例类型、AZ、子网、生命周期(spot编号 :on-demand),和发射时间.- 不支持 :
getUrl(无入站流量)和文件系统API.
测试
pnpm test # unit tests (mocked AWS)
# real AWS: any Ec2Config as JSON
AWS_EC2_INTEGRATION_CONFIG='{"launchTemplate":"my-template","region":"us-east-2","instanceType":"m7a.large"}' pnpm test
特工科雷
AWS Bedrock 代理 Core 代码解释器 计算SDK的提供者:安全, 完全管理,基于会话的沙盒用于运行代码和 shell 命令,没有提供基础设施. 每个 沙盒映射到代理 Core 代码解释会话 .
npm install @computesdk/aws
import { agentcore } from '@computesdk/aws/agentcore';
原载 @computesdk/agentcore,它现在是一个被腐烂的再出口 这个子路径.
认证
提供者使用 标准 AWS 证书提供链 ——与AWS CLI相同的分辨率命令. 您没有通过 API 密钥; 您认证到 AWS 时, 您通常会:
- 环境变量
AWS_ACCESS_KEY_ID, (中文(简体) ),AWS_SECRET_ACCESS_KEY, (中文(简体) ),AWS_SESSION_TOKEN(中文(简体) ) - SSO会议
aws sso login(中文(简体) ) - 命名简介( E)
AWS_PROFILE,或profile在配置中) - EC2/ECS/EKS实例作用
A 类 区域 需要,通过 region 在配置中或 AWS_REGION 编号 : AWS_DEFAULT_REGION。 。 。 .
IAM 权限
主要需要这些 bedrock-agentcore 代码解释器上的动作 :
bedrock-agentcore:StartCodeInterpreterSessionbedrock-agentcore:InvokeCodeInterpreterbedrock-agentcore:StopCodeInterpreterSessionbedrock-agentcore:GetCodeInterpreterSession(计:getById(中文(简体) )bedrock-agentcore:ListCodeInterpreterSessions(计:list(中文(简体) )
使用量
import { compute } from 'computesdk';
import { agentcore } from '@computesdk/aws/agentcore';
// Uses the default AWS credential chain; region from env or config.
compute.setConfig({ defaultProvider: agentcore({ region: 'us-west-2' }) });
const sandbox = await compute.instances.create();
const result = await sandbox.runCommand('echo "Hello from AgentCore" && python3 -c "print(2 + 2)"');
console.log(result.stdout); // Hello from AgentCore\n4
await sandbox.filesystem.writeFile('/tmp/data.txt', 'persisted across calls');
console.log(await sandbox.filesystem.readFile('/tmp/data.txt'));
await sandbox.destroy();
使用命名的配置文件
agentcore({ region: 'us-west-2', profile: 'my-profile' });
使用明确/临时全权证书
agentcore({
region: 'us-west-2',
credentials: {
accessKeyId: '...',
secretAccessKey: '...',
sessionToken: '...', // temporary credentials supported
},
});
配置
| 选项 | 类型 | 说明 |
|---|---|---|
region | string | AWS地区. 倒计时 AWS_REGION 编号 : AWS_DEFAULT_REGION。 。 。 . |
codeInterpreterIdentifier | string | 要使用的代码解释器 。 管理对象的默认值 aws.codeinterpreter.v1。 。 。 . |
profile | string | 命名用于证书的 AWS 配置文件 . |
credentials | AwsCredentialIdentity | AwsCredentialIdentityProvider | 明确全权证书。 关闭使用默认的链条 . |
sessionTimeoutSeconds | number | 会话空闲超时以秒计( 最大 28800 / 8h) 。 默认900. 被每个..create timeout (数). |
API 参考
命令执行
// Run a shell command
const result = await sandbox.runCommand('echo "Hello" && ls -la');
console.log(result.stdout, result.stderr, result.exitCode);
// Run Python
const py = await sandbox.runCommand('python3 -c "print(2 + 2)"');
// Run a multi-line script via heredoc
const script = await sandbox.runCommand(`python3 - <<'PY'
import json
print(json.dumps({"ok": True}))
PY`);
// Pass environment variables and a working directory
await sandbox.runCommand('printenv TOKEN', { env: { TOKEN: 'abc' }, cwd: '/tmp' });
// Install packages
await sandbox.runCommand('pip install requests');
runCommand 从不丢弃命令失败——返回非零退出 exitCode,与 stdout编号 :stderr 分开抓.
文件系统操作
await sandbox.filesystem.writeFile('/tmp/hello.py', 'print("Hello World")');
const content = await sandbox.filesystem.readFile('/tmp/hello.py');
await sandbox.filesystem.mkdir('/tmp/data');
const files = await sandbox.filesystem.readdir('/tmp'); // FileEntry[]
const exists = await sandbox.filesystem.exists('/tmp/hello.py');
await sandbox.filesystem.remove('/tmp/hello.py');
文件系统调用在文本上运行(UTF-8). 要移动二进制数据,请在
沙盒( r)runCommand('curl -sL URL -o /tmp/file'))或基数64 runCommand。 。 。 .
沙盒管理
const info = await sandbox.getInfo(); // { id, provider, status, createdAt, timeout, metadata }
const existing = await provider.sandbox.getById(sandbox.instanceId); // or null if terminated
const all = await provider.sandbox.list(); // READY sessions
await sandbox.destroy();
处理错误
create 将常见的 AWS 失败转化为可操作的信息 :
try {
const sandbox = await compute.instances.create();
} catch (err) {
// e.g. "Missing AWS region for AgentCore. Pass it: agentcore({ region: 'us-west-2' }) ..."
// or "AWS authentication failed for AgentCore. Check your credentials ..."
// or "Access denied ... Ensure your IAM principal allows bedrock-agentcore:*CodeInterpreter* ..."
console.error(err.message);
}
runCommand返回时exitCode: 127打开错误stderr如果援引本身失败(例如会议已过),它不会放弃.- 文件系统操作在失败时抛出(例如读取缺失的文件).
实例
数据处理
const sandbox = await compute.instances.create();
await sandbox.filesystem.writeFile('/tmp/data.csv', 'value\n10\n20\n30\n');
const result = await sandbox.runCommand(`python3 - <<'PY'
import csv, json
with open('/tmp/data.csv') as f:
values = [int(r['value']) for r in csv.DictReader(f)]
print(json.dumps({'count': len(values), 'sum': sum(values), 'mean': sum(values)/len(values)}))
PY`);
console.log(JSON.parse(result.stdout)); // { count: 3, sum: 60, mean: 20 }
await sandbox.destroy();
作为AI代理工具
普遍性 InstanceInterface 接口映射到代理框架工具上——每个包
工具中的方法并将其交给您的代理(与任何代理SDK合作):
import { tool } from '@strands-agents/sdk';
import { z } from 'zod';
const runCommand = tool({
name: 'run_command',
description: 'Run a shell command in the sandbox.',
inputSchema: z.object({ command: z.string() }),
callback: async ({ command }) => {
const r = await sandbox.runCommand(command);
return { stdout: r.stdout, stderr: r.stderr, exitCode: r.exitCode };
},
});
// ...similarly wrap writeFile / readFile / readdir, then: new Agent({ tools: [...] })
支持的运行时间
管理 aws.codeinterpreter.v1 配有 Python 和标准的 Linux shell 的翻译船,所以在该环境中可用的任何语言运行时间都可以通过 runCommand。 。 。 .
限制
- 没有预览 URL/ 端口 . Agent Core Code 解释器没有进入的网络端点,所以
getUrl()掷出. 用于代码执行,而不是托管dev服务器. - 没有交互 PTY . 命令是请求/答复;没有双向终端.
- 会话到期. 会话在闲置超时后自动终止; 之后创建一个新的沙盒 .
- 文件系统持续存在, shell 环境没有. 整个文件幸存
runCommand呼叫,但每个命令 运行在一个新贝壳中——cd, (中文(简体) ),export,而 shell 变量不会结转。 将它们锁在一个单一的命令中(例如:.cd /app && npm test)或使用cwd编号 :env选项. - 背景命令不会超过呼叫.
runCommand(..., { background: true })返回,但当引用结束时 Agent Core 终止进程树,所以任务被杀死而不是被留下运行。 使用运行到完成的单个命令 . - 大写作被块. 为了遵守Core探员的指挥范围,
writeFile上传基数64以~60KB块表示——每60KB大约一个回转,所以5MB文件需要~40s. 阅读为单回行并快. - 每场会议同时进行~10个业务. Agent Core 对单会话同时援引; 超过~10 时同时引用
runCommand/filesystem 调用,额外调用会因配额错误而失败. 将重相平行力分散在多个沙盒中.
许可证
麻省理工学院