Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ agentguard init
agentguard status
```

The npm install runs a best-effort local bootstrap; bare `agentguard init` is the required next step. It auto-detects supported agents and configures their hooks/plugins. Inside DSH it installs the native AgentGuard bundle into the default `web` profile; restart DSH after initialization.
The npm install runs a best-effort local bootstrap; bare `agentguard init` is the required next step. It auto-detects supported agents and configures their hooks/plugins. For DSH, it chooses the only installed profile; if several profiles exist, specify `agentguard init --agent dsh --profile desktop` (or set `AGENTGUARD_DSH_PROFILE=desktop`). Restart that DSH profile after initialization.
No Cloud account or network connection is required for the local runtime guard.

## 3 minutes: protect your agent
Expand Down Expand Up @@ -162,7 +162,13 @@ agentguard dsh-scan ./path/to/dsh-plugin --format html --output report.html

Reports include DSH identification confidence, plugin kind, explainable risk level, permission profile, impact layers, source evidence, structured file-coverage accounting, and an installation recommendation. File-count truncation, oversized matching files, or ordinary read failures produce `DSH_SCAN_INCOMPLETE` and can never return `safe-to-try`. See [AgentGuard for DSH](docs/dsh.md) for the risk model and current limitations.

Install AgentGuard as a native DSH tool plugin, then restart the profile:
Install AgentGuard in the profile your DSH host uses, then restart that host. For **DSH Desktop**:

```bash
dsh plugin --profile desktop add --allow-build=@axorasec/agentguard @axorasec/agentguard
```

For **`dsh web`** instead:

```bash
dsh plugin --profile web add --allow-build=@axorasec/agentguard @axorasec/agentguard
Expand All @@ -173,7 +179,7 @@ It also exposes `agentguard_dsh_scan_batch` for a sequential review queue of up
Use `agentguard_dsh_compare` or the `agentguard dsh-compare` CLI command to identify new permissions and runtime risks before updating an approved plugin version.
The native `agentguard_dsh_subscribe` tool binds system-cron threat-feed polling to the current DSH agent. `agentguard_dsh_subscription_status` reports bounded cron and queue metadata without notice contents, and exact-target `agentguard_dsh_unsubscribe` removes cron, matching queued notices, then saved state in retry-safe order. Notification-worthy pulls are durably queued across DSH downtime and delivered as a safe ordinary follow-up only to that exact live agent; delivery never automatically executes scans or remediation. Scheduled self-checks also discover DSH user/project skills, immediate profile manifests, declared direct dependencies, and home/profile Cordis patches without recursively walking dependency trees. See the [DSH subscription and local testing guide](docs/dsh.md#subscribe-to-threat-intelligence-from-dsh).

Update or remove it from the same profile with `dsh plugin --profile web update @axorasec/agentguard` or `dsh plugin --profile web remove @axorasec/agentguard`. The [DSH operations and report guide](docs/dsh.md#operate-the-dsh-installation) includes verification and troubleshooting steps.
Update or remove the bundle in the **same** profile you installed it in (for example, `dsh plugin --profile desktop update @axorasec/agentguard` or `dsh plugin --profile desktop remove @axorasec/agentguard`). The [DSH operations and report guide](docs/dsh.md#operate-the-dsh-installation) includes verification and troubleshooting steps.

> **DSH runtime guard:** the packaged composition enables `protect` mode by default, applying AgentGuard's shared allow/warn/require-approval/block policy before DSH dispatches a tool. Startup logs and the input-redacted `agentguard_dsh_runtime_summary` tool explicitly show the current configured mode and whether pre-execute enforcement is active. Set `runtime.mode: observe` only when audit-only shadow evaluation is required. DSH protection uses DSH's native one-shot approval service and monotonic composition with other policies. Optional `runtime.postResponseMode: block-malicious` suppresses only block-class malicious network results; approval-class post results remain audit-only because DSH has no resumable post-result approval protocol. Exact operator-configured `runtime.attribution.toolOwners` bindings add source ownership without guessing, and `runtime.ownerPolicies` can impose per-owner minimum decisions without weakening shared security policy. Unmapped tools remain `unknown` until DSH exposes a reliable native owner field. See the [DSH runtime guide](docs/dsh-runtime.md).

Expand Down
8 changes: 4 additions & 4 deletions docs/dsh.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@ AgentGuard can be loaded into a DSH profile as a native tool plugin. From an npm

```bash
npm install -g @axorasec/agentguard
agentguard init --agent dsh
agentguard init --agent dsh --profile desktop # DSH Desktop
```

When invoked inside DSH, bare `agentguard init` auto-detects DSH and performs the same installation. Both commands install the packaged native bundle into DSH's default `web` profile. Restart DSH after initialization.
Bare `agentguard init` detects DSH when a profile exists or DSH is managing the shell. It selects the sole installed profile automatically. If multiple profiles exist, choose the one used by your DSH host with `--profile <name>` or `AGENTGUARD_DSH_PROFILE=<name>`; `--profile` wins. Do not assume the desktop app uses `web`. If no profile exists, specify one explicitly. Initialization fails if the DSH CLI is missing from PATH or the selected profile's `package.json` does not confirm the bundle in `dsh.profile.bundles`. Restart the selected profile after initialization. `agentguard status` verifies the saved profile manifest and reports a nonzero exit status if the DSH bundle is missing or the previously selected profile is unknown. An external bootstrap script must pass through the selected profile and must not set `AGENTGUARD_DSH_PROFILE=web` as an implicit default.

The equivalent low-level DSH command is:
The equivalent low-level DSH command (here for `desktop`) is:

```bash
dsh plugin --profile web add --allow-build=@axorasec/agentguard @axorasec/agentguard
dsh plugin --profile desktop add --allow-build=@axorasec/agentguard @axorasec/agentguard
```

The scoped `--allow-build` approval lets pnpm run AgentGuard's reviewed npm
Expand Down
48 changes: 31 additions & 17 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import { formatProtectResult, protectAction, exitCodeForDecision } from './runti
import { approvePendingApproval, listPendingApprovals } from './runtime/approvals.js';
import { getDefaultEffectiveRuntimePolicy, loadCachedPolicy, saveCachedPolicy } from './runtime/policy.js';
import type { RuntimeActionType, RuntimeAgentHost } from './runtime/types.js';
import { installAgentTemplates, type AgentInstaller, type InstallResult } from './installers.js';
import { installAgentTemplates, installedDshProfiles, isDshProfileBundleInstalled, type AgentInstaller, type InstallResult } from './installers.js';
import { packageVersion } from './version.js';
import { runSelfCheckForAdvisory } from './feed/selfcheck.js';
import { discoverDshSelfCheckRoots } from './feed/dsh-discovery.js';
Expand Down Expand Up @@ -92,6 +92,7 @@ async function main() {
.description('Create ~/.agentguard/config.json and local runtime paths')
.option('--level <level>', 'Protection level: strict | balanced | permissive')
.option('--agent <agent>', 'Install integration for auto, claude-code, codex, openclaw, hermes, qclaw, or dsh (default: auto)')
.option('--profile <name>', 'DSH profile (overrides AGENTGUARD_DSH_PROFILE)')
.option('--cloud <url>', 'AgentGuard Cloud URL to store in local config')
.option('--shell-hooks', 'For Hermes: install legacy shell hooks instead of the native plugin')
.option('--force', 'Overwrite existing hook/template files')
Expand All @@ -118,7 +119,7 @@ async function main() {
? 'auto'
: String(options.agent).trim().toLowerCase();
if (normalizedAgent === 'auto') {
const results = initAutoAgents(config, forceTemplates);
const results = initAutoAgents(config, forceTemplates, options.profile);
if (results.detected.length === 0) {
console.log('No supported agent installation found. Looked for DSH and .claude, .openclaw, .hermes, .qclaw, and .codex.');
} else if (results.installed.length === 0) {
Expand All @@ -131,22 +132,28 @@ async function main() {
for (const failure of results.failed) {
console.error(`! Failed to initialize ${failure.agent}: ${failure.error}`);
}
if (results.failed.some((failure) => failure.agent === 'dsh')) process.exitCode = 1;
printPrivacyEnhancementHint(config);
return;
}
if (!SUPPORTED_AGENT_INSTALLERS.includes(normalizedAgent as AgentInstaller)) {
throw new Error('Invalid agent. Use auto, claude-code, codex, openclaw, hermes, qclaw, or dsh.');
}
const agent = normalizedAgent as AgentInstaller;
if (options.profile !== undefined && agent !== 'dsh') {
throw new Error('--profile is only supported with --agent dsh or --agent auto.');
}
const shellHooks = Boolean(options.shellHooks);
const result = installAgentTemplates(agent, {
force: forceTemplates,
shellHooks,
profile: options.profile,
protectedPaths: agent === 'claude-code'
? loadCachedPolicy(config.policyCachePath)?.protectedPaths
: undefined,
});
config.agentHost = agent;
if (agent === 'dsh') config.dshProfile = result.profile;
config.agentHosts = appendAgentHost(config.agentHosts, agent);
saveConfig(config);
printInstallResult(result);
Expand Down Expand Up @@ -276,8 +283,21 @@ async function main() {
console.log(`Protection level: ${config.level}`);
console.log(`Cloud URL: ${config.cloudUrl || 'not configured'}`);
printCloudAuthStatus(config);
console.log(`Agent host: ${config.agentHost || 'not configured'}`);
const hasDsh = config.agentHost === 'dsh' || config.agentHosts?.includes('dsh') === true;
const dshVerified = hasDsh && config.dshProfile
? isDshProfileBundleInstalled(config.dshProfile)
: false;
const hostLabel = config.agentHost === 'dsh' && !dshVerified
? 'dsh (integration not verified)'
: config.agentHost || 'not configured';
console.log(`Agent host: ${hostLabel}`);
console.log(`Agent hosts: ${config.agentHosts?.join(', ') || 'not configured'}`);
if (hasDsh) {
console.log(dshVerified
? `DSH integration: verified in profile ${config.dshProfile}`
: `DSH integration: not verified${config.dshProfile ? ` in profile ${config.dshProfile}` : ' (profile unknown)'}. Run agentguard init --agent dsh --profile <name> to repair.`);
if (!dshVerified) process.exitCode = 1;
}
console.log(`Policy cache: ${statusPath(config.policyCachePath, paths.home)}`);
console.log(`Audit log: ${statusPath(config.auditPath, paths.home)}`);
console.log(`Privacy enhancement: ${describePrivacyMode(config)}`);
Expand Down Expand Up @@ -1225,7 +1245,7 @@ function validateCronTarget(value: unknown): CronBackend {
throw new Error('Invalid cron target. Use auto, openclaw, qclaw, hermes, system, or windows.');
}

function initAutoAgents(config: AgentGuardConfig, force: boolean): {
function initAutoAgents(config: AgentGuardConfig, force: boolean, profile?: string): {
installed: InstallResult[];
failed: Array<{ agent: AgentInstaller; error: string }>;
detected: AgentInstaller[];
Expand All @@ -1236,7 +1256,9 @@ function initAutoAgents(config: AgentGuardConfig, force: boolean): {
.filter(({ dir }) => existsSync(join(process.cwd(), dir)))
.map(({ agent }) => agent);
const isDshManagedShell = detectDshManagedShell();
const dshAgents: AgentInstaller[] = isDshManagedShell || detectInstalledDshWebProfile() ? ['dsh'] : [];
const dshDetected = isDshManagedShell || installedDshProfiles().length > 0
|| process.env.AGENTGUARD_DSH_PROFILE !== undefined || profile !== undefined;
const dshAgents: AgentInstaller[] = dshDetected ? ['dsh'] : [];
const detectedAgents: AgentInstaller[] = isDshManagedShell
? [...dshAgents, ...directoryAgents]
: [...directoryAgents, ...dshAgents];
Expand All @@ -1246,6 +1268,7 @@ function initAutoAgents(config: AgentGuardConfig, force: boolean): {
installed.push(installAgentTemplates(agent, {
cwd: process.cwd(),
force,
profile,
protectedPaths: agent === 'claude-code'
? loadCachedPolicy(config.policyCachePath)?.protectedPaths
: undefined,
Expand All @@ -1260,6 +1283,8 @@ function initAutoAgents(config: AgentGuardConfig, force: boolean): {

if (installed.length > 0) {
config.agentHosts = installed.map((result) => result.agent);
const installedDsh = installed.find((result) => result.agent === 'dsh');
if (installedDsh) config.dshProfile = installedDsh.profile;
config.agentHost = installed[0].agent;
saveConfig(config);
}
Expand All @@ -1269,7 +1294,7 @@ function initAutoAgents(config: AgentGuardConfig, force: boolean): {

function printInstallResult(result: InstallResult): void {
if (result.agent === 'dsh') {
console.log('Installed dsh integration in profile web.');
for (const message of result.messages || []) console.log(message);
console.log('Restart DSH to activate AgentGuard in that profile.');
return;
}
Expand Down Expand Up @@ -2792,17 +2817,6 @@ function detectDshManagedShell(): boolean {
return process.env.DSH_SHELL === '1';
}

function detectInstalledDshWebProfile(): boolean {
const configuredHome = process.env.DSH_HOME?.trim();
const dshHome = configuredHome
? configuredHome === '~'
? homedir()
: /^~[\\/]/.test(configuredHome)
? join(homedir(), configuredHome.slice(2))
: resolve(configuredHome)
: join(homedir(), '.dsh');
return existsSync(join(dshHome, 'profiles', 'web', 'package.json'));
}

function withDetectedAgentHost(config: AgentGuardConfig, agentHost: AgentGuardAgentHost): AgentGuardConfig {
const next: AgentGuardConfig = {
Expand Down
4 changes: 4 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ export interface AgentGuardConfig {
level: 'strict' | 'balanced' | 'permissive';
agentHost?: AgentGuardAgentHost;
agentHosts?: AgentGuardAgentHost[];
/** Profile where the DSH bundle was last verified during init. */
dshProfile?: string;
cloudUrl?: string;
apiKey?: string;
agentId?: string;
Expand Down Expand Up @@ -113,6 +115,8 @@ export function loadConfig(): AgentGuardConfig {
level: normalizeLevel(parsed.level) ?? fallback.level,
agentHost: normalizeAgentHost(parsed.agentHost),
agentHosts: normalizeAgentHosts(parsed.agentHosts),
dshProfile: typeof parsed.dshProfile === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(parsed.dshProfile)
? parsed.dshProfile : undefined,
cloudUrl: parsed.cloudUrl || fallback.cloudUrl,
policyCachePath: parsed.policyCachePath || fallback.policyCachePath,
auditPath: parsed.auditPath || fallback.auditPath,
Expand Down
71 changes: 65 additions & 6 deletions src/installers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ export type AgentInstaller = 'claude-code' | 'codex' | 'openclaw' | 'hermes' | '
export interface InstallResult {
agent: AgentInstaller;
files: string[];
/** The DSH profile that was installed and verified, if applicable. */
profile?: string;
messages?: string[];
}

Expand All @@ -20,6 +22,8 @@ export function installAgentTemplates(agent: AgentInstaller, options: {
cwd?: string;
force?: boolean;
shellHooks?: boolean;
/** DSH profile selected by --profile (takes precedence over AGENTGUARD_DSH_PROFILE). */
profile?: string;
/** Exact paths explicitly selected for Claude Code @file Read deny compensation. */
protectedPaths?: string[];
} = {}): InstallResult {
Expand All @@ -29,14 +33,53 @@ export function installAgentTemplates(agent: AgentInstaller, options: {
if (agent === 'openclaw') return installOpenClaw(options.cwd, Boolean(options.force));
if (agent === 'hermes') return installHermes(options.cwd, Boolean(options.force), { shellHooks: Boolean(options.shellHooks) });
if (agent === 'qclaw') return installQClaw(root, Boolean(options.force));
if (agent === 'dsh') return installDsh(root);
if (agent === 'dsh') return installDsh(root, options.profile);
throw new Error(`Unsupported agent installer: ${agent}`);
}

function installDsh(root: string): InstallResult {
const DSH_BUNDLE = '@axorasec/agentguard';

export function dshProfilesRoot(): string {
const configuredHome = process.env.DSH_HOME?.trim();
const home = !configuredHome
? join(homedir(), '.dsh')
: configuredHome === '~'
? homedir()
: /^~[\\/]/.test(configuredHome)
? join(homedir(), configuredHome.slice(2))
: resolve(configuredHome);
return join(home, 'profiles');
}

export function installedDshProfiles(): string[] {
const profilesRoot = dshProfilesRoot();
if (!existsSync(profilesRoot)) return [];
return readdirSync(profilesRoot, { withFileTypes: true })
.filter((entry) => entry.isDirectory() && existsSync(join(profilesRoot, entry.name, 'package.json')))
.map((entry) => entry.name).sort();
}

function resolveDshProfile(explicit?: string): string {
const selected = explicit ?? process.env.AGENTGUARD_DSH_PROFILE;
if (selected !== undefined) {
// A profile is a single directory name, never a path or option to pass to dsh.
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(selected)) {
throw new Error('Invalid DSH profile name. Use a single profile name (letters, numbers, _ or -).');
}
return selected;
}
const profiles = installedDshProfiles();
if (profiles.length === 1) return profiles[0];
throw new Error(profiles.length
? `Multiple DSH profiles found (${profiles.join(', ')}). Choose one with --profile <name> or AGENTGUARD_DSH_PROFILE.`
: 'No DSH profile found. Choose one with --profile <name> or AGENTGUARD_DSH_PROFILE.');
}

function installDsh(root: string, selectedProfile?: string): InstallResult {
const profile = resolveDshProfile(selectedProfile);
const args = [
'plugin', '--profile', 'web', 'add',
'--allow-build=@axorasec/agentguard', '@axorasec/agentguard',
'plugin', '--profile', profile, 'add',
`--allow-build=${DSH_BUNDLE}`, DSH_BUNDLE,
];
const result = spawnSync('dsh', args, {
cwd: root,
Expand All @@ -46,14 +89,30 @@ function installDsh(root: string): InstallResult {
if (result.error) {
const code = (result.error as NodeJS.ErrnoException).code;
if (code === 'ENOENT') {
throw new Error('DSH CLI was not found on PATH. Install or run DSH before initializing AgentGuard for DSH.');
throw new Error(`DSH CLI was not found on PATH. If DSH Desktop is installed, link its CLI to PATH, then rerun agentguard init --agent dsh --profile ${profile}.`);
}
throw result.error;
}
if (result.status !== 0) {
throw new Error(`DSH plugin installation failed with exit code ${result.status ?? 1}.`);
}
return { agent: 'dsh', files: [] };
const manifestPath = join(dshProfilesRoot(), profile, 'package.json');
if (!isDshProfileBundleInstalled(profile)) {
throw new Error(`DSH reported success but ${manifestPath} does not list ${DSH_BUNDLE} in dsh.profile.bundles. Retry: dsh plugin --profile ${profile} add --allow-build=${DSH_BUNDLE} ${DSH_BUNDLE}`);
}
return { agent: 'dsh', files: [], profile, messages: [`Installed dsh integration in profile ${profile}.`] };
}

/** Check the selected profile's manifest, not the mere success of the dsh command. */
export function isDshProfileBundleInstalled(profile: string): boolean {
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(profile)) return false;
try {
const manifestPath = join(dshProfilesRoot(), profile, 'package.json');
const pkg = JSON.parse(readFileSync(manifestPath, 'utf8')) as { dsh?: { profile?: { bundles?: unknown } } };
return Array.isArray(pkg.dsh?.profile?.bundles) && pkg.dsh.profile.bundles.includes(DSH_BUNDLE);
} catch {
return false;
}
}

function installClaudeCode(root: string, force: boolean, protectedPaths: string[]): InstallResult {
Expand Down
Loading
Loading