diff --git a/README.md b/README.md index 27885ec..3521a3e 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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 @@ -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). diff --git a/docs/dsh.md b/docs/dsh.md index 90bc800..21cbd99 100644 --- a/docs/dsh.md +++ b/docs/dsh.md @@ -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 ` or `AGENTGUARD_DSH_PROFILE=`; `--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 diff --git a/src/cli.ts b/src/cli.ts index 1fd7c18..c68a3c2 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -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'; @@ -92,6 +92,7 @@ async function main() { .description('Create ~/.agentguard/config.json and local runtime paths') .option('--level ', 'Protection level: strict | balanced | permissive') .option('--agent ', 'Install integration for auto, claude-code, codex, openclaw, hermes, qclaw, or dsh (default: auto)') + .option('--profile ', 'DSH profile (overrides AGENTGUARD_DSH_PROFILE)') .option('--cloud ', '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') @@ -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) { @@ -131,6 +132,7 @@ 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; } @@ -138,15 +140,20 @@ async function main() { 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); @@ -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 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)}`); @@ -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[]; @@ -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]; @@ -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, @@ -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); } @@ -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; } @@ -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 = { diff --git a/src/config.ts b/src/config.ts index f0799b3..0dd186c 100644 --- a/src/config.ts +++ b/src/config.ts @@ -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; @@ -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, diff --git a/src/installers.ts b/src/installers.ts index 9a2ad92..a2c7e71 100644 --- a/src/installers.ts +++ b/src/installers.ts @@ -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[]; } @@ -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 { @@ -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 or AGENTGUARD_DSH_PROFILE.` + : 'No DSH profile found. Choose one with --profile 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, @@ -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 { diff --git a/src/tests/cli-init.test.ts b/src/tests/cli-init.test.ts index 0dae10c..3ffe97f 100644 --- a/src/tests/cli-init.test.ts +++ b/src/tests/cli-init.test.ts @@ -15,7 +15,15 @@ describe('init CLI', () => { writeFileSync(dsh, [ '#!/usr/bin/env node', 'const fs = require("node:fs");', - 'fs.writeFileSync(process.env.DSH_CALL_LOG, JSON.stringify(process.argv.slice(2)));', + 'const path = require("node:path");', + 'const args = process.argv.slice(2);', + 'fs.writeFileSync(process.env.DSH_CALL_LOG, JSON.stringify(args));', + 'if (!process.env.DSH_FAKE_NO_MANIFEST) {', + ' const home = process.env.DSH_HOME.startsWith("~/") ? path.join(process.env.HOME, process.env.DSH_HOME.slice(2)) : process.env.DSH_HOME;', + ' const manifest = path.join(home, "profiles", args[2], "package.json");', + ' fs.mkdirSync(path.dirname(manifest), { recursive: true });', + ' fs.writeFileSync(manifest, JSON.stringify({ dsh: { profile: { bundles: ["@axorasec/agentguard"] } } }));', + '}', 'process.stdout.write("profile bundle installed\\n");', `process.exit(${exitCode});`, '', @@ -209,12 +217,13 @@ describe('init CLI', () => { const cliPath = resolve('dist', 'cli.js'); installFakeDsh(bin, callLog); - const { stdout } = await execFileAsync(process.execPath, [cliPath, 'init', '--agent', 'dsh'], { + const { stdout } = await execFileAsync(process.execPath, [cliPath, 'init', '--agent', 'dsh', '--profile', 'web'], { cwd, env: { ...process.env, AGENTGUARD_HOME: home, DSH_CALL_LOG: callLog, + DSH_HOME: join(home, 'dsh'), PATH: `${bin}:${process.env.PATH || ''}`, }, }); @@ -222,9 +231,11 @@ describe('init CLI', () => { const config = JSON.parse(readFileSync(join(home, 'config.json'), 'utf8')) as { agentHost?: string; agentHosts?: string[]; + dshProfile?: string; }; assert.equal(config.agentHost, 'dsh'); assert.deepEqual(config.agentHosts, ['dsh']); + assert.equal(config.dshProfile, 'web'); assert.deepEqual(JSON.parse(readFileSync(callLog, 'utf8')), [ 'plugin', '--profile', 'web', 'add', '--allow-build=@axorasec/agentguard', '@axorasec/agentguard', @@ -233,6 +244,164 @@ describe('init CLI', () => { assert.match(stdout, /Restart DSH/); }); + it('selects the only installed desktop profile without creating web', async () => { + const home = mkdtempSync(join(tmpdir(), 'agentguard-init-desktop-')); + const cwd = mkdtempSync(join(tmpdir(), 'agentguard-init-desktop-cwd-')); + const dshHome = join(home, 'dsh'); + const bin = join(cwd, 'bin'); + const callLog = join(cwd, 'dsh-call.json'); + const cliPath = resolve('dist', 'cli.js'); + mkdirSync(join(dshHome, 'profiles', 'desktop'), { recursive: true }); + writeFileSync(join(dshHome, 'profiles', 'desktop', 'package.json'), '{}'); + installFakeDsh(bin, callLog); + + const { stdout } = await execFileAsync(process.execPath, [cliPath, 'init'], { + cwd, + env: { ...process.env, AGENTGUARD_HOME: home, DSH_HOME: dshHome, DSH_CALL_LOG: callLog, AGENTGUARD_DSH_PROFILE: undefined, + PATH: `${bin}:${process.env.PATH || ''}` }, + }); + assert.match(stdout, /Installed dsh integration in profile desktop/); + assert.equal(JSON.parse(readFileSync(callLog, 'utf8'))[2], 'desktop'); + assert.equal(existsSync(join(dshHome, 'profiles', 'web')), false); + }); + + it('rejects ambiguous profiles instead of silently installing to web', async () => { + const home = mkdtempSync(join(tmpdir(), 'agentguard-init-ambiguous-')); + const cwd = mkdtempSync(join(tmpdir(), 'agentguard-init-ambiguous-cwd-')); + const dshHome = join(home, 'dsh'); + const cliPath = resolve('dist', 'cli.js'); + for (const name of ['web', 'desktop']) { + mkdirSync(join(dshHome, 'profiles', name), { recursive: true }); + writeFileSync(join(dshHome, 'profiles', name, 'package.json'), '{}'); + } + await assert.rejects(execFileAsync(process.execPath, [cliPath, 'init', '--agent', 'dsh'], { + cwd, env: { ...process.env, AGENTGUARD_HOME: home, DSH_HOME: dshHome, AGENTGUARD_DSH_PROFILE: '' }, + }), /Invalid DSH profile name/); + await assert.rejects(execFileAsync(process.execPath, [cliPath, 'init', '--agent', 'dsh'], { + cwd, env: { ...process.env, AGENTGUARD_HOME: home, DSH_HOME: dshHome, AGENTGUARD_DSH_PROFILE: undefined }, + }), /Multiple DSH profiles found \(desktop, web\)/); + const config = JSON.parse(readFileSync(join(home, 'config.json'), 'utf8')) as { agentHost?: string }; + assert.equal(config.agentHost, undefined); + }); + + it('uses AGENTGUARD_DSH_PROFILE to select desktop among multiple profiles', async () => { + const home = mkdtempSync(join(tmpdir(), 'agentguard-init-env-profile-')); + const cwd = mkdtempSync(join(tmpdir(), 'agentguard-init-env-profile-cwd-')); + const dshHome = join(home, 'dsh'); + const bin = join(cwd, 'bin'); + const callLog = join(cwd, 'dsh-call.json'); + for (const name of ['desktop', 'web']) { + mkdirSync(join(dshHome, 'profiles', name), { recursive: true }); + writeFileSync(join(dshHome, 'profiles', name, 'package.json'), '{}'); + } + installFakeDsh(bin, callLog); + const { stdout } = await execFileAsync(process.execPath, [resolve('dist', 'cli.js'), 'init'], { + cwd, env: { ...process.env, AGENTGUARD_HOME: home, DSH_HOME: dshHome, DSH_CALL_LOG: callLog, + AGENTGUARD_DSH_PROFILE: 'desktop', PATH: `${bin}:${process.env.PATH || ''}` }, + }); + assert.match(stdout, /profile desktop/); + assert.equal(JSON.parse(readFileSync(callLog, 'utf8'))[2], 'desktop'); + assert.equal(readFileSync(join(dshHome, 'profiles', 'web', 'package.json'), 'utf8'), '{}'); + }); + + it('returns nonzero in auto mode if multiple DSH profiles are ambiguous', async () => { + const home = mkdtempSync(join(tmpdir(), 'agentguard-init-auto-ambiguous-')); + const cwd = mkdtempSync(join(tmpdir(), 'agentguard-init-auto-ambiguous-cwd-')); + const dshHome = join(home, 'dsh'); + for (const name of ['desktop', 'web']) { + mkdirSync(join(dshHome, 'profiles', name), { recursive: true }); + writeFileSync(join(dshHome, 'profiles', name, 'package.json'), '{}'); + } + await assert.rejects(execFileAsync(process.execPath, [resolve('dist', 'cli.js'), 'init'], { + cwd, env: { ...process.env, AGENTGUARD_HOME: home, DSH_HOME: dshHome, AGENTGUARD_DSH_PROFILE: undefined }, + }), /Multiple DSH profiles found/); + }); + + it('prefers --profile over AGENTGUARD_DSH_PROFILE for desktop', async () => { + const home = mkdtempSync(join(tmpdir(), 'agentguard-init-profile-')); + const cwd = mkdtempSync(join(tmpdir(), 'agentguard-init-profile-cwd-')); + const dshHome = join(home, 'dsh'); + const bin = join(cwd, 'bin'); + const callLog = join(cwd, 'dsh-call.json'); + installFakeDsh(bin, callLog); + const { stdout } = await execFileAsync(process.execPath, [resolve('dist', 'cli.js'), 'init', '--agent', 'dsh', '--profile', 'desktop'], { + cwd, env: { ...process.env, AGENTGUARD_HOME: home, DSH_HOME: dshHome, DSH_CALL_LOG: callLog, + AGENTGUARD_DSH_PROFILE: 'web', PATH: `${bin}:${process.env.PATH || ''}` }, + }); + assert.match(stdout, /profile desktop/); + assert.equal(JSON.parse(readFileSync(callLog, 'utf8'))[2], 'desktop'); + }); + + it('fails if DSH reports success without installing the selected bundle', async () => { + const home = mkdtempSync(join(tmpdir(), 'agentguard-init-unverified-')); + const cwd = mkdtempSync(join(tmpdir(), 'agentguard-init-unverified-cwd-')); + const dshHome = join(home, 'dsh'); + const bin = join(cwd, 'bin'); + const callLog = join(cwd, 'dsh-call.json'); + installFakeDsh(bin, callLog); + await assert.rejects(execFileAsync(process.execPath, [resolve('dist', 'cli.js'), 'init', '--agent', 'dsh', '--profile', 'desktop'], { + cwd, env: { ...process.env, AGENTGUARD_HOME: home, DSH_HOME: dshHome, DSH_CALL_LOG: callLog, + DSH_FAKE_NO_MANIFEST: '1', PATH: `${bin}:${process.env.PATH || ''}` }, + }), /does not list @axorasec\/agentguard/); + const config = JSON.parse(readFileSync(join(home, 'config.json'), 'utf8')) as { agentHost?: string }; + assert.equal(config.agentHost, undefined); + }); + + it('reports missing DSH CLI as a failure in auto mode when desktop is installed', async () => { + const home = mkdtempSync(join(tmpdir(), 'agentguard-init-no-cli-')); + const cwd = mkdtempSync(join(tmpdir(), 'agentguard-init-no-cli-cwd-')); + const dshHome = join(home, 'dsh'); + mkdirSync(join(dshHome, 'profiles', 'desktop'), { recursive: true }); + writeFileSync(join(dshHome, 'profiles', 'desktop', 'package.json'), '{}'); + await assert.rejects(execFileAsync(process.execPath, [resolve('dist', 'cli.js'), 'init'], { + cwd, env: { ...process.env, AGENTGUARD_HOME: home, DSH_HOME: dshHome, + PATH: '/usr/bin:/bin', AGENTGUARD_DSH_PROFILE: undefined }, + }), /DSH CLI was not found on PATH/); + }); + + it('reports a previously configured DSH host as unverified after its bundle disappears and reinit fails', async () => { + const home = mkdtempSync(join(tmpdir(), 'agentguard-init-dsh-stale-home-')); + const cwd = mkdtempSync(join(tmpdir(), 'agentguard-init-dsh-stale-cwd-')); + const dshHome = join(home, 'dsh'); + const bin = join(cwd, 'bin'); + const callLog = join(cwd, 'dsh-call.json'); + const cliPath = resolve('dist', 'cli.js'); + installFakeDsh(bin, callLog); + const env = { ...process.env, AGENTGUARD_HOME: home, DSH_HOME: dshHome, DSH_CALL_LOG: callLog, + PATH: `${bin}:${process.env.PATH || ''}` }; + await execFileAsync(process.execPath, [cliPath, 'init', '--agent', 'dsh', '--profile', 'desktop'], { cwd, env }); + const { stdout: healthyStatus } = await execFileAsync(process.execPath, [cliPath, 'status'], { cwd, env }); + assert.match(healthyStatus, /DSH integration: verified in profile desktop/); + assert.match(healthyStatus, /Agent host: dsh\n/); + + writeFileSync(join(dshHome, 'profiles', 'desktop', 'package.json'), '{}'); + await assert.rejects(execFileAsync(process.execPath, [cliPath, 'init', '--agent', 'dsh', '--profile', 'desktop'], { + cwd, env: { ...env, DSH_FAKE_NO_MANIFEST: '1' }, + }), /does not list @axorasec\/agentguard/); + const config = JSON.parse(readFileSync(join(home, 'config.json'), 'utf8')) as { agentHost?: string; dshProfile?: string }; + assert.equal(config.agentHost, 'dsh'); + assert.equal(config.dshProfile, 'desktop'); + await assert.rejects(execFileAsync(process.execPath, [cliPath, 'status'], { cwd, env }), (error: Error & { stdout?: string; code?: number }) => { + assert.equal(error.code, 1); + assert.match(error.stdout ?? '', /Agent host: dsh \(integration not verified\)/); + assert.match(error.stdout ?? '', /DSH integration: not verified in profile desktop/); + return true; + }); + }); + + it('does not present legacy DSH configuration without a recorded profile as verified', async () => { + const home = mkdtempSync(join(tmpdir(), 'agentguard-init-dsh-legacy-home-')); + const cliPath = resolve('dist', 'cli.js'); + writeFileSync(join(home, 'config.json'), JSON.stringify({ agentHost: 'dsh', agentHosts: ['dsh'] })); + await assert.rejects(execFileAsync(process.execPath, [cliPath, 'status'], { + env: { ...process.env, AGENTGUARD_HOME: home, DSH_HOME: join(home, 'dsh') }, + }), (error: Error & { stdout?: string; code?: number }) => { + assert.equal(error.code, 1); + assert.match(error.stdout ?? '', /DSH integration: not verified \(profile unknown\)/); + return true; + }); + }); + it('does not persist DSH as initialized when native bundle installation fails', async () => { const home = mkdtempSync(join(tmpdir(), 'agentguard-init-dsh-failure-home-')); const cwd = mkdtempSync(join(tmpdir(), 'agentguard-init-dsh-failure-cwd-')); @@ -242,12 +411,13 @@ describe('init CLI', () => { installFakeDsh(bin, callLog, 17); await assert.rejects( - execFileAsync(process.execPath, [cliPath, 'init', '--agent', 'dsh'], { + execFileAsync(process.execPath, [cliPath, 'init', '--agent', 'dsh', '--profile', 'web'], { cwd, env: { ...process.env, AGENTGUARD_HOME: home, DSH_CALL_LOG: callLog, + DSH_HOME: join(home, 'dsh'), PATH: `${bin}:${process.env.PATH || ''}`, }, }), @@ -422,7 +592,9 @@ describe('init CLI', () => { ...process.env, AGENTGUARD_HOME: home, DSH_CALL_LOG: callLog, + DSH_HOME: join(home, 'dsh'), DSH_SHELL: '1', + AGENTGUARD_DSH_PROFILE: 'web', PATH: `${bin}:${process.env.PATH || ''}`, }, }); @@ -454,7 +626,9 @@ describe('init CLI', () => { ...process.env, AGENTGUARD_HOME: home, DSH_CALL_LOG: callLog, + DSH_HOME: join(home, 'dsh'), DSH_SHELL: '1', + AGENTGUARD_DSH_PROFILE: 'web', PATH: `${bin}:${process.env.PATH || ''}`, }, }); @@ -528,9 +702,11 @@ describe('init CLI', () => { const config = JSON.parse(readFileSync(join(home, 'config.json'), 'utf8')) as { agentHost?: string; agentHosts?: string[]; + dshProfile?: string; }; assert.equal(config.agentHost, 'openclaw'); assert.deepEqual(config.agentHosts, ['openclaw', 'dsh']); + assert.equal(config.dshProfile, 'web'); }); it('does not fail auto init when no supported agent directory exists', async () => {