1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

OpenAI Agents SDKのSandbox、execはcmdプロパティで動いた

1
Posted at

はじめに

対象読者は、OpenAI Agents SDK(TypeScript版)でエージェントに隔離実行環境を持たせたい開発者です。npm パッケージ @openai/agents には Python 版と同じ Sandbox Agents 機能がありますが、TypeScript 版を実コードで解説した記事はまだ少なく、公式ドキュメント通りに書いても動かない箇所がありました。

TL;DR

  • @openai/agents の Sandbox 機能は @openai/agents/sandbox ではなく @openai/agents/sandbox/local からインポートする(直下エクスポートには UnixLocalSandboxClient が含まれていない)
  • コマンド実行は session.exec({ command: '...' }) ではなく session.exec({ cmd: '...' })。プロパティ名を間違えると内部の manifest パス置換処理が undefined.replace で落ちる
  • materializeEntry() での直接ファイル書き込みは { path, entry: { type: 'file', content } } の形が正解。entry を省略したり type を kind と書くと弾かれる。急ぐならシェルのリダイレクト(echo ... > file)経由の書き込みでも同じ結果になる
  • OpenAI API キーなしでもサンドボックスセッションの作成・コマンド実行・ファイル操作までは動く(エージェントループを回す部分だけが API キーを要求する)

Sandbox Agentsとは

Sandbox Agents は、Agents SDK がエージェントに「隔離されたファイルシステムとシェル」を持たせる仕組みです(OpenAI Agents SDK 公式ドキュメント)。ハーネス(モデル呼び出し・ツールルーティング・承認フロー・トレーシングを司る制御層)とサンドボックス(実際にファイル読み書きやコマンド実行が起きる実行層)が分離されており、ローカル開発では UnixLocalSandboxClient、Windows や本番運用では Docker ベースのクライアントを選べます。

TypeScript 版 SDK は npm に @openai/agents として公開されており、npm の公開ダウンロード統計によれば2026年2月〜3月の30日間で約152万件のダウンロードがありました(OpenAI 公式ブログ・2026年4月発表でも紹介)。

環境構築

Node.js 22 以上が必要です。今回は Node.js v22.22.2 で検証しました。

mkdir agents-sdk-test && cd agents-sdk-test
npm init -y
npm install @openai/agents zod

インストール自体は 25 パッケージが数秒で入り、脆弱性の警告もありませんでした。ここまでは公式手順どおりです。

つまずきポイント1: インポートパス

公式ドキュメントの Quickstart は UnixLocalSandboxClient の使い方を示していますが、素直に @openai/agents/sandbox からインポートすると失敗します。

// これは失敗する
import { UnixLocalSandboxClient } from '@openai/agents/sandbox';
// SyntaxError: The requested module '@openai/agents/sandbox' does not provide an export named 'UnixLocalSandboxClient'

node_modules/@openai/agents/package.json の exports フィールドを確認すると、サブパスごとにエクスポートが分かれていることが分かります。

node -e "console.log(JSON.stringify(require('./node_modules/@openai/agents/package.json').exports, null, 2))"

./sandbox は Manifest や各種エラークラス・マウントヘルパーなど抽象度の高いものだけを公開しており、UnixLocalSandboxClient の実体は ./sandbox/local サブパスに置かれています。これは 公式サンプル が実際に使っているインポート経路と一致します。

// これが正解(公式サンプルと同じ経路)
import { UnixLocalSandboxClient } from '@openai/agents/sandbox/local';

内部依存の @openai/agents-core/sandbox/local からも同じクラスをインポートできますが、公式サンプルに揃えるなら @openai/agents/sandbox/local を使うのが安全です。

つまずきポイント2: execのプロパティ名

インポートが直れば、次はセッションを作ってコマンドを実行します。

const client = new UnixLocalSandboxClient();
const session = await client.create({});

const result = await session.exec({ command: 'echo hi' });

これも実行すると内部で例外が飛びます。

TypeError: Cannot read properties of undefined (reading 'replace')
    at translateManifestRootCommandInput (.../sandbox/sandboxes/unixLocal.mjs:848:20)

エラーメッセージからは原因が読み取りにくいのですが、型定義ファイル(node_modules/@openai/agents-core/dist/sandbox/session.d.ts)を見ると ExecCommandArgs の実際のプロパティ名が判明します。

export type ExecCommandArgs = {
    cmd: string;
    workdir?: string;
    shell?: string;
    login?: boolean;
    tty?: boolean;
    yieldTimeMs?: number;
    maxOutputTokens?: number;
    runAs?: string;
};

command ではなく cmd が正しいプロパティ名でした。渡したオブジェクトに cmd が存在しないため、内部でコマンド文字列に対して行う manifest ルートパスの置換処理が undefined.replace(...) を呼んで落ちていたわけです。修正して実行すると、期待どおりの結果が返ります。

const result = await session.exec({ cmd: 'echo hello-from-sandbox && node --version && pwd' });
console.log(result);
{
  "output": "hello-from-sandbox\nv22.22.2\n/workspace\n",
  "stdout": "hello-from-sandbox\nv22.22.2\n/workspace\n",
  "stderr": "",
  "wallTimeSeconds": 0.122,
  "exitCode": 0
}

サンドボックス内部のワークスペースは /workspace に隔離されており、ホスト側の Node.js(v22.22.2)がそのまま動いていることも確認できました。

つまずきポイント3: materializeEntryのentryはネストしたオブジェクト

Sandbox Agents にはファイルを直接書き込む materializeEntry() というメソッドがあります。エージェントのツール呼び出しを介さずファイルを流し込みたいときに使う想定のAPIです。最初に次のような呼び方を試しましたが、2段階で失敗しました。

// 失敗1: entry がトップレベルに無い
await session.materializeEntry({
  path: 'hello.txt',
  kind: 'file',
  content: 'sandboxed write test\n',
});
// TypeError: Cannot read properties of undefined (reading 'permissions')
//     at normalizeEntry (.../sandbox/manifest.mjs:600:20)

型定義(node_modules/@openai/agents-core/dist/sandbox/entries/types.d.ts)を確認すると、materializeEntry() の引数は path と entry の2つで、ファイルの中身は entry オブジェクトにネストする必要がありました。

export type EntryBase = {
    description?: string;
    ephemeral?: boolean;
    group?: SandboxEntryGroup;
    permissions?: PermissionsInit | PermissionsValue;
};
export type File = EntryBase & {
    type: 'file';
    content: string | Uint8Array;
};

kind ではなく type が正しいプロパティ名で、しかも entry: {...} の形でラップする必要があります(kind のまま entry でラップしても Cannot read properties of undefined (reading 'endsWith') で別のエラーになりました)。

// これが正解
await session.materializeEntry({
  path: 'hello.txt',
  entry: { type: 'file', content: 'sandboxed write test\n' },
});

const r = await session.exec({ cmd: 'cat hello.txt' });
console.log(r.output); // sandboxed write test

実行すると materializeEntry() は正常終了し、書き込んだ内容が読み出せました。もう一つの経路として、シェルのリダイレクトを cmd に直接渡す方法もあります。

const w = await session.exec({ cmd: "echo 'sandboxed write test 2' > hello2.txt" });
console.log('write exitCode:', w.exitCode); // 0

const r2 = await session.exec({ cmd: 'ls -la' });
console.log(r2.output);
total 16
drwx------  2 root root 4096 Aug 29 07:19 .
drwxrwxrwt 12 root root 4096 Aug 29 07:19 ..
-rw-r--r--  1 root root   21 Aug 29 07:19 hello.txt
-rw-r--r--  1 root root   23 Aug 29 07:19 hello2.txt

書き込んだファイルが root 権限の隔離ディレクトリに置かれ、他プロセスから読めない drwx------ になっている点も、サンドボックスとして機能していることの裏付けです。materializeEntry() は Manifest ベースでファイルの権限・グループなど詳細な属性を制御したいときに、exec() 経由のシェルリダイレクトはとにかく素早く動かしたいときに向いています。

動作確認までの流れ

著者の一次所見

実際に手を動かして分かったのは、Sandbox Agents はエージェントループ(モデル呼び出し)とは独立して単体で動く ということでした。今回の検証では OpenAI API キーを一切使っていません。セッションの作成・コマンド実行・ファイル操作はすべてローカルの Node.js プロセスとして完結しており、「エージェントに実行環境を持たせる」部分と「モデルに何をさせるか」を決める部分が、実装上もきれいに分離されています。

裏を返すと、Sandbox 単体のユニットテストに API キーやモック LLM は不要で、CI 上でも session.exec() の入出力だけを検証すれば済みます。エージェント本体の振る舞いとサンドボックスの安全性を別々にテストできるのは、実務で採用するときに地味に効いてくるポイントだと感じました。

もう一つの気づきは、型定義ファイル(.d.ts)が最も信頼できるドキュメントだったことです。今回つまずいた cmd プロパティも materializeEntry() の形式も、公式ドキュメントの文章だけでは分からず、node_modules 配下の型定義とソースを直接読むことで解決できました。npm パッケージの SDK は、公式ガイドと実装の間にこの程度のズレが生じうる前提で検証するのが安全です。

まとめ

  • UnixLocalSandboxClient は @openai/agents/sandbox/local からインポートする(公式サンプルと同じ経路)
  • コマンド実行は session.exec({ cmd: '...' })(command ではない)
  • ファイル書き込みは materializeEntry({ path, entry: { type: 'file', content } }) が正解。急ぐなら exec() 経由のシェルリダイレクトでも同じ結果になる
  • Sandbox 単体は OpenAI API キーなしで動作確認できる

検証コードは Node.js v22.22.2、@openai/agents v0.17.0 で動作を確認しました。SDK は活発に更新されているため、バージョンが変わればインポートパスやプロパティ名が変わる可能性があります。

関連記事

参考リンク

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?