メインコンテンツへスキップ
Droid ExecはFactory自動化ワークフロー向けに設計されたヘッドレス実行モードです。インタラクティブなCLIとは異なり、droid exec はタスクを完了して終了するワンショットコマンドとして実行されるため、CI/CDパイプライン、シェルスクリプト、バッチ処理に最適です。

概要と目標

Droid Execは次のことを目的として設計されたワンショットタスクランナーです:
  • 読みやすいログと、要求された場合は構造化された成果物を生成
  • 変更/コマンド実行にオプトインを強制(デフォルトでセキュア)
  • 明確なエラーメッセージで権限違反時に高速失敗
  • バッチおよび並列処理のシンプルな組み合わせをサポート

Non-Interactive

Single run execution that writes to stdout/stderr for CI/CD integration

Secure by Default

Read-only by default with explicit opt-in for mutations via autonomy levels

Composable

Designed for shell scripting, parallel execution, and pipeline integration

Clean Output

Structured output formats and artifacts for automated processing

実行モデル

  • stdout/stderrに書き込む非インタラクティブなシングルラン。
  • デフォルトはspecモード:エージェントは読み取り専用操作の実行のみが許可されます。
  • 編集とコマンドを有効にするには --auto を追加します;リスクティアが実行可能なものを制御します。
CLIヘルプ(抜粋):
Usage: droid exec [options] [prompt]

Execute a single command (non-interactive mode)

Arguments:
  prompt                          The prompt to execute

Options:
  -o, --output-format <format>    Output format (default: "text")
  --input-format <format>         Input format: stream-json for multi-turn sessions
  -f, --file <path>               Read prompt from file
  --auto <level>                  Autonomy level: low|medium|high
  --skip-permissions-unsafe       Skip ALL permission checks - allows all permissions (unsafe)
  -s, --session-id <id>           Existing session to continue (requires a prompt)
  -m, --model <id>                Model ID to use
  -r, --reasoning-effort <level>  Reasoning effort (defaults per model)
  --spec-model <id>               Model ID to use for spec mode
  --use-spec                      Start in spec mode
  --enabled-tools <ids>           Enable specific tools (comma or space separated list)
  --disabled-tools <ids>          Disable specific tools (comma or space separated list)
  --list-tools                    List available tools for the selected model and exit
  --cwd <path>                    Working directory path
  -h, --help                      display help for command
サポートされているモデル(例):
  • claude-opus-4-6
  • claude-opus-4-6-fast
  • claude-opus-4-5-20251101
  • claude-sonnet-4-5-20250929
  • claude-haiku-4-5-20251001
  • gpt-5.1-codex
  • gpt-5.1-codex-max
  • gpt-5.1
  • gpt-5.2
  • gpt-5.2-codex
  • gpt-5.3-codex
  • gemini-3-pro-preview
  • gemini-3.1-pro-preview
  • gemini-3-flash-preview
  • glm-4.7
  • glm-5
  • kimi-k2.5
  • minimax-m2.5
See the model table for the full list of available models and their costs.

インストール

1

Install Droid CLI

curl -fsSL https://app.factory.ai/cli | sh
2

Get Factory API Key

Generate your API key from the Factory Settings Page
3

Set Environment Variable

Export your API key as an environment variable:
export FACTORY_API_KEY=fk-...

クイックスタート

  • 直接プロンプト:
    • droid exec "analyze code quality"
    • droid exec "fix the bug in src/main.js" --auto low
  • ファイルから:
    • droid exec -f prompt.md
  • パイプ:
    • echo "summarize repo structure" | droid exec
  • セッション継続:
    • droid exec --session-id <session-id> "continue with next steps"

自律性レベル

Droid execは階層化された自律性システムを使用して、エージェントが実行できる操作を制御します。デフォルトでは読み取り専用モードで動作し、変更を有効にするには明示的なフラグが必要です。

DEFAULT(フラグなし) - 読み取り専用モード

実行せずに計画された変更を確認するための最も安全なモード:
  • ✅ ファイルやログの読み取り:cat、less、head、tail、systemctl status
  • ✅ 表示コマンド:echo、pwd
  • ✅ 情報収集:whoami、date、uname、ps、top
  • ✅ Git読み取り操作:git status、git log、git diff
  • ✅ ディレクトリ一覧:ls、find(-deleteや-execなし)
  • ❌ ファイルやシステムの変更なし
  • 使用例: どのような変更が行われるかを安全に確認
# Analyze and plan refactoring without making changes
droid exec "Analyze the authentication system and create a detailed plan for migrating from session-based auth to OAuth2. List all files that would need changes and describe the modifications required."

# Review code quality and generate report
droid exec "Review the codebase for security vulnerabilities, performance issues, and code smells. Generate a prioritized list of improvements needed."

# Understand project structure
droid exec "Analyze the project architecture and create a dependency graph showing how modules interact with each other."

--auto low - 低リスク操作

システム変更をブロックしながら基本的なファイル操作を有効化:
  • ✅ プロジェクトディレクトリ内でのファイル作成/編集
  • ❌ システム変更やパッケージインストールなし
  • 使用例: ドキュメント更新、コード整形、コメント追加
# Safe file operations
droid exec --auto low "add JSDoc comments to all functions"
droid exec --auto low "fix typos in README.md"

--auto medium - 開発操作

重大な副作用を伴う可能性がある操作ですが、これらの副作用は通常無害で回復が簡単です。 低リスク操作に一般的な開発タスクを追加:
  • 信頼できるソースからのパッケージインストール:npm install、pip install(sudoなし)
  • 信頼できるエンドポイントへのネットワークリクエスト:既知のAPIへのcurl、wget
  • ローカルリポジトリを変更するGit操作:git commit、git checkout、git pull(ただしgit pushは除く)
  • make、npm run build、mvn compileなどのツールでコードをビルド
  • ❌ git push、sudoコマンド、本番環境の変更なし
  • 使用例: ローカル開発、テスト、依存関係管理
# Development tasks
droid exec --auto medium "install deps, run tests, fix issues"
droid exec --auto medium "update packages and resolve conflicts"

--auto high - 本番操作

信頼できないソース間でのデータ転送や未知のコードの実行などのセキュリティ上の影響がある可能性があるコマンド、または不可逆的なデータ損失や本番システム/デプロイメントの変更などの重大な副作用を伴うコマンド。
  • 任意/信頼できないコードの実行:curl | bash、eval、ダウンロードしたスクリプトの実行
  • ポートの公開や外部アクセスを許可する可能性があるファイアウォールルールの変更
  • リモートリポジトリを変更するGit push操作:git push、git push —force
  • 本番デプロイメント、データベースマイグレーション、その他の機密操作への不可逆的なアクション
  • パスワードやキーなどの機密情報にアクセスまたは変更するコマンド
  • ❌ それでもブロック:sudo rm -rf /、システム全体の変更
  • 使用例: CI/CDパイプライン、自動デプロイメント
# Full workflow automation
droid exec --auto high "fix bug, test, commit, and push to main"
droid exec --auto high "deploy to staging after running tests"

--skip-permissions-unsafe - すべてのチェックをバイパス

DANGEROUS: This mode allows ALL operations without confirmation. Only use in completely isolated environments like Docker containers or throwaway VMs.
  • ⚠️ 確認なしですべての操作を許可
  • ⚠️ 不可逆的な操作を実行可能
  • —autoフラグと組み合わせることはできません
  • 使用例: 分離された環境
# In a disposable Docker container for CI testing
docker run --rm -v $(pwd):/workspace alpine:latest sh -c "
  apk add curl bash &&
  curl -fsSL https://app.factory.ai/cli | sh &&
  droid exec --skip-permissions-unsafe 'Install all system dependencies, modify system configs, run integration tests that require root access, and clean up test databases'
"

# In ephemeral GitHub Actions runner for rapid iteration
# where the runner is destroyed after each job
droid exec --skip-permissions-unsafe "Modify /etc/hosts for test domains, install custom kernel modules, run privileged container tests, and reset network interfaces"

# In a temporary VM for security testing
droid exec --skip-permissions-unsafe "Run penetration testing tools, modify firewall rules, test privilege escalation scenarios, and generate security audit reports"

高速失敗動作

要求されたアクションが現在の自律性レベルを超える場合、droid execは:
  1. 明確なエラーメッセージで即座に停止
  2. 非ゼロの終了コードを返す
  3. 部分的な変更を実行しない
これにより、自動化スクリプトやCI/CDパイプラインで予測可能な動作が保証されます。

出力形式と成果物

Droid execは異なる使用例に対応する3つの出力形式をサポートしています:

text(デフォルト)

直接消費またはログ用の人間が読める出力:
$ droid exec --auto low "create a python file that prints 'hello world'"
Perfect! I've created a Python file named `hello_world.py` in your home directory that prints 'hello world' when executed.

json

スクリプトと自動化で解析するための構造化JSON出力:
$ droid exec "summarize this repository" --output-format json
{
  "type": "result",
  "subtype": "success",
  "is_error": false,
  "duration_ms": 5657,
  "num_turns": 1,
  "result": "This is a Factory documentation repository containing guides for CLI tools, web platform features, and onboarding procedures...",
  "session_id": "8af22e0a-d222-42c6-8c7e-7a059e391b0b"
}
次の場合にJSON形式を使用してください:
  • スクリプトで結果を解析する
  • 成功/失敗をプログラム的にチェックする
  • 継続のためのセッションIDを抽出する
  • パイプラインで結果を処理する

stream-json / debug

エージェントの実行をリアルタイムで表示するストリーミングJSONLメッセージ。各行は独立して解析できる個別のJSONイベントです:
$ droid exec "run ls command" --output-format stream-json
{"type":"system","subtype":"init","cwd":"/path/to/dir","session_id":"abc-123","tools":["Read","Execute",...],"model":"claude-sonnet-4-5-20250929"}
{"type":"message","role":"user","id":"msg-1","text":"run ls command","timestamp":1762517060816,"session_id":"abc-123"}
{"type":"message","role":"assistant","id":"msg-2","text":"I'll run the ls command to list the contents...","timestamp":1762517062000,"session_id":"abc-123"}
{"type":"tool_call","id":"call-1","messageId":"msg-2","toolId":"Execute","toolName":"Execute","parameters":{"command":"ls -la"},"timestamp":1762517062500,"session_id":"abc-123"}
{"type":"tool_result","id":"call-1","messageId":"msg-3","toolId":"Execute","isError":false,"value":"total 16\ndrwxr-xr-x@ 8 user staff...","timestamp":1762517063000,"session_id":"abc-123"}
{"type":"completion","finalText":"The ls command has been executed successfully. Here are the directory contents...","numTurns":1,"durationMs":3000,"session_id":"abc-123","timestamp":1762517064000}
The debug format is a deprecated alias for stream-json and works identically.

stream-jsonrpc(マルチターン)

SDK統合とマルチターン会話には、JSON-RPCストリーミングプロトコルを使用します:
droid exec --input-format stream-jsonrpc --output-format stream-jsonrpc --auto low
このモードはstdinからJSONLメッセージを読み取り、JSON-RPC形式のレスポンスを出力し、以下を可能にします:
  • 単一のexec呼び出し内でのマルチターン会話
  • 実行中の動的モード切り替え
  • インタラクティブなTUIのような完全なツールアクセス
JSONL形式でstdin経由でメッセージを送信し、構造化されたJSON-RPCレスポンスを受信します。 主要なイベントタイプ:
  • system - 利用可能なツールとモデルでのセッション初期化
  • message - ユーザーまたはアシスタントのテキストメッセージ
  • tool_call - エージェントがツールを呼び出し(Read、Executeなど)
  • tool_result - ツール実行からの結果
  • completion - finalText での完全なレスポンスを含む最終イベント
completionイベント は常に最後に発行され、以下を含みます:
  • finalText - エージェントの最終レスポンステキスト
  • numTurns - 実行されたアシスタントターン数
  • durationMs - ミリ秒での総実行時間
  • session_id - 継続のためのセッション識別子
Stream-JSON形式は以下に有用です:
  • エージェントの動作をリアルタイムで監視
  • ユーザーへの進捗更新のストリーミング
  • 実行問題のトラブルシューティング
  • ツール使用パターンの理解
  • completion.finalText からの最終結果の抽出
シェルスクリプトでの解析例:
# Extract just the final result
droid exec "analyze code" --output-format stream-json | \
  jq -r 'select(.type == "completion") | .finalText'

# Monitor tool calls in real-time
droid exec "complex task" --output-format stream-json | \
  jq -r 'select(.type == "tool_call") | "\(.toolName): \(.parameters.command // .parameters.file_path // "")"'
自動化パイプラインでは、特定の成果物を書き込むようエージェントに指示することもできます:
droid exec --auto low "Analyze dependencies and write to deps.json"
droid exec --auto low "Generate metrics report in CSV format to metrics.csv"

作業ディレクトリ

  • 実行をスコープするには --cwd を使用:
droid exec --cwd /home/runner/work/repo "Map internal packages and dump graphviz DOT to deps.dot"

モデルと推論努力

-m でモデルを選択し、-r で推論を調整します。利用可能なモデルについては model table を参照してください。
droid exec -m claude-sonnet-4-5-20250929 -r medium -f plan.md
--use-spec を使用して、エージェントが実行前に計画する仕様モードで開始します:
droid exec --use-spec --auto low "refactor the auth module"
spec段階で別のモデルを使用することもできます:
droid exec --use-spec --spec-model claude-haiku-4-5-20251001 --auto medium "implement feature X"

ツール制御

モデルで利用可能なツールを一覧表示:
droid exec --list-tools
droid exec --model gpt-5-codex --list-tools --output-format json
特定のツールを有効または無効にする:
# Enable additional tools
droid exec --enabled-tools ApplyPatch "refactor files"

# Disable specific tools
droid exec --auto medium --disabled-tools execute-cli "run edits only"

カスタムモデル

~/.factory/settings.json ファイルに追加することで、droid execで使用するカスタムモデルを設定できます:
{
  "customModels": [
    {
      "model": "gpt-5.1-codex-custom",
      "displayName": "My Custom Model",
      "baseUrl": "https://api.openai.com/v1",
      "apiKey": "your-api-key-here",
      "provider": "openai"
    }
  ]
}
カスタムモデルを使用するには、custom: プレフィックスの後に表示名(スペースをダッシュに置換)とインデックスを使用します:
droid exec --model "custom:My-Custom-Model-0" "analyze this codebase"
複数のカスタムモデルが設定されている場合:
{
  "customModels": [
    {
      "model": "kimi-k2",
      "displayName": "Kimi K2 [Groq]",
      "baseUrl": "https://api.groq.com/openai/v1",
      "apiKey": "your-groq-key",
      "provider": "generic-chat-completion-api",
      "maxOutputTokens": 16384
    },
    {
      "model": "openai/gpt-oss-20b",
      "displayName": "GPT-OSS-20B [OpenRouter]",
      "baseUrl": "https://openrouter.ai/api/v1",
      "apiKey": "YOUR_OPENROUTER_KEY",
      "provider": "generic-chat-completion-api",
      "maxOutputTokens": 32000
    }
  ]
}
次のように参照します:
  • --model "custom:Kimi-K2-[Groq]-0"
  • --model "custom:GPT-OSS-20B-[OpenRouter]-1"
インデックスは customModels 配列内の位置に対応します(0ベース)。
Reasoning effort (-r / --reasoning-effort) is not yet supported for custom models, but coming soon.

バッチと並列パターン

シェルループ(制限された並行性):
# Process files in parallel (GNU xargs -P)
find src -name "*.ts" -print0 | xargs -0 -P 4 -I {} \
  droid exec --auto low "Refactor file: {} to use modern TS patterns"
バックグラウンドジョブ並列化:
# Process multiple directories in parallel with job control
for path in packages/ui packages/models apps/factory-app; do
  (
    cd "$path" &&
    droid exec --auto low "Run targeted analysis and write report.md"
  ) &
done
wait  # Wait for all background jobs to complete
チャンク入力:
# Split large file lists into manageable chunks
git diff --name-only origin/main...HEAD | split -l 50 - /tmp/files_
for f in /tmp/files_*; do
  list=$(tr '\n' ' ' < "$f")
  droid exec --auto low "Review changed files: $list and write to review.json"
done
rm /tmp/files_*  # Clean up temporary files
ワークフロー自動化(CI/CD):
# Dead code detection and cleanup suggestions
name: Code Cleanup Analysis
on:
  schedule:
    - cron: '0 1 * * 0' # Weekly on Sundays
  workflow_dispatch:
jobs:
  cleanup-analysis:
    strategy:
      matrix:
        module: ['src/components', 'src/services', 'src/utils', 'src/hooks']
    steps:
      - uses: actions/checkout@v4
      - run: droid exec --cwd "${{ matrix.module }}" --auto low "Identify unused exports, dead code, and deprecated patterns. Generate cleanup recommendations in cleanup-report.md"

ユニークな使用例

ライセンスヘッダー強制:
git ls-files "*.ts" | xargs -I {} \
  droid exec --auto low "Ensure {} begins with the Apache-2.0 header; add it if missing"
APIコントラクトドリフトチェック(読み取り専用):
droid exec "Compare openapi.yaml operations to our TypeScript client methods and write drift.md with any mismatches"
セキュリティスイープ:
droid exec --auto low "Run a quick audit for sync child_process usage and propose fixes; write findings to sec-audit.csv"

終了動作

  • 0:成功
  • 非ゼロ:失敗(権限違反、ツールエラー、目標未達成)。CIでは非ゼロを失敗として扱います。

ベストプラクティス

  • --auto low を優先;変更を最小限に抑え、スクリプトステップでcommit/pushしてください。
  • 完全にサンドボックス化されていない限り --skip-permissions-unsafe は避けてください。
  • パイプラインが検証できる成果物をエージェントに出力させてください。
  • モノレポでスコープを制約するには --cwd を使用してください。