<?php
require 'examples/boot.php';
use Cognesy\AgentCtrl\AgentCtrl;
use Cognesy\AgentCtrl\Broadcasting\AgentCtrlConsoleLogger;
use Cognesy\AgentCtrl\Enum\AgentType;
use Cognesy\AgentCtrl\Event\AgentExecutionCompleted;
use Cognesy\AgentCtrl\Event\AgentToolUsed;
// 1. Built-in console logger: formatted, color-coded output
$logger = new AgentCtrlConsoleLogger(
useColors: true,
showTimestamps: true,
showToolArgs: true, // Show tool input args
showSandbox: false, // Hide sandbox setup events
showPipeline: false, // Hide request/response pipeline
showStreaming: false, // Hide stream events
);
$agent = AgentCtrl::make(AgentType::OpenCode)
->withModel('opencode/ling-3.0-flash-fin-free')
->withTimeout(60)
->wiretap($logger->wiretap());
$observedTools = [];
$completed = null;
// 2. Targeted listeners: subscribe to specific event types
$agent->onEvent(AgentToolUsed::class, function (AgentToolUsed $event) use (&$observedTools) {
$observedTools[] = $event->tool;
echo "\n >>> Tool used: {$event->tool}\n\n";
});
$agent->onEvent(AgentExecutionCompleted::class, function (AgentExecutionCompleted $event) use (&$completed) {
$completed = $event;
echo "\n=== Execution Complete ===\n";
echo " Tools: {$event->toolCallCount}\n";
if ($event->cost !== null) {
echo " Cost: $" . number_format($event->cost, 4) . "\n";
}
$tokens = ($event->inputTokens ?? 0) + ($event->outputTokens ?? 0);
if ($tokens > 0) {
echo " Tokens: {$tokens}\n";
}
});
// Run the agent
echo "=== Agent Execution Log ===\n\n";
$response = $agent->executeStreaming('List files in current directory and explain what you see.');
echo "\n=== Result ===\n";
if ($response->isSuccess()) {
echo "Answer: " . $response->text() . "\n";
assert($response->text() !== '');
assert(str_contains(strtolower($response->text()), 'composer.json'));
assert($observedTools !== [], 'Expected the directory inspection to emit a tool-use event');
assert($completed instanceof AgentExecutionCompleted, 'Expected an execution-completed event');
assert($completed->cost !== null, 'Expected the completion event to carry reported cost');
} else {
echo "Error: Command failed with exit code {$response->exitCode}\n";
exit(1);
}
?>