@lousy-agents/agent-shell

中文文档
5.22.24发布于 2026/11/02BSD-2-Clause-PatentES Module构建来源已验证

A flight recorder for npm script execution

原始使用文档
文档目录40 节
  1. Quick Start
  2. How It Works
  3. Setup with agent-shell init
  4. Interactive Mode (TTY)
  5. Non-Interactive Mode (CI / Flags)
  6. What It Generates
  7. Flight Recording with agent-shell record
  8. Copilot Hook Configuration
  9. Telemetry Schema (v1)
  10. script_end Event
  11. tool_use Event
  12. policy_decision Event
  13. shim_error Event
  14. Field Reference
  15. Actor Detection
  16. Querying Events
  17. Duration Formats
  18. Policy-Based Command Blocking
  19. How It Works
  20. Policy File
  21. Copilot Hook Configuration
  22. Input/Output Format
  23. Policy Initialization ( policy --init )
  24. What It Generates
  25. How It Discovers Commands
  26. AI-Enhanced Analysis
  27. Authentication Setup
  28. Prerequisites
  29. Example Output
  30. Environment Variables
  31. Custom Tags
  32. Session Correlation
  33. Scope
  34. Troubleshooting
  35. npm fails with "script-shell not found"
  36. Bypass all instrumentation
  37. Remove instrumentation entirely
  38. Verify the shim is active
  39. Clean up recorded events
  40. .gitignore

@lousy-agents/agent-shell

agent-shell demo

A flight recorder for AI agent tool usage and npm script execution.

agent-shell records structured JSONL telemetry for both npm script execution (via script-shell shim) and AI agent tool usage (via Copilot lifecycle hooks). It provides an audit trail that doesn't depend on agent self-reports.

Quick Start

# Install globally
npm install -g @lousy-agents/agent-shell

# Initialize hooks and policy (interactive)
agent-shell init

# Add event storage to .gitignore
echo '.agent-shell/' >> .gitignore

# Verify it's working
agent-shell --version

agent-shell init detects your project, prompts for which features to enable (flight recording, policy blocking), and writes the Copilot hook configuration and policy files.

Note: agent-shell init sets up Copilot hooks and policy files, but npm script execution recording is configured separately. To record npm script runs and emit script_end events, set npm's script-shell to agent-shell (for example by adding script-shell=agent-shell to your project's .npmrc).

Why global? agent-shell is configured as npm's script-shell and as a Copilot hook command, so it must be available before npm ci or npm install runs. A local dev dependency creates a circular dependency. Installing globally keeps it on PATH independent of node_modules.

How It Works

When npm runs a script (e.g., npm test), it invokes the configured script-shell instead of /bin/sh. agent-shell wraps the real shell:

  1. Captures context (actor, environment, timestamps)
  2. Spawns /bin/sh -c <command> — your script runs normally
  3. Records a JSONL event with execution metadata
  4. Propagates the exit code unchanged

Scripts behave identically — same output, same exit codes, same signals. agent-shell adds observability without changing behavior.

Setup with agent-shell init

The init subcommand is the recommended way to configure agent-shell for your project. It detects existing configuration and guides you through enabling features.

Interactive Mode (TTY)

agent-shell init

When run in a terminal, init prompts for each feature:

  • Flight recording — Records all agent tool usage via postToolUse hook
  • Policy blocking — Evaluates commands against allow/deny rules via preToolUse hook

If hooks.json already exists, only missing features are prompted.

Non-Interactive Mode (CI / Flags)

# Enable specific features
agent-shell init --flight-recorder
agent-shell init --policy
agent-shell init --flight-recorder --policy

# Disable specific features
agent-shell init --no-flight-recorder
agent-shell init --no-policy

In a non-TTY environment with no explicit flags, all missing features are auto-enabled with a message to stderr.

What It Generates

FileDescription
.github/hooks/agent-shell/hooks.jsonCopilot hook configuration with selected features
.github/hooks/agent-shell/policy.jsonAllow/deny policy (only when policy is enabled)

Flight Recording with agent-shell record

The record subcommand is a postToolUse hook handler that records every tool invocation as a tool_use telemetry event. It captures tool usage that happens outside npm scripts — file edits, code searches, API calls, and more.

Copilot Hook Configuration

When both flight recording and policy are enabled, hooks.json looks like this:

{
  "version": 1,
  "hooks": {
    "preToolUse": [
      {
        "type": "command",
        "bash": "agent-shell policy-check",
        "timeoutSec": 30
      }
    ],
    "postToolUse": [
      {
        "type": "command",
        "bash": "agent-shell record",
        "timeoutSec": 30
      }
    ]
  }
}

The record handler reads the JSON payload from Copilot's postToolUse hook via stdin. For terminal tools (bash, zsh, ash, sh), it extracts the command string from toolArgs. For non-terminal tools, the command is recorded as an empty string.

Telemetry Schema (v1)

Each event produces one JSON line. There are four event types:

script_end Event

Recorded when an npm script completes:

{
  "v": 1,
  "session_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "event": "script_end",
  "script": "test",
  "command": "vitest run",
  "package": "my-app",
  "package_version": "1.2.0",
  "actor": "claude-code",
  "exit_code": 1,
  "signal": null,
  "duration_ms": 3420,
  "timestamp": "2026-03-08T14:32:01.000Z",
  "env": {
    "NODE_ENV": "test",
    "CI": "true"
  },
  "tags": {
    "pr": "1234"
  }
}

tool_use Event

Recorded by the postToolUse hook when an agent uses any tool:

{
  "v": 1,
  "session_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "event": "tool_use",
  "tool_name": "bash",
  "command": "npm test",
  "actor": "copilot",
  "timestamp": "2026-03-08T14:32:01.000Z",
  "env": {
    "CI": "true"
  },
  "tags": {}
}

For non-terminal tools (file edits, searches, etc.), command is an empty string and tool_name identifies the tool (e.g., file_edit, curl).

policy_decision Event

Recorded when the preToolUse policy-check hook evaluates a command:

{
  "v": 1,
  "session_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "event": "policy_decision",
  "decision": "deny",
  "matched_rule": "rm -rf *",
  "command": "rm -rf /",
  "actor": "copilot",
  "timestamp": "2026-03-08T14:32:01.000Z",
  "env": {
    "CI": "true"
  },
  "tags": {}
}

shim_error Event

Recorded when agent-shell encounters an internal error (e.g., failed to parse npm context):

{
  "v": 1,
  "session_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "event": "shim_error",
  "command": "",
  "actor": "copilot",
  "timestamp": "2026-03-08T14:32:01.000Z",
  "env": {},
  "tags": {}
}

Field Reference

FieldTypeDescription
vnumberSchema version (always 1)
session_idstringUUID identifying the session
eventstringscript_end, tool_use, shim_error, or policy_decision
scriptstring?npm lifecycle event name (e.g., test, build) — script_end only
tool_namestring?Tool identifier (e.g., bash, file_edit) — tool_use only
commandstringThe actual command executed
packagestring?Package name from package.json
package_versionstring?Package version
actorstringWho initiated it: human, ci, claude-code, copilot, or custom
exit_codenumberChild process exit code
signalstring | nullSignal name if killed (e.g., SIGINT), otherwise null
duration_msnumberWall-clock execution time in milliseconds
timestampstringISO 8601 completion timestamp
envobjectCaptured environment variables (allowlisted)
tagsobjectCustom tags from AGENTSHELL_TAG_* variables

Fields script, package, and package_version are only present when running within an npm context.

Actor Detection

agent-shell classifies who initiated each script execution:

PriorityConditionActor
1AGENTSHELL_ACTOR is setValue of the variable
2GITHUB_ACTIONS=trueci
3CLAUDE_CODE is setclaude-code
4COPILOT_AGENT is setcopilot
5COPILOT_CLI is setcopilot
6COPILOT_CLI_BINARY_VERSION is setcopilot
7No matchhuman

Querying Events

Use the log subcommand to query execution history. Both script_end and tool_use events are included in results:

# Show events from the most recent session
agent-shell log

# Show events from the last 2 hours
agent-shell log --last 2h

# Show only failures (script_end events with non-zero exit)
agent-shell log --failures

# Filter by actor
agent-shell log --actor claude-code

# Filter by script name (script_end events only)
agent-shell log --script test

# Combine filters
agent-shell log --actor claude-code --failures --last 2h

# Output as JSON (for scripting)
agent-shell log --json

# List all sessions
agent-shell log --list-sessions

Duration Formats

FormatMeaning
30mLast 30 minutes
2hLast 2 hours
1dLast 1 day

Policy-Based Command Blocking

agent-shell includes a policy-check subcommand that evaluates shell commands against allow/deny rules before execution. This enables repository maintainers to define which commands AI agents are permitted to run via a pre-tool-use hook.

How It Works

The policy-check command is designed to be used as a GitHub Copilot pre-tool-use hook. It reads a JSON request from stdin containing the tool name and arguments, evaluates the command against a policy file, and writes a permission decision to stdout.

Only terminal tools (bash, zsh, ash, sh) have their commands evaluated against policy rules when the policy file loads successfully; non-terminal tools are then allowed without policy evaluation. If the default policy file is missing, all tools are allowed, but if the policy file is present and malformed or invalid, all tools are denied.

Policy File

By default, the policy file is located at .github/hooks/agent-shell/policy.json relative to the repository root. Override the location with the AGENTSHELL_POLICY_PATH environment variable.

{
  "allow": ["npm test", "npm run lint*", "git status"],
  "deny": ["npm publish", "rm -rf *"]
}

Evaluation order:

  1. If the command matches any deny pattern → deny
  2. If an allow list exists and the command does not match any pattern → deny
  3. Otherwise → allow

Patterns support * wildcards for prefix, suffix, and infix matching (e.g., npm run * matches npm run test). When using the default policy path, a missing policy file results in all commands being allowed. When AGENTSHELL_POLICY_PATH is set and the referenced policy file is missing, malformed, or cannot be loaded, commands are denied (fail-closed).

Copilot Hook Configuration

Add the following to .github/hooks/agent-shell/hooks.json, or use agent-shell init to generate it automatically:

{
  "version": 1,
  "hooks": {
    "preToolUse": [
      {
        "type": "command",
        "timeoutSec": 30,
        "bash": "agent-shell policy-check"
      }
    ],
    "postToolUse": [
      {
        "type": "command",
        "timeoutSec": 30,
        "bash": "agent-shell record"
      }
    ]
  }
}

Input/Output Format

Input (JSON via stdin):

{
  "toolName": "bash",
  "toolArgs": "{\"command\": \"npm test\"}"
}

Output (JSON to stdout):

{"permissionDecision": "allow"}

Or when denied:

{
  "permissionDecision": "deny",
  "permissionDecisionReason": "Command 'npm publish' denied by policy rule: npm publish"
}

Policy decisions are recorded as telemetry events alongside regular script execution events.

Policy Initialization (policy --init)

Manually writing a policy.json allow list requires knowing which commands your project actually uses. policy --init eliminates that blank-page problem: it scans your project and generates a ready-to-commit policy and hook configuration.

agent-shell policy --init

What It Generates

FileDescription
.github/hooks/agent-shell/policy.jsonAllow/deny policy derived from discovered commands
.github/hooks/agent-shell/hooks.jsonCopilot preToolUse hook entry wiring agent-shell policy-check

If either file already exists, the command skips writing it and notifies you. Both files are safe to commit for team-wide enforcement.

How It Discovers Commands

The scanner inspects three sources:

  1. package.json scripts — Each npm run <script> entry becomes an exact allow rule
  2. GitHub Actions workflow files — run: commands in .github/workflows/*.yml are extracted and deduplicated
  3. mise.toml tasks — Each task becomes an exact mise run <task> allow rule (no wildcards, for security)

Language detection (Node.js, Python, Go, Rust, Ruby, Java) is also performed and reported in the scan summary. Language-specific build tool patterns may be added in a future version.

AI-Enhanced Analysis

When the @github/copilot-sdk package is available and authenticated, policy --init runs a second pass using the GitHub Copilot AI to refine the generated allow list. The AI session connects to @lousy-agents/mcp as a local MCP server for structured project discovery, and exposes two additional sandboxed tools for ad-hoc exploration:

ToolWhat it does
read_project_fileReads a file within the repository (max 100 KB, path-traversal safe)
validate_allow_ruleChecks whether a proposed allow rule is safe (no shell metacharacters)

The MCP server also provides discover_feedback_loops and discover_environment tools, giving the model structured access to SDLC commands and runtime/toolchain details without raw filesystem browsing.

Fallback behavior:

ConditionBehavior
@github/copilot-sdk not installedSilently falls back to static analysis; no error
SDK installed but not authenticatedSilently falls back to static analysis; no error
SDK session fails mid-analysisFalls back to static results; logs error to stderr when AGENT_SHELL_COPILOT_DEBUG is set

The final policy file is always generated. AI enhancement is best-effort and never blocks output.

Authentication Setup

The @github/copilot-sdk authenticates using the GitHub Copilot CLI. You need both the GitHub CLI and the Copilot CLI extension installed and signed in.

1. Install the GitHub CLI

Follow the official installation guide for your platform, then authenticate:

gh auth login

2. Install the GitHub Copilot CLI extension

gh extension install github/gh-copilot

3. Authenticate with Copilot

gh copilot auth

4. Install the SDK

npm install @github/copilot-sdk

Once authenticated, policy --init will automatically detect the SDK and run AI-enhanced analysis. To debug SDK interactions, set AGENT_SHELL_COPILOT_DEBUG=1.

Prerequisites

  • Must be run inside a git repository (git rev-parse --show-toplevel is used to locate the repo root)
  • agent-shell must be globally installed (required for the generated hook script to be on PATH)
  • @github/copilot-sdk is optional — see Authentication Setup above to enable AI-enhanced analysis

Example Output

Scanning project...
Discovered: 8 npm script(s), 12 workflow command(s), 3 mise task(s), 1 language(s)
Created .github/hooks/agent-shell/policy.json
Created .github/hooks/agent-shell/hooks.json

--- Proposed Policy ---
{
  "allow": [
    "git branch --list *",
    "git branch --show-current",
    "git diff *",
    "git log *",
    "git rev-parse *",
    "git show *",
    "git status *",
    "npm run build",
    "npm run lint",
    "npm test",
    "pwd"
  ],
  "deny": [
    "rm -rf *",
    "sudo *"
  ]
}

--- Hook Configuration ---
{
  "version": 1,
  "hooks": {
    "preToolUse": [
      {
        "type": "command",
        "bash": "agent-shell policy-check",
        "timeoutSec": 30
      }
    ]
  }
}

Environment Variables

VariablePurposeDefault
AGENTSHELL_PASSTHROUGHSet to 1 to bypass all instrumentationUnset (instrumentation active)
AGENTSHELL_ACTOROverride automatic actor detectionUnset (heuristic detection)
AGENTSHELL_SESSION_IDShared session ID for event correlationUnset (fresh UUID per invocation)
AGENTSHELL_LOG_DIROverride event file directory.agent-shell/events/
AGENTSHELL_POLICY_PATHOverride policy file location for policy-check.github/hooks/agent-shell/policy.json
AGENTSHELL_TAG_<key>Attach custom key=value metadata to eventsNone
AGENT_SHELL_COPILOT_DEBUGSet to 1 to enable debug logging for Copilot SDK interactions during policy --initUnset (debug logging off)

Custom Tags

Set AGENTSHELL_TAG_* environment variables to attach metadata:

AGENTSHELL_TAG_pr=1234 AGENTSHELL_TAG_task=fix-auth npm test

Produces: "tags": { "pr": "1234", "task": "fix-auth" }

Session Correlation

By default, each script invocation gets a fresh session ID. To correlate events across a workflow:

export AGENTSHELL_SESSION_ID=$(uuidgen)
npm run lint && npm test && npm run build
# All three events share the same session_id

Scope

  • npm only — Configured via .npmrc script-shell. Other package managers (yarn, pnpm, bun) are not supported.
  • POSIX only — macOS and Linux. Windows requires WSL or Git Bash.

Troubleshooting

npm fails with "script-shell not found"

Your .npmrc references agent-shell but it's not installed globally:

# Fix: install the package globally
npm install -g @lousy-agents/agent-shell

# Or: bypass temporarily
AGENTSHELL_PASSTHROUGH=1 npm test

Bypass all instrumentation

Set the passthrough escape hatch — zero overhead, zero recording:

AGENTSHELL_PASSTHROUGH=1 npm test

Remove instrumentation entirely

Remove the script-shell line from .npmrc:

# Edit .npmrc and delete this line:
# script-shell=agent-shell

# Or remove it with sed:
sed -i '' '/script-shell/d' .npmrc

Then optionally uninstall:

npm uninstall -g @lousy-agents/agent-shell

Verify the shim is active

npx agent-shell --version

Clean up recorded events

rm -rf .agent-shell/

.gitignore

Add .agent-shell/ to your .gitignore:

# agent-shell telemetry
.agent-shell/

版本与发布记录

@lousy-agents/agent-shell 共发布 168 个版本,首次发布于 2026/03/11;过去 12 个月发布了 168 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
5.22.24latest2026/11/021 天前
5.22.232026/11/012 天前
5.22.222026/10/313 天前
5.22.212026/10/313 天前
5.22.202026/10/303 天前
5.22.192026/10/304 天前

关于 @lousy-agents/agent-shell 的常见问题

@lousy-agents/agent-shell 是什么?

一个用于npm脚本执行的飞行记录器

如何安装 @lousy-agents/agent-shell?

在项目目录运行 npm install @lousy-agents/agent-shell,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 agent-shell,可以用 npx agent-shell 直接运行。

@lousy-agents/agent-shell 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/lousy-agents__agent-shell 是否存在。

@lousy-agents/agent-shell 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@lousy-agents/agent-shell 可以商用吗?

@lousy-agents/agent-shell 使用 BSD-2-Clause-Patent 许可。声明的许可为 BSD-2-Clause-Patent,请阅读许可原文确认使用条件。以上为概括,不构成法律意见,请以许可原文为准。

@lousy-agents/agent-shell 还在维护吗?

最新版本 5.22.24 发布于 2026/11/02(1 天前);至今共发布 168 个版本,其中过去 12 个月发布了 168 个;首次发布于 2026/03/11。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。