Compare commits

...
Author SHA1 Message Date
David Mokos d2f8b90f53 adds Grok Bot environment detection (#21)
Grok Bot sets CURSOR_AGENT alongside SAND_BOX_BOOT_ID and SAND_BOX_STORE_ID, so it is matched before Cursor. Session ids still come from CURSOR_CONVERSATION_ID.
2026-10-24 03:10:00 -07:00
David Mokos e308d262b1 adds Factory Droid detection (#20) 2026-09-24 04:58:40 -07:00
David Mokos 09f4c420ad adds Grok environment detection (#19) 2026-08-24 23:30:14 +02:00
David Mokos 9205525ad4 adds Muse Code environment detection (#18) 2026-08-17 18:02:47 +02:00
David Mokos cf68eb6e0c updates repository metadata for npm provenance (#16) 2026-08-04 16:15:59 +02:00
David Mokos b7c8ccd0aa documents opencode detection and bumps version to 0.1.5 (#15) 2026-08-04 16:11:59 +02:00
Din 1cad0bda77 [lib] detect OpenCode from environment variables (#14)
OpenCode was only detectable through the process-tree strategy, which is
opt-in via experimentalProcessTree. With the default strategies it was
never detected.

The OpenCode CLI unconditionally sets OPENCODE=1 and OPENCODE_PID in its
yargs middleware, so both are inherited by any process it spawns.
2026-08-04 07:01:07 -07:00
David Mokos 8e4fdd3c6f add rork environment detection 2026-07-18 16:42:01 +02:00
David Mokos 238a06ac5f adds repository metadata and normalizes bin path for npm provenance 2026-07-17 17:50:47 +02:00
David Mokos 2369c9194f splits exports types per condition and bumps to 0.1.3 2026-07-17 17:49:19 +02:00
David Mokos eecb49a358 [pkg] add Replit detection (#12)
* add replit agent detection

* add bolt agent detection
2026-07-17 17:17:55 +02:00
David Mokos 9010110dea restructures readme to match ci-info style (#11) 2026-07-17 13:37:47 +02:00
David Mokos 8738a0aa09 adds npm trusted publishing workflow (#10) 2026-07-03 16:41:46 +02:00
David Mokos 0855546c89 dual publish esm and commonjs builds 2026-06-26 17:09:39 +02:00
David Mokos a9720cb533 fixes publish prepack lifecycle 2026-06-26 12:39:35 +02:00
David Mokos b742350c0b fixes cross-platform ci test execution 2026-06-25 20:40:21 +02:00
David Mokos 4784e73f5a adds cross-platform package tests 2026-06-25 19:40:03 +02:00
David Mokos 5c2c67042d simplify agent detection defaults (#5) 2026-06-25 19:32:11 +02:00
David Mokos a49b298948 [pkg] document npm install flow (#4)
* document npm install and normalize bin path

* fix npx cli package execution
2026-06-25 13:11:13 +02:00
15 changed files with 2088 additions and 276 deletions

No files matched your search

+41
View File
@@ -0,0 +1,41 @@
name: publish
on:
release:
types: [published]
permissions:
contents: read
id-token: write
jobs:
publish:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 24
registry-url: https://registry.npmjs.org
cache: npm
- name: Update npm
run: npm install -g npm@latest
- name: Install dependencies
run: npm ci
- name: Verify release tag matches package.json version
run: |
PKG_VERSION="v$(node -p "require('./package.json').version")"
if [ "$GITHUB_REF_NAME" != "$PKG_VERSION" ]; then
echo "Release tag $GITHUB_REF_NAME does not match package.json version $PKG_VERSION"
exit 1
fi
- name: Publish
run: npm publish
+43
View File
@@ -0,0 +1,43 @@
name: test
on:
workflow_dispatch:
pull_request:
push:
permissions:
contents: read
jobs:
test:
name: ${{ matrix.os }} / Node ${{ matrix.node-version }}
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os:
- ubuntu-latest
- macos-latest
- windows-latest
node-version:
- 18.18.0
- 20.x
- 22.x
- 24.x
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: npm
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
+119 -60
View File
@@ -2,40 +2,131 @@
Detect whether a JavaScript CLI is running inside a coding agent.
The package is designed around small detection strategies and data-driven agent definitions. Today it supports environment-variable detection and parent-process detection; additional agents or strategies can be added without changing the core detector.
Please [open an issue](https://github.com/expo/agent-cli-detector/issues/new)
if your coding agent isn't properly detected :)
## Install
[![npm](https://img.shields.io/npm/v/agent-cli-detector.svg)](https://www.npmjs.com/package/agent-cli-detector)
[![Tests](https://github.com/expo/agent-cli-detector/actions/workflows/test.yml/badge.svg)](https://github.com/expo/agent-cli-detector/actions)
```sh
## Installation
```bash
npm install agent-cli-detector
```
## Library usage
## Usage
```ts
import { detectAgent, isRunningFromAgent } from "agent-cli-detector";
```js
import { detectAgent } from "agent-cli-detector";
const result = detectAgent();
if (result.detected) {
console.log(`running from ${result.agent.name}`);
console.log(`confidence: ${result.confidence.level} (${result.confidence.score})`);
console.log("The name of the coding agent is:", result.agent.name);
} else {
console.log("This program is not running inside a coding agent");
}
```
if (result.agent.sessionId) {
console.log(`session: ${result.agent.sessionId}`);
## Supported agents
Officially supported coding agents:
| Name | ID | Session ID |
| ----------------------------------------------------------------- | ------------- | ---------- |
| [Antigravity](https://antigravity.google/) | `antigravity` | ✅ |
| [Bolt](https://bolt.new/) | `bolt` | 🚫 |
| [Claude Code](https://claude.com/claude-code) | `claude-code` | ✅ |
| [Cline](https://cline.bot/) | `cline` | 🚫 |
| [Codex](https://developers.openai.com/codex/) | `codex` | ✅ |
| [Cursor](https://cursor.com/) | `cursor` | ✅ |
| [Devin](https://devin.ai/) | `devin` | 🚫 |
| [Factory Droid](https://docs.factory.ai/droid-cli/overview) | `droid` | 🚫 |
| [Gemini CLI](https://github.com/google-gemini/gemini-cli) | `gemini` | 🚫 |
| [GitHub Copilot CLI](https://github.com/github/copilot-cli) | `copilot` | ✅ |
| [Grok](https://x.ai/build) | `grok` | ✅ |
| [Grok Bot](https://x.ai/bot) | `grok-bot` | ✅ |
| [Kilo Code](https://kilocode.ai/) | `kilocode` | ✅ |
| [Kiro](https://kiro.dev/) | `kiro` | ✅ |
| [Muse Code][muse-code] | `muse` | 🚫 |
| [OpenCode](https://opencode.ai/) | `opencode` | 🚫 |
| [Pi](https://github.com/badlogic/pi-mono) | `pi` | 🚫 |
| [Replit](https://replit.com/) | `replit` | ✅ |
| [Rork](https://rork.com/) | `rork` | 🚫 |
[muse-code]: https://developer.meta.com/ai/products/muse-code/
Detection is data-driven: the exact environment variables and process
patterns for each agent live in [`src/agents.ts`](src/agents.ts).
OpenCode 1.0.19 and later is detected from environment variables by default.
OpenCode 0.x requires experimental process-tree detection.
## API
### `detectAgent([options])`
Runs detection and returns a `DetectionResult`:
```js
{
detected: true,
agent: {
id: "cursor",
name: "Cursor",
sessionId: "d9e9cd60-2e1c-487c-9bc7-fceee5e9c3a2"
}
}
```
### `result.detected`
A boolean. Will be `true` if the code is running inside a coding agent,
otherwise `false`.
### `result.agent.id`
A stable identifier for the detected agent (see the ID column in the
support table above). Prefer comparing against this instead of
`result.agent.name`.
### `result.agent.name`
A string containing the display name of the detected coding agent.
Don't depend on the value of this string not to change for a specific
agent. If you find yourself writing `result.agent.name === "Claude Code"`,
you most likely want to use `result.agent.id === "claude-code"` instead.
### `result.agent.sessionId`
A string containing the agent's session identifier, normalized from
agent-specific environment variables such as `CODEX_THREAD_ID`,
`CURSOR_CONVERSATION_ID`, `CLAUDE_CODE_SESSION_ID`,
`ANTIGRAVITY_TRAJECTORY_ID`, `KIRO_SESSION_ID`, `KILO_RUN_ID`, and
`COPILOT_AGENT_SESSION_ID`, `REPLIT_SESSION`, and `GROK_SESSION_ID`.
Omitted when the agent doesn't expose one
(see the Session ID column in the support table above).
### `isRunningFromAgent([options])`
A convenience shortcut that returns `result.detected` as a boolean:
```js
import { isRunningFromAgent } from "agent-cli-detector";
if (isRunningFromAgent()) {
// Adjust CLI behavior for agent-driven execution.
}
```
## CLI usage
## CLI
```sh
npx detect-agent
npx detect-agent --json
The package also ships a CLI:
```bash
npx agent-cli-detector
npx agent-cli-detector --json
```
Exit codes:
@@ -43,59 +134,25 @@ Exit codes:
- `0`: a coding agent was detected
- `1`: no coding agent was detected
## Result shape
## Process-tree detection (experimental)
`detectAgent()` returns a normalized agent identity instead of the internal detector definition:
Detection uses environment variables by default. Parent-process
inspection is available as an opt-in for callers that can tolerate
best-effort process-tree matching:
```ts
{
detected: true,
agent: {
id: "cursor",
name: "Cursor",
sessionId: "d9e9cd60-2e1c-487c-9bc7-fceee5e9c3a2"
},
confidence: {
level: "high",
score: 0.988,
signals: 2
}
}
```js
const result = detectAgent({ experimentalProcessTree: true });
```
`sessionId` is normalized from agent-specific environment variables when available, such as `CODEX_THREAD_ID`, `CURSOR_CONVERSATION_ID`, `CLAUDE_CODE_SESSION_ID`, `ANTIGRAVITY_TRAJECTORY_ID`, `KIRO_SESSION_ID`, `KILO_RUN_ID`, and `COPILOT_AGENT_SESSION_ID`.
Some sandboxes block `ps`, and process names can vary by launcher, so
process-tree detection should be treated as experimental. It has only
been tested on macOS and does not work on Windows.
Confidence is a heuristic score from `0` to `1`, not a statistical probability. Exact agent-owned environment markers score highest, presence-only environment markers score medium-high, and process-tree signals score medium by default. Multiple signals for the same agent are combined with `1 - product(1 - signalScore)`, so corroborating evidence raises confidence while keeping the score bounded at `1`.
## Supported agents
The built-in detector uses two strategies:
- `environment`: matches agent-specific environment variables in `process.env`
- `process-tree`: walks up the current process tree with `ps` and matches ancestor command names
| Agent | Environment strategy | Process-tree strategy | Session ID |
| --- | --- | --- | --- |
| Antigravity | `ANTIGRAVITY_AGENT=1`, `ANTIGRAVITY_TRAJECTORY_ID` | `antigravity` | `ANTIGRAVITY_TRAJECTORY_ID` |
| Claude Code | `CLAUDECODE=1`, `CLAUDE_CODE_SESSION_ID`, `CLAUDE_CODE_CHILD_SESSION=1`, `CLAUDE_CODE_EXECPATH` | `claude` | `CLAUDE_CODE_SESSION_ID` |
| Cline | `CLINE_WRAPPER_PATH` | `cline` | - |
| Codex | `CODEX_CI=1`, `CODEX_SHELL=1`, `CODEX_THREAD_ID`, `CODEX_INTERNAL_ORIGINATOR_OVERRIDE` containing `codex` | `codex` | `CODEX_THREAD_ID` |
| Cursor | `CURSOR_AGENT=1`, `CURSOR_CONVERSATION_ID`, `CURSOR_EXTENSION_HOST_ROLE=agent-exec` | `cursor` | `CURSOR_CONVERSATION_ID` |
| Devin | - | command containing `devin` | - |
| Gemini CLI | `GEMINI_CLI=1`, `GEMINI_CLI_NO_RELAUNCH=true` | `gemini` | - |
| GitHub Copilot CLI | `COPILOT_CLI=1`, `COPILOT_AGENT_SESSION_ID`, `COPILOT_RUN_APP=1` | `github-copilot-cli` or `copilot` | `COPILOT_AGENT_SESSION_ID` |
| Kiro | `KIRO_SESSION_ID` | command containing `kiro` | `KIRO_SESSION_ID` |
| Kilo Code | `KILO=1`, `KILOCODE_VERSION`, `KILO_RUN_ID` | `kilo` or `kilocode` | `KILO_RUN_ID` |
| OpenCode | - | `opencode` | - |
| Pi | `PI_CODING_AGENT=true` | - | - |
Process-tree detection is best-effort. Some sandboxes block `ps`, so environment-variable matches are preferred when available.
## Extending
## Custom agents
Add an agent by supplying an `AgentDefinition`:
```ts
```js
import { detectAgent, defaultAgents } from "agent-cli-detector";
const result = detectAgent({
@@ -111,6 +168,8 @@ const result = detectAgent({
});
```
## Custom strategies
Add a detection strategy by implementing `DetectionStrategy`:
```ts
@@ -126,4 +185,4 @@ const strategy: DetectionStrategy = {
## License
MIT
[MIT](LICENSE)
+1449 -3
View File
File diff suppressed because it is too large. Load diff
+28 -10
View File
@@ -1,31 +1,40 @@
{
"name": "agent-cli-detector",
"version": "0.1.0",
"version": "0.1.8",
"description": "Detect whether a JavaScript CLI is running inside a coding agent.",
"type": "module",
"sideEffects": false,
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"bin": {
"detect-agent": "./dist/cli.js"
"agent-cli-detector": "dist/cli.js"
},
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
"import": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
}
},
"types": "./dist/index.d.ts",
"files": [
"dist",
"README.md"
"README.md",
"LICENSE"
],
"engines": {
"node": ">=18.18"
},
"scripts": {
"build": "tsc -p tsconfig.json",
"build": "tsup && node -e \"require('node:fs').chmodSync('dist/cli.js', 0o755)\"",
"clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
"test": "npm run build && node --test test/*.test.mjs",
"prepack": "npm run clean && npm test"
"test": "npm run build && node --test test/detector.test.mjs test/package.test.mjs",
"prepack": "npm run clean && npm run build && node --test test/detector.test.mjs"
},
"keywords": [
"agent",
@@ -38,6 +47,15 @@
"license": "MIT",
"devDependencies": {
"@types/node": "^24.0.4",
"tsup": "^8.5.0",
"typescript": "^5.8.3"
}
},
"repository": {
"type": "git",
"url": "git+https://github.com/expo/agent-cli-detector.git"
},
"bugs": {
"url": "https://github.com/expo/agent-cli-detector/issues"
},
"homepage": "https://github.com/expo/agent-cli-detector#readme"
}
+56 -11
View File
@@ -7,19 +7,26 @@ export const defaultAgents = [
env: [
{ name: "CODEX_CI", value: "1" },
{ name: "CODEX_SHELL", value: "1" },
{ name: "CODEX_THREAD_ID" },
{ name: "CODEX_INTERNAL_ORIGINATOR_OVERRIDE", value: /codex/i }
{ name: "CODEX_THREAD_ID" }
],
process: [{ pattern: /^codex$/i }],
sessionEnv: ["CODEX_THREAD_ID"]
},
{
id: "grok-bot",
name: "Grok Bot",
env: [
{ name: "SAND_BOX_BOOT_ID" },
{ name: "SAND_BOX_STORE_ID" }
],
sessionEnv: ["CURSOR_CONVERSATION_ID"]
},
{
id: "cursor",
name: "Cursor",
env: [
{ name: "CURSOR_AGENT", value: "1" },
{ name: "CURSOR_CONVERSATION_ID" },
{ name: "CURSOR_EXTENSION_HOST_ROLE", value: "agent-exec" }
{ name: "CURSOR_CONVERSATION_ID" }
],
process: [{ pattern: /^cursor$/i }],
sessionEnv: ["CURSOR_CONVERSATION_ID"]
@@ -29,9 +36,7 @@ export const defaultAgents = [
name: "Claude Code",
env: [
{ name: "CLAUDECODE", value: "1" },
{ name: "CLAUDE_CODE_SESSION_ID" },
{ name: "CLAUDE_CODE_CHILD_SESSION", value: "1" },
{ name: "CLAUDE_CODE_EXECPATH" }
{ name: "CLAUDE_CODE_SESSION_ID" }
],
process: [{ pattern: /^claude$/i }],
sessionEnv: ["CLAUDE_CODE_SESSION_ID"]
@@ -39,6 +44,10 @@ export const defaultAgents = [
{
id: "opencode",
name: "OpenCode",
env: [
{ name: "OPENCODE", value: "1" },
{ name: "OPENCODE_PID" }
],
process: [{ pattern: /^opencode$/i }]
},
{
@@ -46,15 +55,26 @@ export const defaultAgents = [
name: "Devin",
process: [{ pattern: /devin/i }]
},
{
id: "droid",
name: "Factory Droid",
env: [{ name: "FACTORY_ENV", value: "production" }]
},
{
id: "gemini",
name: "Gemini CLI",
env: [
{ name: "GEMINI_CLI", value: "1" },
{ name: "GEMINI_CLI_NO_RELAUNCH", value: "true", confidence: "medium" }
],
env: [{ name: "GEMINI_CLI", value: "1" }],
process: [{ pattern: /^gemini$/i }]
},
{
id: "grok",
name: "Grok",
env: [
{ name: "GROK_AGENT", value: "1" },
{ name: "GROK_SESSION_ID" }
],
sessionEnv: ["GROK_SESSION_ID"]
},
{
id: "antigravity",
name: "Antigravity",
@@ -65,11 +85,31 @@ export const defaultAgents = [
process: [{ pattern: /^antigravity$/i }],
sessionEnv: ["ANTIGRAVITY_TRAJECTORY_ID"]
},
{
id: "bolt",
name: "Bolt",
env: [
{ name: "BOLT_ENV" },
{ name: "BOLT_ORIGIN" },
{ name: "BOLT_SERVER_URL" }
]
},
{
id: "pi",
name: "Pi",
env: [{ name: "PI_CODING_AGENT", value: "true" }]
},
{
id: "replit",
name: "Replit",
env: [{ name: "REPLIT_SESSION" }],
sessionEnv: ["REPLIT_SESSION"]
},
{
id: "rork",
name: "Rork",
env: [{ name: "RORK_API_URL" }]
},
{
id: "kiro",
name: "Kiro",
@@ -77,6 +117,11 @@ export const defaultAgents = [
process: [{ pattern: /kiro/i }],
sessionEnv: ["KIRO_SESSION_ID"]
},
{
id: "muse",
name: "Muse Code",
env: [{ name: "MUSE_RELEASE_INFO" }]
},
{
id: "cline",
name: "Cline",
+1 -2
View File
@@ -48,7 +48,6 @@ function toJsonResult(result: DetectionResult): object {
id: result.agent.id,
name: result.agent.name,
sessionId: result.agent.sessionId
},
confidence: result.confidence
}
};
}
+15 -84
View File
@@ -3,8 +3,6 @@ import { EnvironmentDetectionStrategy } from "./strategies/environment.js";
import { ProcessTreeDetectionStrategy } from "./strategies/process-tree.js";
import type {
AgentDefinition,
Confidence,
ConfidenceMeasurement,
DetectAgentOptions,
DetectedAgent,
DetectionContext,
@@ -15,7 +13,7 @@ import type {
export function detectAgent(options: DetectAgentOptions = {}): DetectionResult {
const agents = options.agents ?? defaultAgents;
const strategies = options.strategies ?? defaultStrategies(options.includeProcessTree);
const strategies = options.strategies ?? defaultStrategies(options.experimentalProcessTree);
const context: DetectionContext = {
env: options.env ?? process.env,
pid: options.pid ?? process.pid,
@@ -34,8 +32,7 @@ export function detectAgent(options: DetectAgentOptions = {}): DetectionResult {
return {
detected: true,
agent: bestMatch.detectedAgent,
confidence: bestMatch.confidence
agent: bestMatch
};
}
@@ -43,90 +40,40 @@ export function isRunningFromAgent(options: DetectAgentOptions = {}): boolean {
return detectAgent(options).detected;
}
export function createDefaultStrategies(includeProcessTree = true): readonly DetectionStrategy[] {
return defaultStrategies(includeProcessTree);
export function createDefaultStrategies(experimentalProcessTree = false): readonly DetectionStrategy[] {
return defaultStrategies(experimentalProcessTree);
}
function defaultStrategies(includeProcessTree = true): readonly DetectionStrategy[] {
function defaultStrategies(experimentalProcessTree = false): readonly DetectionStrategy[] {
const strategies: DetectionStrategy[] = [new EnvironmentDetectionStrategy()];
if (includeProcessTree) {
if (experimentalProcessTree) {
strategies.push(new ProcessTreeDetectionStrategy());
}
return strategies;
}
interface AgentMatch {
readonly agent: AgentDefinition;
readonly detectedAgent: DetectedAgent;
readonly confidence: ConfidenceMeasurement;
readonly evidence: readonly DetectionEvidence[];
}
function selectBestAgent(
agents: readonly AgentDefinition[],
matches: readonly DetectionEvidence[],
env: NodeJS.ProcessEnv
): AgentMatch | undefined {
const agentMatches: AgentMatch[] = [];
): DetectedAgent | undefined {
const matchedAgentIds = new Set(matches.map((match) => match.agent.id));
for (const agent of agents) {
const evidence = matches.filter((match) => match.agent.id === agent.id);
if (evidence.length === 0) {
if (!matchedAgentIds.has(agent.id)) {
continue;
}
agentMatches.push({
agent,
detectedAgent: {
id: agent.id,
name: agent.name,
...sessionIdProperties(agent, env)
},
confidence: measureConfidence(evidence),
evidence
});
return {
id: agent.id,
name: agent.name,
...sessionIdProperties(agent, env)
};
}
return agentMatches.sort(compareAgentMatches)[0];
}
function measureConfidence(evidence: readonly DetectionEvidence[]): ConfidenceMeasurement {
const score = roundScore(1 - evidence.reduce((miss, match) => miss * (1 - match.score), 1));
return {
level: scoreToConfidence(score),
score,
signals: evidence.length
};
}
function compareAgentMatches(left: AgentMatch, right: AgentMatch): number {
const scoreDelta = right.confidence.score - left.confidence.score;
if (scoreDelta !== 0) {
return scoreDelta;
}
return bestStrategyRank(right.evidence) - bestStrategyRank(left.evidence);
}
function bestStrategyRank(evidence: readonly DetectionEvidence[]): number {
return Math.max(...evidence.map((match) => strategyRank(match.strategy)));
}
function strategyRank(strategy: string): number {
if (strategy === "environment") {
return 2;
}
if (strategy === "process-tree") {
return 1;
}
return 0;
return undefined;
}
function sessionIdProperties(
@@ -143,19 +90,3 @@ function sessionIdProperties(
return {};
}
function scoreToConfidence(score: number): Confidence {
if (score >= 0.85) {
return "high";
}
if (score >= 0.6) {
return "medium";
}
return "low";
}
function roundScore(score: number): number {
return Math.round(score * 1000) / 1000;
}
-2
View File
@@ -14,8 +14,6 @@ export type {
AgentDefinition,
AgentId,
AgentIdentity,
Confidence,
ConfidenceMeasurement,
DetectAgentOptions,
DetectedAgent,
DetectionContext,
-37
View File
@@ -1,6 +1,5 @@
import type {
AgentDefinition,
Confidence,
DetectionContext,
DetectionEvidence,
DetectionStrategy,
@@ -47,49 +46,13 @@ function matchesEnvValue(value: string, matcher: EnvValueMatcher | undefined): b
}
function toEvidence(agent: AgentDefinition, signal: EnvSignal, value: string): DetectionEvidence {
const score = scoreForEnvSignal(signal);
return {
agent: {
id: agent.id,
name: agent.name
},
strategy: "environment",
confidence: scoreToConfidence(score),
score,
signal: signal.name,
value
};
}
function scoreForEnvSignal(signal: EnvSignal): number {
if (signal.confidence !== undefined) {
return scoreForConfidence(signal.confidence);
}
return signal.value === undefined ? 0.75 : 0.95;
}
function scoreForConfidence(confidence: Confidence): number {
if (confidence === "high") {
return 0.95;
}
if (confidence === "medium") {
return 0.75;
}
return 0.4;
}
function scoreToConfidence(score: number): Confidence {
if (score >= 0.85) {
return "high";
}
if (score >= 0.6) {
return "medium";
}
return "low";
}
-28
View File
@@ -84,45 +84,17 @@ function toEvidence(
signal: ProcessSignal,
processInfo: ProcessInfo
): DetectionEvidence {
const score = scoreForProcessSignal(signal);
return {
agent: {
id: agent.id,
name: agent.name
},
strategy: "process-tree",
confidence: scoreToConfidence(score),
score,
signal: signal.pattern.toString(),
value: `${processInfo.pid}:${processInfo.command}`
};
}
function scoreForProcessSignal(signal: ProcessSignal): number {
if (signal.confidence === "high") {
return 0.85;
}
if (signal.confidence === "low") {
return 0.4;
}
return 0.65;
}
function scoreToConfidence(score: number): "high" | "medium" | "low" {
if (score >= 0.85) {
return "high";
}
if (score >= 0.6) {
return "medium";
}
return "low";
}
function readPsField(pid: number, field: "comm" | "ppid"): string {
try {
return execFileSync("ps", ["-o", `${field}=`, "-p", String(pid)], {
+9 -15
View File
@@ -1,21 +1,26 @@
export type AgentId =
| "antigravity"
| "bolt"
| "cline"
| "codex"
| "copilot"
| "cursor"
| "devin"
| "droid"
| "gemini"
| "grok"
| "grok-bot"
| "kiro"
| "kilocode"
| "claude-code"
| "muse"
| "opencode"
| "pi";
| "pi"
| "replit"
| "rork";
export type DetectionStrategyName = "environment" | "process-tree";
export type Confidence = "high" | "medium" | "low";
export type EnvValueMatcher =
| string
| RegExp
@@ -24,13 +29,11 @@ export type EnvValueMatcher =
export interface EnvSignal {
readonly name: string;
readonly value?: EnvValueMatcher;
readonly confidence?: Confidence;
readonly description?: string;
}
export interface ProcessSignal {
readonly pattern: RegExp;
readonly confidence?: Confidence;
readonly description?: string;
}
@@ -58,22 +61,13 @@ export interface ProcessInfo {
export interface DetectionEvidence {
readonly agent: AgentIdentity;
readonly strategy: DetectionStrategyName | string;
readonly confidence: Confidence;
readonly score: number;
readonly signal: string;
readonly value?: string;
}
export interface ConfidenceMeasurement {
readonly level: Confidence;
readonly score: number;
readonly signals: number;
}
export interface DetectionResult {
readonly detected: boolean;
readonly agent?: DetectedAgent;
readonly confidence?: ConfidenceMeasurement;
}
export interface DetectionContext {
@@ -93,6 +87,6 @@ export interface DetectAgentOptions {
readonly pid?: number;
readonly agents?: readonly AgentDefinition[];
readonly strategies?: readonly DetectionStrategy[];
readonly includeProcessTree?: boolean;
readonly experimentalProcessTree?: boolean;
readonly maxProcessDepth?: number;
}
+170 -24
View File
@@ -1,6 +1,7 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
createDefaultStrategies,
detectAgent,
EnvironmentDetectionStrategy,
ProcessTreeDetectionStrategy
@@ -10,14 +11,11 @@ test("detects an agent from a strong environment variable", () => {
const result = detectAgent({
env: {
CLAUDECODE: "1"
},
includeProcessTree: false
}
});
assert.equal(result.detected, true);
assert.equal(result.agent.id, "claude-code");
assert.equal(result.confidence.level, "high");
assert.equal(result.confidence.score, 0.95);
});
test("normalizes session ids across agent-specific environment variables", () => {
@@ -25,8 +23,7 @@ test("normalizes session ids across agent-specific environment variables", () =>
env: {
CURSOR_AGENT: "1",
CURSOR_CONVERSATION_ID: "conversation-123"
},
includeProcessTree: false
}
});
assert.equal(result.detected, true);
@@ -35,17 +32,13 @@ test("normalizes session ids across agent-specific environment variables", () =>
name: "Cursor",
sessionId: "conversation-123"
});
assert.equal(result.confidence.level, "high");
assert.equal(result.confidence.score, 0.988);
assert.equal(result.confidence.signals, 2);
});
test("detects kiro and normalizes its session id", () => {
const result = detectAgent({
env: {
KIRO_SESSION_ID: "a537a99b-b87d-450b-ace9-74231e3f4fe8"
},
includeProcessTree: false
}
});
assert.equal(result.detected, true);
@@ -54,8 +47,171 @@ test("detects kiro and normalizes its session id", () => {
name: "Kiro",
sessionId: "a537a99b-b87d-450b-ace9-74231e3f4fe8"
});
assert.equal(result.confidence.level, "medium");
assert.equal(result.confidence.score, 0.75);
});
test("detects replit and normalizes its session id", () => {
const result = detectAgent({
env: {
REPLIT_SESSION: "session-123"
}
});
assert.equal(result.detected, true);
assert.deepEqual(result.agent, {
id: "replit",
name: "Replit",
sessionId: "session-123"
});
});
test("detects grok and normalizes its session id", () => {
const result = detectAgent({
env: {
GROK_AGENT: "1",
GROK_SESSION_ID: "01a035a8-166c-7771-8e5e-f67e0dd98c83"
}
});
assert.equal(result.detected, true);
assert.deepEqual(result.agent, {
id: "grok",
name: "Grok",
sessionId: "01a035a8-166c-7771-8e5e-f67e0dd98c83"
});
});
test("detects Grok Bot from SAND_BOX_BOOT_ID and normalizes the conversation id", () => {
const result = detectAgent({
env: {
CURSOR_AGENT: "1",
CURSOR_CONVERSATION_ID: "conversation-123",
SAND_BOX_BOOT_ID: "boot-456"
}
});
assert.equal(result.detected, true);
assert.deepEqual(result.agent, {
id: "grok-bot",
name: "Grok Bot",
sessionId: "conversation-123"
});
});
test("detects cursor from CURSOR_AGENT without Grok Bot signals", () => {
const result = detectAgent({
env: {
CURSOR_AGENT: "1",
CURSOR_CONVERSATION_ID: "conversation-123"
}
});
assert.equal(result.detected, true);
assert.deepEqual(result.agent, {
id: "cursor",
name: "Cursor",
sessionId: "conversation-123"
});
});
test("detects Grok Bot from SAND_BOX_STORE_ID alone", () => {
const result = detectAgent({
env: {
SAND_BOX_STORE_ID: "store-789"
}
});
assert.equal(result.detected, true);
assert.deepEqual(result.agent, {
id: "grok-bot",
name: "Grok Bot"
});
});
test("detects Factory Droid from FACTORY_ENV", () => {
const result = detectAgent({
env: {
FACTORY_ENV: "production"
}
});
assert.equal(result.detected, true);
assert.deepEqual(result.agent, {
id: "droid",
name: "Factory Droid"
});
});
test("detects rork from RORK_API_URL", () => {
const result = detectAgent({
env: {
RORK_API_URL: "https://api.rork.com"
}
});
assert.equal(result.detected, true);
assert.deepEqual(result.agent, {
id: "rork",
name: "Rork"
});
});
test("detects Muse Code from MUSE_RELEASE_INFO", () => {
const result = detectAgent({
env: {
MUSE_RELEASE_INFO: JSON.stringify({
channel: "muse-stable",
version: "0.1.0-R708.1"
})
}
});
assert.equal(result.detected, true);
assert.deepEqual(result.agent, {
id: "muse",
name: "Muse Code"
});
});
test("detects bolt from any known environment variable", () => {
for (const envName of ["BOLT_ENV", "BOLT_ORIGIN", "BOLT_SERVER_URL"]) {
const result = detectAgent({
env: {
[envName]: "1"
}
});
assert.equal(result.detected, true);
assert.deepEqual(result.agent, {
id: "bolt",
name: "Bolt"
});
}
});
test("detects opencode from any known environment variable", () => {
for (const env of [{ OPENCODE: "1" }, { OPENCODE_PID: "12345" }]) {
const result = detectAgent({ env });
assert.equal(result.detected, true);
assert.deepEqual(result.agent, {
id: "opencode",
name: "OpenCode"
});
}
});
test("default strategies only use environment variables", () => {
assert.deepEqual(
createDefaultStrategies().map((strategy) => strategy.name),
["environment"]
);
});
test("process tree strategy is experimental and opt-in", () => {
assert.deepEqual(
createDefaultStrategies(true).map((strategy) => strategy.name),
["environment", "process-tree"]
);
});
test("process tree detection can detect kiro in the hierarchy", () => {
@@ -81,22 +237,17 @@ test("process tree detection can detect kiro in the hierarchy", () => {
assert.equal(result.detected, true);
assert.equal(result.agent.id, "kiro");
assert.equal(result.confidence.level, "high");
assert.equal(result.confidence.score, 0.957);
assert.equal(result.confidence.signals, 3);
});
test("does not detect unrelated environment variables", () => {
const result = detectAgent({
env: {
PATH: "/usr/bin"
},
includeProcessTree: false
}
});
assert.equal(result.detected, false);
assert.equal(result.agent, undefined);
assert.equal(result.confidence, undefined);
});
test("process tree detection can detect opencode without env vars", () => {
@@ -119,8 +270,6 @@ test("process tree detection can detect opencode without env vars", () => {
assert.equal(result.detected, true);
assert.equal(result.agent.id, "opencode");
assert.equal(result.confidence.level, "medium");
assert.equal(result.confidence.score, 0.65);
});
test("process tree detection can detect devin in the hierarchy", () => {
@@ -143,8 +292,6 @@ test("process tree detection can detect devin in the hierarchy", () => {
assert.equal(result.detected, true);
assert.equal(result.agent.id, "devin");
assert.equal(result.confidence.level, "medium");
assert.equal(result.confidence.score, 0.65);
});
test("custom agents can be added without custom detector code", () => {
@@ -164,5 +311,4 @@ test("custom agents can be added without custom detector code", () => {
assert.equal(result.detected, true);
assert.equal(result.agent.id, "example-agent");
assert.equal(result.confidence.score, 0.95);
});
+138
View File
@@ -0,0 +1,138 @@
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import test from "node:test";
const projectRoot = path.resolve(fileURLToPath(new URL("..", import.meta.url)));
test("packed package can be installed, imported, and run as a CLI", () => {
const workspace = mkdtempSync(path.join(tmpdir(), "agent-cli-detector-"));
try {
const packOutput = execNpm(
["pack", "--ignore-scripts", "--json", "--pack-destination", workspace],
{
cwd: projectRoot,
encoding: "utf8"
}
);
const [packResult] = JSON.parse(packOutput);
const tarball = path.join(workspace, packResult.filename);
const packageContents = packResult.files.map((file) => file.path).sort();
assert.deepEqual(packageContents, [
"LICENSE",
"README.md",
"dist/cli.cjs",
"dist/cli.cjs.map",
"dist/cli.d.cts",
"dist/cli.d.ts",
"dist/cli.js",
"dist/cli.js.map",
"dist/index.cjs",
"dist/index.cjs.map",
"dist/index.d.cts",
"dist/index.d.ts",
"dist/index.js",
"dist/index.js.map",
"package.json"
]);
writeFileSync(path.join(workspace, "package.json"), '{"type":"module"}\n');
execNpm(["install", "--ignore-scripts", "--no-audit", "--no-fund", tarball], {
cwd: workspace,
stdio: "pipe"
});
const importOutput = execFileSync(
process.execPath,
[
"--input-type=module",
"--eval",
[
"import { detectAgent, isRunningFromAgent } from 'agent-cli-detector';",
"const result = detectAgent({ env: { CODEX_THREAD_ID: 'thread-123' } });",
"console.log(JSON.stringify({ result, running: isRunningFromAgent({ env: { CODEX_CI: '1' } }) }));"
].join("")
],
{
cwd: workspace,
encoding: "utf8"
}
);
assert.deepEqual(JSON.parse(importOutput), {
result: {
detected: true,
agent: {
id: "codex",
name: "Codex",
sessionId: "thread-123"
}
},
running: true
});
const requireOutput = execFileSync(
process.execPath,
[
"--eval",
[
"const { detectAgent, isRunningFromAgent } = require('agent-cli-detector');",
"const result = detectAgent({ env: { CLAUDECODE: '1', CLAUDE_CODE_SESSION_ID: 'session-123' } });",
"console.log(JSON.stringify({ result, running: isRunningFromAgent({ env: { CLAUDECODE: '1' } }) }));"
].join("")
],
{
cwd: workspace,
encoding: "utf8"
}
);
assert.deepEqual(JSON.parse(requireOutput), {
result: {
detected: true,
agent: {
id: "claude-code",
name: "Claude Code",
sessionId: "session-123"
}
},
running: true
});
const installedPackage = JSON.parse(
readFileSync(path.join(workspace, "node_modules/agent-cli-detector/package.json"), "utf8")
);
const binPath = path.join(workspace, "node_modules/agent-cli-detector", installedPackage.bin["agent-cli-detector"]);
const cliOutput = execFileSync(process.execPath, [binPath, "--json"], {
cwd: workspace,
env: {
...process.env,
CODEX_CI: "1",
CODEX_THREAD_ID: ""
},
encoding: "utf8"
});
assert.deepEqual(JSON.parse(cliOutput), {
detected: true,
agent: {
id: "codex",
name: "Codex"
}
});
} finally {
rmSync(workspace, { recursive: true, force: true });
}
});
function execNpm(args, options) {
if (process.env.npm_execpath !== undefined) {
return execFileSync(process.execPath, [process.env.npm_execpath, ...args], options);
}
const npm = process.platform === "win32" ? "npm.cmd" : "npm";
return execFileSync(npm, args, options);
}
+19
View File
@@ -0,0 +1,19 @@
import { defineConfig } from "tsup";
export default defineConfig({
entry: {
index: "src/index.ts",
cli: "src/cli.ts"
},
format: ["esm", "cjs"],
dts: true,
sourcemap: true,
clean: true,
splitting: false,
target: "node18",
outExtension({ format }) {
return {
js: format === "cjs" ? ".cjs" : ".js"
};
}
});