Repository navigation
Expand file tree
/
Copy pathfiles.php
More file actions
157 lines (143 loc) · 6.51 KB
/
Copy pathfiles.php
File metadata and controls
157 lines (143 loc) · 6.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
<?php
declare(strict_types=1);
/*
* An agent with the file tools over a directory. Writes, edits and patches need your approval on
* the terminal; a shared Journal records every change, so typing "undo" (instead of a task) undoes
* everything written so far.
*
* HARNESS_OPENAI_URL=http://127.0.0.1:8012/v1 HARNESS_MODEL=qwen3.8 php examples/files.php <dir> [task]
*
* With a task it runs one turn; without, it asks for tasks until EOF. Ctrl-C cancels a turn.
*/
require __DIR__ . '/../vendor/autoload.php';
use Harness\Approval;
use Harness\Call;
use Harness\Decision;
use Harness\Event;
use Harness\Http\StreamTransport;
use Harness\Message;
use Harness\Options;
use Harness\Part\Text;
use Harness\Part\ToolCall;
use Harness\Provider\OpenAI\ChatCompletions;
use Harness\Reason;
use Harness\Result;
use Harness\Role;
use Harness\Run;
use Harness\ToolMiddleware;
use Harness\Tools;
use Harness\Tools\Files;
// This repository installs two adapters for its tests; an application installs one and skips this line.
fiber\setup(new FiberInterop\Phasync\Adapter());
$url = \getenv('HARNESS_OPENAI_URL') ?: exit("Set HARNESS_OPENAI_URL (and HARNESS_MODEL)\n");
$dir = $argv[1] ?? exit("Usage: php examples/files.php <dir> [task]\n");
$task = \implode(' ', \array_slice($argv, 2));
$root = new Files\Root($dir);
$journal = new Files\Journal();
// A CLI that only ever answers on the terminal gates in one middleware (see examples/shell.php): it
// asks, then calls $next() or returns an error Result. This example uses two on purpose, to show the
// form for a policy shared with a web host (examples/policy.php does the same with Harness\Policy).
// The policy asks with needsInput(), which a web host answers in its next request; the terminal
// middleware outside it answers at once instead, in the tool's fiber, so the turn never ends
// awaiting input. It answers any need, so a paused sub-agent would be answered the same way.
$policy = new class implements ToolMiddleware {
public function call(ToolCall $call, Call $context, Closure $next): Result
{
// answers() set: the host answered this call already.
if ([] === $context->answers() && null !== $context->spec && !$context->spec->hints->readOnly) {
return $context->needsInput([new Approval(reason: "{$call->name} changes files")]);
}
return $next($call, $context);
}
};
$terminal = new class implements ToolMiddleware {
public function call(ToolCall $call, Call $context, Closure $next): Result
{
$result = $next($call, $context);
while (null !== ($pending = $context->pending())) {
$answers = [];
$denied = false;
foreach ($pending->needs as $need) {
$input = $call->input;
$shown = isset($input['content']) ? \strlen((string) $input['content']) . ' bytes' : \json_encode(\array_diff_key($input, ['path' => 1]), \JSON_UNESCAPED_SLASHES);
echo "\n\e[33m" . ($need instanceof Approval ? "Allow {$call->name} on " . ($input['path'] ?? '?') . " ($shown)? {$need->reason} [y/N]" : $need->text) . "\e[0m ";
$line = \trim((string) \fgets(fiber\readable(\STDIN)));
if ($need instanceof Approval) {
$answers[$need->id] = 'y' === \strtolower($line) ? Decision::allow() : Decision::deny('the user said no');
$denied = $denied || !$answers[$need->id]->allowed;
} else {
$answers[$need->id] = $line;
}
}
$context->answer($answers);
// The rule the Run applies: without state, a denied approval is not called again.
if ($denied && null === $pending->state) {
return new Result([new Text('Denied: the user said no')], error: true);
}
$result = $next($call, $context);
}
return $result;
}
};
$model = new ChatCompletions(new StreamTransport(), $url, \getenv('HARNESS_MODEL') ?: 'default');
$run = new Run(
$model,
new Tools(
new Files\ReadFile($root), new Files\ListDir($root), new Files\Glob($root), new Files\Grep($root),
new Files\WriteFile($root, journal: $journal), new Files\EditFile($root, journal: $journal), new Files\ApplyPatch($root, journal: $journal),
),
system: "You work on the files in {$root->path} with your tools. Paths are relative to it. Be brief.",
middleware: [$terminal, $policy],
options: new Options(maxOutputTokens: 2000),
);
$busy = false;
\pcntl_async_signals(true);
\pcntl_signal(\SIGINT, function () use ($run, &$busy) {
$busy ? $run->cancel() : exit(0);
});
function render(Event $e): void
{
match (true) {
$e instanceof Event\ReasoningDelta => print ("\e[2m{$e->text}\e[0m"),
$e instanceof Event\TextDelta => print ($e->text),
$e instanceof Event\ToolCallReady => print ("\n\e[36m→ {$e->name} " . \json_encode($e->input, \JSON_UNESCAPED_SLASHES) . "\e[0m\n"),
$e instanceof Event\ToolEnded => print ($e->outcome instanceof Result
? "\e[2m← " . ($e->outcome->error ? 'error: ' : '') . \strtok($e->outcome->content[0]->text ?? '(media)', "\n") . "\e[0m\n"
: "\e[31m← {$e->outcome->getMessage()}\e[0m\n"),
$e instanceof Event\TurnEnded => print ("\n\e[2m[{$e->reason->value}" . ($e->error ? ": {$e->error->value}" : '') . ", {$e->usage->input} in, {$e->usage->output} out]\e[0m\n"),
default => null,
};
}
fiber\run(function () use ($run, $task, $journal, &$busy) {
do {
if ('' === $task) {
echo "\n\e[1mtask>\e[0m ";
$line = \fgets(fiber\readable(\STDIN));
if (false === $line) {
return;
}
$task = \trim($line);
if ('' === $task) {
continue;
}
if ('undo' === $task) {
$paths = $journal->undo();
echo [] === $paths ? "\e[2mNothing to undo\e[0m\n" : "\e[2mUndone: " . \implode(', ', $paths) . "\e[0m\n";
$task = '';
continue;
}
$once = false;
} else {
$once = true;
}
$busy = true;
foreach ($run->turn(new Message(Role::User, [new Text($task)])) as $event) {
render($event);
}
$busy = false;
if (Reason::Failed === $run->ended()->reason) {
echo "\e[31m{$run->ended()->error->getMessage()}\e[0m\n";
}
$task = '';
} while (!$once);
});