Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changeset/add-govern-interceptor.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@inkeep/agents-sdk': patch
---

Add `govern()` fail-closed governance interceptor helper (CCS Conformance / CWE-636 mitigation) to structurally block tool execution on policy exceptions or denials.
57 changes: 57 additions & 0 deletions packages/agents-sdk/src/__tests__/governance.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { describe, expect, it, vi } from 'vitest';
import { govern } from '../governance';

describe('govern interceptor', () => {
it('should execute handler when policy returns true', async () => {
const handler = vi.fn().mockResolvedValue('success');
const governed = govern(handler, {
policy: async (args) => args.allowed === true,
});

const result = await governed({ allowed: true });
expect(result).toBe('success');
expect(handler).toHaveBeenCalledTimes(1);
expect(handler).toHaveBeenCalledWith({ allowed: true });
});

it('should block execution and throw error when policy returns false (fail-closed)', async () => {
const handler = vi.fn().mockResolvedValue('success');
const governed = govern(handler, {
policy: async (args) => args.allowed === true,
});

await expect(governed({ allowed: false })).rejects.toThrow(
'Governance policy check failed: execution blocked by fail-closed contract'
);
expect(handler).not.toHaveBeenCalled();
});

it('should block execution when policy throws an exception (fail-closed contract)', async () => {
const handler = vi.fn().mockResolvedValue('success');
const governed = govern(handler, {
policy: async () => {
throw new Error('Policy server timeout');
},
});

await expect(governed({ param: 'test' })).rejects.toThrow(
'Governance exception: Policy server timeout'
);
expect(handler).not.toHaveBeenCalled();
});

it('should invoke custom onDeny handler when governance blocks execution', async () => {
const handler = vi.fn().mockResolvedValue('success');
const onDeny = vi.fn().mockReturnValue('custom_denied_response');

const governed = govern(handler, {
policy: () => false,
onDeny,
});

const result = await governed({ param: 'test' });
expect(result).toBe('custom_denied_response');
expect(handler).not.toHaveBeenCalled();
expect(onDeny).toHaveBeenCalledTimes(1);
});
});
75 changes: 75 additions & 0 deletions packages/agents-sdk/src/governance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { getLogger } from '@inkeep/agents-core';

const logger = getLogger('governance');

export interface GovernanceOptions<TArgs = any> {
/**
* Policy identifier string or a boolean policy function that evaluates tool call arguments.
*/
policy?: string | ((args: TArgs) => boolean | Promise<boolean>);
/**
* Custom handler called when governance denies execution.
*/
onDeny?: (reason: string, args: TArgs) => any;
/**
* Custom error message returned when fail-closed contract blocks execution.
*/
failClosedErrorMessage?: string;
}

/**
* Wraps a tool handler function with a fail-closed governance boundary (CCS Conformance / CWE-636 mitigation).
* If the policy function throws an exception, rejects, or evaluates to false, the underlying tool
* handler is GUARANTEED to NOT be called.
*
* @param handler The target tool function to govern.
* @param options Governance configuration options.
*/
export function govern<TArgs = any, TResult = any>(
handler: (args: TArgs) => Promise<TResult> | TResult,
options: GovernanceOptions<TArgs> = {}
): (args: TArgs) => Promise<TResult> {
const {
policy = 'default',
failClosedErrorMessage = 'Governance policy check failed: execution blocked by fail-closed contract',
} = options;

return async (args: TArgs): Promise<TResult> => {
let allowed = false;
let policyError: Error | null = null;

try {
if (typeof policy === 'function') {
allowed = await policy(args);
} else {
allowed = true;
}
} catch (err) {
allowed = false;
policyError = err instanceof Error ? err : new Error(String(err));
}

if (!allowed) {
const reason = policyError
? `Governance exception: ${policyError.message}`
: `Policy '${typeof policy === 'string' ? policy : 'custom'}' denied execution`;

logger.warn(
{
policy: typeof policy === 'string' ? policy : 'custom',
reason,
hasError: !!policyError,
},
'Governance interceptor blocked tool execution (fail-closed)'
);

if (options.onDeny) {
return options.onDeny(reason, args);
}

throw new Error(`${failClosedErrorMessage} (${reason})`);
}

return await handler(args);
};
}
1 change: 1 addition & 0 deletions packages/agents-sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ export {
externalAgents,
} from './external-agent';
export { FunctionTool } from './function-tool';
export { govern, type GovernanceOptions } from './governance';
export { Project, type ProjectConfig } from './project';
export {
createFullProjectViaAPI,
Expand Down
Loading