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
17 changes: 17 additions & 0 deletions .github/workflows/build-and-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,23 @@ jobs:
if-no-files-found: error
include-hidden-files: true

windows-subprocess-test:
name: windows-subprocess-test (20.x)
runs-on: >-
${{ fromJSON(format('["codebuild-agentcore-e2e-{0}-{1}","image:windows-1.0","e2e-windows"]', github.run_id,
github.run_attempt)) }}
timeout-minutes: 10
steps:
- uses: actions/checkout@v7
- name: Use Node.js 20.x
uses: actions/setup-node@v7
with:
node-version: 20.x
cache: 'npm'
- run: npm ci
- name: Run Windows subprocess tests
run: npx vitest run --project unit src/lib/utils/__tests__/subprocess-windows-real.test.ts

merge-reports:
needs: unit-test
runs-on: codebuild-agentcore-e2e-${{ github.run_id }}-${{ github.run_attempt }}
Expand Down
18 changes: 18 additions & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,24 @@ export default tseslint.config(
},
},
prettier,
// Spawn only through src/lib/utils/subprocess.ts so bare command lookup stays consistent
// across platforms and uses explicit PATH entries on Windows.
{
files: ['src/**/*.{ts,tsx}'],
ignores: ['src/lib/utils/subprocess.ts', 'src/assets/**', '**/*.test.ts', '**/*.test.tsx', '**/test-utils/**'],
rules: {
'@typescript-eslint/no-restricted-imports': [
'error',
{
paths: ['child_process', 'node:child_process', 'cross-spawn'].map(name => ({
name,
allowTypeImports: true,
message: 'Use spawn/spawnSync or the run*/check* helpers from src/lib/utils/subprocess.ts.',
})),
},
],
},
},
// Relaxed rules for test files
{
files: ['**/*.test.ts', '**/*.test.tsx', '**/test-utils/**', 'integ-tests/**', 'browser-tests/**'],
Expand Down
11 changes: 3 additions & 8 deletions src/cli/cdk/toolkit-lib/wrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,6 @@ async function withErrorContext<T>(context: string, operation: () => Promise<T>)
}
}

/**
* Command to execute the CDK app.
* Matches the "app" command in cdk.json.
* Requires the CDK project to be built first (tsc).
*/
const CDK_APP_COMMAND = 'node';

/**
* Thin wrapper around @aws-cdk/toolkit-lib for AgentCore CLI.
*
Expand Down Expand Up @@ -85,7 +78,9 @@ export class CdkToolkitWrapper {
* Points to the compiled JS file in dist/ (requires tsc build first).
*/
getCdkAppCommand(): string {
return `${CDK_APP_COMMAND} ${CDK_APP_ENTRY}`;
// The toolkit runs this command through a shell in the project directory. Use the
// absolute path of the Node binary running the CLI for consistent Windows lookup.
return `"${process.execPath}" ${CDK_APP_ENTRY}`;
}

/**
Expand Down
5 changes: 5 additions & 0 deletions src/cli/cli.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { getOrCreateInstallationId } from '../lib/schemas/io/global-config';
import { disableCwdExecutableSearch } from '../lib/utils/subprocess';
import { registerAdd } from './commands/add';
import { registerAddSkill } from './commands/add/skill-command';
import { registerAddTool } from './commands/add/tool-command';
Expand Down Expand Up @@ -139,6 +140,10 @@ export function registerCommands(program: Command) {
}

export const main = async (argv: string[]) => {
// Keep Windows executable lookup on explicit PATH entries, including for child processes
// spawned by third-party libraries.
disableCwdExecutableSearch();

// Register global cleanup handlers once at startup
setupAltScreenCleanup();

Expand Down
2 changes: 1 addition & 1 deletion src/cli/commands/dev/command.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
getWorkingDirectory,
} from '../../../lib';
import { failureResult } from '../../../lib/result.js';
import { spawn } from '../../../lib/utils/subprocess';
import { COMMAND_DESCRIPTIONS } from '../../constants';
import { getErrorMessage } from '../../errors';
import { detectContainerRuntime } from '../../external-requirements';
Expand Down Expand Up @@ -38,7 +39,6 @@ import { runCliDeploy } from '../deploy/progress';
import { parseHeaderFlags } from '../shared/header-utils';
import { launchTuiDevScreenWithPicker, runBrowserMode } from './browser-mode';
import type { Command } from '@commander-js/extra-typings';
import { spawn } from 'child_process';
import { render } from 'ink';
import path from 'node:path';
import React from 'react';
Expand Down
4 changes: 2 additions & 2 deletions src/cli/commands/export/__tests__/container-export.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

vi.mock('node:child_process', async importOriginal => ({
vi.mock('../../../../lib/utils/subprocess', async importOriginal => ({
...(await importOriginal<Record<string, unknown>>()),
execSync: vi.fn(),
runSubprocessCaptureSync: vi.fn(() => ({ stdout: '', stderr: '', code: 0, signal: null })),
}));

describe('exported container Dockerfiles', () => {
Expand Down
6 changes: 2 additions & 4 deletions src/cli/commands/export/harness-action.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { AgentAlreadyExistsError, ConfigIO, setEnvVar } from '../../../lib';
import { ExportHarnessError, ValidationError } from '../../../lib/errors/types';
import { runSubprocessCaptureSync } from '../../../lib/utils/subprocess';
import { AgentNameSchema } from '../../../schema';
import type { AgentEnvSpec, BuildType, Credential, HarnessSpec } from '../../../schema';
import { getErrorMessage } from '../../errors';
Expand All @@ -23,7 +24,6 @@ import { fetchHarnessSpecByArn } from './fetch-harness-spec';
import { isPathSkill, mapHarnessToExportConfig } from './harness-mapper';
import { resolveHarnessContext } from './harness-resolver';
import type { ExportHarnessOptions, ExportNote, ResolvedHarnessContext } from './types';
import { execSync } from 'node:child_process';
import { copyFileSync, cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { basename, isAbsolute, join, resolve, sep } from 'node:path';

Expand Down Expand Up @@ -208,9 +208,7 @@ export async function handleExportHarness(
// 5b. Generate uv.lock for Container builds (required by the Dockerfile's uv sync step)
if (renderConfig.buildType === 'Container') {
log('Generating uv.lock for container build');
try {
execSync('uv lock', { cwd: agentDir, stdio: 'pipe' });
} catch {
if (runSubprocessCaptureSync('uv', ['lock'], { cwd: agentDir }).code !== 0) {
// uv not installed or failed — add a note and continue; user can run manually
context.exportNotes.push({
category: 'uv.lock missing — run `uv lock` before deploying',
Expand Down
22 changes: 11 additions & 11 deletions src/cli/commands/update/__tests__/update-action.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { compareVersions, fetchLatestVersion, handleUpdate } from '../action.js';
import { afterEach, describe, expect, it, vi } from 'vitest';

const { mockExecSync } = vi.hoisted(() => ({
mockExecSync: vi.fn(),
const { mockRunSubprocess } = vi.hoisted(() => ({
mockRunSubprocess: vi.fn(),
}));

vi.mock('child_process', () => ({
execSync: mockExecSync,
vi.mock('../../../../lib/utils/subprocess', () => ({
runSubprocess: mockRunSubprocess,
}));

vi.mock('../../../constants.js', () => ({
Expand Down Expand Up @@ -104,7 +104,7 @@ describe('fetchLatestVersion', () => {
describe('handleUpdate', () => {
afterEach(() => {
vi.restoreAllMocks();
mockExecSync.mockReset();
mockRunSubprocess.mockReset();
});

it('returns up-to-date when versions match', async () => {
Expand Down Expand Up @@ -140,30 +140,30 @@ describe('handleUpdate', () => {
const result = await handleUpdate(true);

expect(result.status).toBe('update-available');
expect(mockExecSync).not.toHaveBeenCalled();
expect(mockRunSubprocess).not.toHaveBeenCalled();
});

it('returns updated after successful install', async () => {
vi.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
json: () => Promise.resolve({ version: '2.0.0' }),
} as Response);
mockExecSync.mockReturnValue(undefined);
mockRunSubprocess.mockResolvedValue(undefined);

const result = await handleUpdate(false);

expect(result.status).toBe('updated');
expect(mockExecSync).toHaveBeenCalledWith('npm install -g @aws/agentcore@latest', { stdio: 'inherit' });
expect(mockRunSubprocess).toHaveBeenCalledWith('npm', ['install', '-g', '@aws/agentcore@latest'], {
stdio: 'inherit',
});
});

it('returns update-failed when install throws', async () => {
vi.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
json: () => Promise.resolve({ version: '2.0.0' }),
} as Response);
mockExecSync.mockImplementation(() => {
throw new Error('install failed');
});
mockRunSubprocess.mockRejectedValue(new Error('install failed'));

const result = await handleUpdate(false);

Expand Down
5 changes: 3 additions & 2 deletions src/cli/commands/update/action.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { runSubprocess } from '../../../lib/utils/subprocess';
import { PACKAGE_VERSION, getDistroConfig } from '../../constants';
import { execSync } from 'child_process';

const distroConfig = getDistroConfig();

Expand Down Expand Up @@ -88,7 +88,8 @@ export async function handleUpdate(checkOnly: boolean): Promise<UpdateResult> {
}

try {
execSync(distroConfig.installCommand, { stdio: 'inherit' });
const [installBinary, ...installArgs] = distroConfig.installCommand.trim().split(/\s+/);
await runSubprocess(installBinary!, installArgs, { stdio: 'inherit' });
return { status: 'updated', currentVersion: PACKAGE_VERSION, latestVersion };
} catch {
return { status: 'update-failed', currentVersion: PACKAGE_VERSION, latestVersion };
Expand Down
31 changes: 13 additions & 18 deletions src/cli/external-requirements/__tests__/detect.test.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,22 @@
import { detectContainerRuntime, requireContainerRuntime } from '../detect.js';
import { afterEach, describe, expect, it, vi } from 'vitest';

const { mockCheckSubprocess, mockRunSubprocessCapture } = vi.hoisted(() => ({
mockCheckSubprocess: vi.fn(),
const { mockResolveExecutable, mockRunSubprocessCapture } = vi.hoisted(() => ({
mockResolveExecutable: vi.fn(),
mockRunSubprocessCapture: vi.fn(),
}));

vi.mock('../../../lib', () => ({
CONTAINER_RUNTIMES: ['docker', 'podman', 'finch'],
checkSubprocess: mockCheckSubprocess,
resolveExecutable: mockResolveExecutable,
runSubprocessCapture: mockRunSubprocessCapture,
isWindows: false,
}));

afterEach(() => vi.clearAllMocks());

describe('detectContainerRuntime', () => {
it('returns docker when docker is installed', async () => {
mockCheckSubprocess.mockResolvedValue(true);
mockResolveExecutable.mockImplementation((bin: string) => `/usr/bin/${bin}`);
mockRunSubprocessCapture.mockImplementation((_bin: string, args: string[]) => {
if (args[0] === '--version') return Promise.resolve({ code: 0, stdout: 'Docker version 24.0.0\n', stderr: '' });
if (args[0] === 'build') return Promise.resolve({ code: 0, stdout: '', stderr: '' });
Expand All @@ -29,11 +28,7 @@ describe('detectContainerRuntime', () => {
});

it('falls back to podman when docker not installed', async () => {
mockCheckSubprocess.mockImplementation((_cmd: string, args: string[]) => {
if (args[0] === 'docker') return Promise.resolve(false);
if (args[0] === 'podman') return Promise.resolve(true);
return Promise.resolve(false);
});
mockResolveExecutable.mockImplementation((bin: string) => (bin === 'podman' ? '/usr/bin/podman' : null));
mockRunSubprocessCapture.mockImplementation((bin: string, args: string[]) => {
if (bin === 'podman' && args[0] === '--version')
return Promise.resolve({ code: 0, stdout: 'podman version 4.5.0\n', stderr: '' });
Expand All @@ -46,14 +41,14 @@ describe('detectContainerRuntime', () => {
});

it('returns null runtime when nothing is installed', async () => {
mockCheckSubprocess.mockResolvedValue(false);
mockResolveExecutable.mockReturnValue(null);

const result = await detectContainerRuntime();
expect(result.runtime).toBeNull();
});

it('skips runtime when --version check fails', async () => {
mockCheckSubprocess.mockResolvedValue(true);
mockResolveExecutable.mockImplementation((bin: string) => `/usr/bin/${bin}`);
mockRunSubprocessCapture.mockImplementation((bin: string, args: string[]) => {
// docker --version fails, podman works
if (bin === 'docker' && args[0] === '--version') return Promise.resolve({ code: 1, stdout: '', stderr: 'error' });
Expand All @@ -70,7 +65,7 @@ describe('detectContainerRuntime', () => {
});

it('extracts first line of --version output as version string', async () => {
mockCheckSubprocess.mockResolvedValue(true);
mockResolveExecutable.mockImplementation((bin: string) => `/usr/bin/${bin}`);
mockRunSubprocessCapture.mockImplementation((_bin: string, args: string[]) => {
if (args[0] === '--version')
return Promise.resolve({ code: 0, stdout: 'Docker version 24.0.0\nExtra info line\n', stderr: '' });
Expand All @@ -83,7 +78,7 @@ describe('detectContainerRuntime', () => {
});

it('uses empty first line when version output is empty', async () => {
mockCheckSubprocess.mockResolvedValue(true);
mockResolveExecutable.mockImplementation((bin: string) => `/usr/bin/${bin}`);
mockRunSubprocessCapture.mockImplementation((_bin: string, args: string[]) => {
if (args[0] === '--version') return Promise.resolve({ code: 0, stdout: '', stderr: '' });
if (args[0] === 'build') return Promise.resolve({ code: 0, stdout: '', stderr: '' });
Expand All @@ -96,7 +91,7 @@ describe('detectContainerRuntime', () => {
});

it('skips runtime when build --help check fails with non-zero exit', async () => {
mockCheckSubprocess.mockResolvedValue(true);
mockResolveExecutable.mockImplementation((bin: string) => `/usr/bin/${bin}`);
mockRunSubprocessCapture.mockImplementation((_bin: string, args: string[]) => {
if (args[0] === '--version') return Promise.resolve({ code: 0, stdout: '1.0.0\n', stderr: '' });
if (args[0] === 'build') return Promise.resolve({ code: 1, stdout: '', stderr: 'unknown command "build"' });
Expand All @@ -108,7 +103,7 @@ describe('detectContainerRuntime', () => {
});

it('skips runtime when build --help exits 0 but stderr indicates unknown command (shim/wrapper)', async () => {
mockCheckSubprocess.mockResolvedValue(true);
mockResolveExecutable.mockImplementation((bin: string) => `/usr/bin/${bin}`);
mockRunSubprocessCapture.mockImplementation((_bin: string, args: string[]) => {
// Shim exits 0 for everything but prints error to stderr
if (args[0] === '--version') return Promise.resolve({ code: 0, stdout: '1.0.0\n', stderr: '' });
Expand All @@ -124,7 +119,7 @@ describe('detectContainerRuntime', () => {

describe('requireContainerRuntime', () => {
it('returns runtime info when available', async () => {
mockCheckSubprocess.mockResolvedValue(true);
mockResolveExecutable.mockImplementation((bin: string) => `/usr/bin/${bin}`);
mockRunSubprocessCapture.mockImplementation((_bin: string, args: string[]) => {
if (args[0] === '--version') return Promise.resolve({ code: 0, stdout: 'Docker version 24.0.0\n', stderr: '' });
if (args[0] === 'build') return Promise.resolve({ code: 0, stdout: '', stderr: '' });
Expand All @@ -136,7 +131,7 @@ describe('requireContainerRuntime', () => {
});

it('throws with install links when no runtime found', async () => {
mockCheckSubprocess.mockResolvedValue(false);
mockResolveExecutable.mockReturnValue(null);

await expect(requireContainerRuntime()).rejects.toThrow('No container runtime found');
await expect(requireContainerRuntime()).rejects.toThrow('https://docker.com');
Expand Down
6 changes: 3 additions & 3 deletions src/cli/external-requirements/checks.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* External dependency version checks.
*/
import { checkSubprocess, isWindows, runSubprocessCapture } from '../../lib';
import { checkSubprocess, isWindows, resolveExecutable, runSubprocessCapture } from '../../lib';
import type { AgentCoreProjectSpec, TargetLanguage } from '../../schema';
import { detectContainerRuntime } from './detect';
import { AWS_CLI_MIN_VERSION, NODE_MIN_VERSION, formatSemVer, parseSemVer, semVerGte } from './versions';
Expand Down Expand Up @@ -399,8 +399,8 @@ export async function checkCreateDependencies(
async function checkBinaryAvailable(binary: string): Promise<boolean> {
// Try multiple detection strategies
const checks = [
// Primary: use 'where' on Windows, 'which' on Unix
() => (isWindows ? checkSubprocess('where', [binary]) : checkSubprocess('which', [binary])),
// Primary: look it up on PATH (never the current directory)
() => Promise.resolve(resolveExecutable(binary) !== null),
// Fallback: try running with --version
() => checkSubprocess(binary, ['--version']),
// Fallback: try running with -v
Expand Down
5 changes: 2 additions & 3 deletions src/cli/external-requirements/detect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* Detects Docker, Podman, or Finch for container operations.
*/
import { CONTAINER_RUNTIMES, type ContainerRuntime } from '../../lib';
import { checkSubprocess, isWindows, runSubprocessCapture } from '../../lib';
import { resolveExecutable, runSubprocessCapture } from '../../lib';

export type { ContainerRuntime } from '../../lib';

Expand All @@ -26,8 +26,7 @@ export interface DetectionResult {
export async function detectContainerRuntime(): Promise<DetectionResult> {
for (const runtime of CONTAINER_RUNTIMES) {
// Check if binary exists
const exists = isWindows ? await checkSubprocess('where', [runtime]) : await checkSubprocess('which', [runtime]);
if (!exists) continue;
if (resolveExecutable(runtime) === null) continue;

// Verify with --version
const result = await runSubprocessCapture(runtime, ['--version']);
Expand Down
Loading
Loading