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
27 changes: 27 additions & 0 deletions src/Hooks/Response.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,19 @@ public function block(string $reason): self

return $this;
}

/**
* Block the tool call and immediately send the response
* Useful for replacing tool output entirely
*
* @param string $reason The reason/content to provide instead of tool execution
*/
public function blockAndSend(string $reason): never
{
$this->data['decision'] = 'block';
$this->data['reason'] = $reason;
$this->send();
}

/**
* Approve the tool call (PreToolUse only)
Expand All @@ -51,6 +64,20 @@ public function approve(string $reason = ''): self

return $this;
}

/**
* Approve the tool call and immediately send the response
*
* @param string $reason Optional approval reason
*/
public function approveAndSend(string $reason = ''): never
{
$this->data['decision'] = 'approve';
if ($reason) {
$this->data['reason'] = $reason;
}
$this->send();
}

/**
* Suppress output from transcript mode
Expand Down
61 changes: 61 additions & 0 deletions tests/Hooks/ExtendedResponseTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php

use BeyondCode\ClaudeHooks\Hooks\Response;

it('can block and send immediately', function () {
$response = new class extends Response {
public function testBlockAndSend(): void {
ob_start();
try {
$this->blockAndSend('Tool execution blocked');
} catch (SystemExit $e) {
// Expected
}
$output = ob_get_clean();

$data = json_decode($output, true);
expect($data)->toBeArray();
expect($data['decision'])->toBe('block');
expect($data['reason'])->toBe('Tool execution blocked');
}
};

$response->testBlockAndSend();
});

it('can approve and send immediately', function () {
$response = new class extends Response {
public function testApproveAndSend(): void {
ob_start();
try {
$this->approveAndSend('Tool execution approved');
} catch (SystemExit $e) {
// Expected
}
$output = ob_get_clean();

$data = json_decode($output, true);
expect($data)->toBeArray();
expect($data['decision'])->toBe('approve');
expect($data['reason'])->toBe('Tool execution approved');
}
};

$response->testApproveAndSend();
});

it('blockAndSend terminates execution', function () {
$response = new Response();

expect(function () use ($response) {
$response->blockAndSend('Blocked');
})->toThrow(SystemExit::class);
});

it('approveAndSend terminates execution', function () {
$response = new Response();

expect(function () use ($response) {
$response->approveAndSend('Approved');
})->toThrow(SystemExit::class);
});