サンドボックスの現在のコンテナで、監視対象プロセスを起動し、状態を確認します。
考え方は プロセスの実行 を参照してください。対話型の PTY 入力とブラウザターミナルは ターミナル と Terminals API を参照してください。
プロセスハンドルに 標準入力はありません。対話なしの作業では cwd、env、argv(または明示的なシェルスクリプト)を使います。対話型の PTY が必要なときは ターミナル を使います。
argv(実行ファイル、続いて引数)からプロセスを起動します。起動が成功した時点で解決し、プロセス終了時ではありません。SDK はシェルを実行せず、argv をシェルエスケープしません。各エントリが 1 つのプロセス引数です。
exec(command: SandboxCommand, options?: ExecOptions): Promise<SandboxProcess>type SandboxCommand = readonly [executable: string, ...args: string[]];command[0]は空でない実行ファイルのパスまたは名前である必要があります。- 以降の引数は空文字列でも構いません。
- エントリはそのまま渡されます(argv のシェルエスケープなし)。
- シェル構文を使う場合は、明示的なシェルが必要です。例:
['/bin/bash', '-lc', script]。
| フィールド | 型 | 説明 |
|---|---|---|
cwd |
string |
この起動の作業ディレクトリです。未設定時のデフォルトは /workspace です。 |
env |
Record<string, string> |
この起動用の環境変数オーバーレイです。以降の起動は変更しません。サンドボックスレベルの env は引き続き適用されます。 |
timeout |
number |
リモートプロセスの生存時間(ミリ秒)です。スーパーバイザーがプロセスを停止することがあり、完了時に timedOut: true が報告されることがあります。 |
Promise<SandboxProcess>
const process = await sandbox.exec(["node", "--version"]);
const output = await process.output({ encoding: "utf8" });
console.log(process.id, process.pid, output.stdout, output.exitCode);const process = await sandbox.exec(["node", "--version"]);
const output = await process.output({ encoding: "utf8" });
console.log(process.id, process.pid, output.stdout, output.exitCode);このサンドボックスの 現在のコンテナ で動作中のプロセスのハンドルを返します。なければ null です。
コンテナが起動していなくても、コンテナは起動しません。コンテナが起動していない場合、現在のコンテナでプロセス ID が不明な場合、またはそのプロセスが同じサンドボックス ID の以前のコンテナに属していた場合は null を返します。
getProcess(id: string): Promise<SandboxProcess | null>プロセス ID は、コンテナの停止や差し替えをまたいで永続しません。プロセスの生存期間 を参照してください。
このサンドボックスの現在のコンテナ内のプロセスを一覧します。コンテナが起動していなくても、コンテナは起動しません。コンテナが起動していない場合は空のリストを返します。
listProcesses(): Promise<ProcessStatus[]>各エントリは ProcessStatus 値です(status() と同じ形)。
| メンバー | 説明 |
|---|---|
id |
現在のコンテナ内のプロセス ID です。 |
pid |
起動時のコンテナ pid です。 |
exitCode |
監視対象のプロセスグループが完了したときに解決する Promise<number> です。 |
status() |
現在の判別共用体ステータスです。 |
logs(options?) |
カーソルベースのログストリームです。 |
output(options?) |
バッファした stdout と stderr、および終了メタデータです。 |
waitForExit(options?) |
監視対象のプロセスグループが完了するまで待ちます。 |
waitForLog(pattern, options?) |
stdout または stderr が一致するまで待ちます。 |
waitForPort(port, options?) |
ポートの準備完了、または準備失敗まで待ちます。 |
kill(signal?) |
数値シグナルを送ります。デフォルトは 15(SIGTERM)です。 |
このハンドルにプロセス stdin API はありません。
status(): Promise<ProcessStatus>ProcessStatus を参照してください。ルート pid が終了しても子孫が動き続ける場合でも、監視対象の プロセスグループ が完了するまでプロセスは running のままです。
プロセスが完了する(またはローカルの待機が終わる)まで stdout と stderr をバッファし、終了メタデータを返します。
output(options?: ProcessOutputOptions): Promise<ProcessOutput<Uint8Array>>
output(
options: ProcessOutputOptions & { encoding: "utf8" },
): Promise<ProcessOutput<string>>interface ProcessOutput<T = Uint8Array> {
stdout: T;
stderr: T;
exitCode: number;
signal?: number;
timedOut: boolean;
truncated: boolean;
}デフォルトの本文エンコーディングはバイナリ(Uint8Array)です。encoding: "utf8" を渡した場合を除きます。出力がバッファしたい量を超える可能性がある場合は logs() を使ってください。
| フィールド | 型 | 説明 |
|---|---|---|
encoding |
"utf8" |
stdout/stderr を文字列としてデコードします。 |
maxBytes |
number |
結果のストリーム側ごとにバッファするバイト数の上限です。truncated: true になることがあります。省略時にデフォルトの上限はありません。 |
timeout |
number |
ローカル待機の期限(ミリ秒)のみです。プロセスは終了しません。 |
signal |
AbortSignal |
この待機だけをキャンセルします。プロセスは終了しません。 |
maxBytes を設定する場合は、負でない有限の数値である必要があります。
const process = await sandbox.exec(["/bin/bash", "-lc", "npm test"], {
cwd: "/workspace/app",
});
const result = await process.output({ encoding: "utf8", timeout: 120_000 });
console.log(result.exitCode, result.stdout, result.timedOut, result.truncated);const process = await sandbox.exec(["/bin/bash", "-lc", "npm test"], {
cwd: "/workspace/app",
});
const result = await process.output({ encoding: "utf8", timeout: 120_000 });
console.log(result.exitCode, result.stdout, result.timedOut, result.truncated);不透明なカーソル付きで、再生可能なログイベントをストリームします。
logs(options?: ProcessLogsOptions): Promise<ReadableStream<ProcessLogEvent>>| フィールド | 型 | 説明 |
|---|---|---|
since |
string |
不透明なカーソルです。前回のイベントのあとから再開します。 |
replay |
boolean |
再開時にバッファ済みの履歴を含めます。 |
follow |
boolean |
ライブ出力のためストリームを開いたままにします。 |
signal |
AbortSignal |
この購読だけをキャンセルします。プロセスは動き続けます。 |
type ProcessLogEvent =
| {
type: "stdout" | "stderr";
cursor: string;
timestamp: string;
data: Uint8Array;
}
| {
type: "terminal";
state: "exited";
cursor: string;
timestamp: string;
exit: ProcessExit;
}
| {
type: "terminal";
state: "error";
cursor: string;
timestamp: string;
error: ProcessFailure;
}
| {
type: "truncated";
cursor?: string;
timestamp: string;
};あとから Worker リクエストが、同じ コンテナの 同じ プロセスに対して logs({ since: cursor, replay: true, follow: true }) で再開する場合に備え、配信済みイベントから最新の cursor を保持してください。
const process = await sandbox.exec(["/bin/bash", "-lc", "npm run dev"], {
cwd: "/workspace/app",
});
const stream = await process.logs({ follow: true, replay: true });
const reader = stream.getReader();
const decoder = new TextDecoder();
for (;;) {
const { done, value } = await reader.read();
if (done) break;
if (value.type === "stdout" || value.type === "stderr") {
// Keep value.cursor if you will resume later
console.log(value.type, decoder.decode(value.data, { stream: true }));
continue;
}
if (value.type === "terminal") {
console.log("done", value.state);
break;
}
}const process = await sandbox.exec(["/bin/bash", "-lc", "npm run dev"], {
cwd: "/workspace/app",
});
const stream = await process.logs({ follow: true, replay: true });
const reader = stream.getReader();
const decoder = new TextDecoder();
for (;;) {
const { done, value } = await reader.read();
if (done) break;
if (value.type === "stdout" || value.type === "stderr") {
// Keep value.cursor if you will resume later
console.log(value.type, decoder.decode(value.data, { stream: true }));
continue;
}
if (value.type === "terminal") {
console.log("done", value.state);
break;
}
}監視対象のプロセスグループが完了するまで待ちます。
waitForExit(options?: {
timeout?: number;
signal?: AbortSignal;
}): Promise<ProcessExit>| フィールド | 型 | 説明 |
|---|---|---|
timeout |
number |
ローカル待機の期限のみです。プロセスは終了しません。 |
signal |
AbortSignal |
この待機だけをキャンセルします。プロセスは終了しません。 |
ProcessExit を返します。ローカルタイムアウトは ProcessWaitTimeoutError として表面化します。ローカル abort は ProcessAbortedError として表面化します。
const build = await sandbox.exec(["/bin/bash", "-lc", "npm run build"], {
cwd: "/workspace/app",
});
const exit = await build.waitForExit({ timeout: 600_000 });
console.log(exit.code, exit.signal, exit.timedOut);const build = await sandbox.exec(["/bin/bash", "-lc", "npm run build"], {
cwd: "/workspace/app",
});
const exit = await build.waitForExit({ timeout: 600_000 });
console.log(exit.code, exit.signal, exit.timedOut);stdout または stderr(あるいは両方)がパターンに一致するまで待ちます。
waitForLog(
pattern: string | RegExp,
options?: WaitForLogOptions,
): Promise<WaitForLogResult>| フィールド | 型 | 説明 |
|---|---|---|
stream |
"stdout" | "stderr" | "both" |
照合するストリームです。デフォルト: "both"。 |
timeout |
number |
ローカル待機の期限のみです。プロセスは終了しません。 |
signal |
AbortSignal |
この待機だけをキャンセルします。プロセスは終了しません。 |
interface WaitForLogResult {
stream: "stdout" | "stderr";
text: string;
match: string;
cursor?: string;
}textは、そのストリームのデコード済み出力のうち一致したウィンドウです。matchは一致した部分文字列です。cursorは、利用可能な場合、一致時点のログカーソルです。
一致前にプロセスが終了した場合、SDK は ProcessExitedBeforeLogError をスローします。ローカル待機のタイムアウトは ProcessWaitTimeoutError をスローします。
const server = await sandbox.exec(["/bin/bash", "-lc", "npm run dev"], {
cwd: "/workspace/app",
});
const ready = await server.waitForLog(/listening on/i, {
stream: "both",
timeout: 60_000,
});
console.log(ready.stream, ready.match);const server = await sandbox.exec(["/bin/bash", "-lc", "npm run dev"], {
cwd: "/workspace/app",
});
const ready = await server.waitForLog(/listening on/i, {
stream: "both",
timeout: 60_000,
});
console.log(ready.stream, ready.match);ポートの準備が整うまで待ちます。プロセスが先に終了した場合、またはローカル待機が終わった場合は失敗します。
waitForPort(port: number, options?: WaitForPortOptions): Promise<void>| フィールド | 型 | 説明 |
|---|---|---|
mode |
"tcp" | "http" |
準備完了チェックです。デフォルト: "tcp"(TCP 接続を受け付けます)。 |
path |
string |
mode が "http" のときにリクエストする HTTP パスです。デフォルト: "/"。 |
status |
number | { min: number; max: number } |
mode が "http" のときの期待 HTTP ステータス、または両端を含む範囲です。デフォルト: { min: 200, max: 399 }。 |
interval |
number |
チェック間隔(ミリ秒)です。デフォルト: 500。 |
timeout |
number |
ローカル待機の期限のみです。プロセスは終了しません。省略時にデフォルトのタイムアウトはありません。 |
signal |
AbortSignal |
この待機だけをキャンセルします。プロセスは終了しません。 |
TCP モード(デフォルト)は、ポートが接続を受け付けたときに成功します。
const db = await sandbox.exec(["redis-server"]);
await db.waitForPort(6379, {
mode: "tcp",
timeout: 10_000,
});const db = await sandbox.exec(["redis-server"]);
await db.waitForPort(6379, {
mode: "tcp",
timeout: 10_000,
});HTTP モードは HTTP リクエストを発行し、レスポンスステータスを確認します。
const server = await sandbox.exec(["/bin/bash", "-lc", "npm run dev"], {
cwd: "/workspace/app",
});
await server.waitForPort(3000, {
mode: "http",
path: "/health",
status: { min: 200, max: 299 },
timeout: 60_000,
});const server = await sandbox.exec(["/bin/bash", "-lc", "npm run dev"], {
cwd: "/workspace/app",
});
await server.waitForPort(3000, {
mode: "http",
path: "/health",
status: { min: 200, max: 299 },
timeout: 60_000,
});よくある失敗は次のとおりです。
ProcessReadyTimeoutError— ローカルタイムアウトまでにポートの準備が整わなかったProcessExitedBeforeReadyError— ポートの準備が整う前にプロセスが終了したProcessAbortedError— ローカルのAbortSignalが待機をキャンセルした(プロセスは動き続けていることがあります)
プロセスに数値シグナルを送ります。
kill(signal?: number): Promise<void>デフォルトの signal は 15(SIGTERM)です。数値シグナルだけを渡します(例: SIGKILL なら 9)。文字列のシグナル名は受け付けません。
プロセスの停止と、ローカル待機またはログ購読のキャンセルは別です。
readonly exitCode: Promise<number>監視対象のプロセスグループが完了したときの終了コードに解決します(waitForExit() と同じ完了境界)。signal や timedOut も必要な場合は waitForExit() を使ってください。
type ProcessStatus =
| {
state: "running";
id: string;
pid: number;
command: SandboxCommand;
cwd?: string;
startedAt: string;
}
| {
state: "exited";
id: string;
pid: number;
command: SandboxCommand;
cwd?: string;
startedAt: string;
endedAt: string;
exit: ProcessExit;
}
| {
state: "error";
id: string;
pid: number;
command: SandboxCommand;
cwd?: string;
startedAt: string;
endedAt: string;
error: ProcessFailure;
};listProcesses() はこの形の ProcessStatus[] を返します。
監視対象グループが完了したときに、ルート サブプロセスで観測された結果です。
interface ProcessExit {
code: number;
signal?: number;
timedOut: boolean;
}子孫にだけ送られたシグナルは、この結果を書き換えません。プロセスの実行 を参照してください。
interface ProcessFailure {
code: string;
message: string;
}getProcess と listProcesses は、対象がない場合にスローしません。コンテナが起動していない、現在のコンテナで ID が不明、またはプロセスが以前のコンテナに属していた場合は null または [] を返します。次のエラークラスは、プロセスハンドル上の操作(および起動)に適用され、これらの検索には適用されません。
| 状況 | クラス / 結果 |
|---|---|
コンテナが起動していないときの getProcess / listProcesses |
null / [](エラーではありません。コンテナは起動しません) |
不明な ID、または以前のコンテナのプロセスに対する getProcess |
null |
| コンテナ差し替え後のハンドル操作 | StaleProcessHandleError |
| 現在のコンテナでプロセスがなくなったハンドル操作 | ProcessNotFoundError |
ローカル待機のタイムアウト(output / waitForExit / waitForLog) |
ProcessWaitTimeoutError |
待機またはストリームに対するローカル AbortSignal |
ProcessAbortedError |
| ローカルタイムアウトまでにポートの準備が整わない | ProcessReadyTimeoutError |
| ポート準備完了前にプロセスが終了 | ProcessExitedBeforeReadyError |
| ログ一致前にプロセスが終了 | ProcessExitedBeforeLogError |
| 起動時の作業ディレクトリが無効 | InvalidProcessCwdError |
| 起動時の環境が無効 | InvalidProcessEnvironmentError |
| ログカーソルが無効 | InvalidProcessCursorError |
| プロセスの起動に失敗 | ProcessSpawnFailedError |
| コンテナの準備ができておらず、作業が始まらなかった | ContainerUnavailableError |
| 作業が始まった可能性があるあとに中断された | OperationInterruptedError |
復旧の指針: エラーと復旧。完全なカタログ: Errors API。生存期間: プロセスの生存期間。