-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJobContext.php
More file actions
241 lines (226 loc) · 9.28 KB
/
JobContext.php
File metadata and controls
241 lines (226 loc) · 9.28 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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
<?php
declare(strict_types=1);
namespace Arcp\Runtime;
use Amp\Cancellation;
use Amp\DeferredCancellation;
use Arcp\Envelope\Priority;
use Arcp\Errors\PermissionDeniedException;
use Arcp\Ids\JobId;
use Arcp\Ids\LeaseId;
use Arcp\Ids\SessionId;
use Arcp\Ids\StreamId;
use Arcp\Ids\TraceId;
use Arcp\Messages\Artifacts\ArtifactRef;
use Arcp\Messages\Execution\JobProgress;
use Arcp\Messages\Human\HumanChoiceRequest;
use Arcp\Messages\Human\HumanChoiceResponse;
use Arcp\Messages\Human\HumanInputRequest;
use Arcp\Messages\Human\HumanInputResponse;
use Arcp\Messages\Permissions\LeaseGranted;
use Arcp\Messages\Permissions\PermissionDeny;
use Arcp\Messages\Permissions\PermissionGrant;
use Arcp\Messages\Permissions\PermissionRequest;
use Arcp\Messages\Streaming\StreamChunk;
use Arcp\Messages\Streaming\StreamClose;
use Arcp\Messages\Streaming\StreamKind;
use Arcp\Messages\Streaming\StreamOpen;
/**
* Handle passed to a {@see ToolHandler} to interact with the runtime
* (progress, streams, human-input, permissions, artifacts). All async
* methods accept an optional {@see Cancellation} that participates in
* the per-job cancellation tree.
*/
final class JobContext
{
/** @internal The runtime sets this during job dispatch. */
public ?DeferredCancellation $cancellation = null;
public function __construct(
public readonly ARCPRuntime $runtime,
public readonly Session $session,
public readonly JobId $jobId,
public readonly SessionId $sessionId,
public readonly ?TraceId $traceId = null,
) {
}
public function reportProgress(int $percent, ?string $message = null): void
{
$this->runtime->emit($this->session, new JobProgress($percent, $message), [
'job_id' => $this->jobId,
'trace_id' => $this->traceId,
]);
}
/** @param array<string, mixed> $attributes */
public function emitLog(string $level, string $message, array $attributes = []): void
{
$this->runtime->emit($this->session, new \Arcp\Messages\Telemetry\LogEvent($level, $message, $attributes), [
'job_id' => $this->jobId,
'trace_id' => $this->traceId,
]);
}
/** @param array<string, bool|float|int|string> $dims */
public function emitMetric(string $name, int|float $value, string $unit, array $dims = []): void
{
$this->runtime->emit($this->session, new \Arcp\Messages\Telemetry\MetricEvent($name, $value, $unit, $dims), [
'job_id' => $this->jobId,
'trace_id' => $this->traceId,
]);
}
/**
* Open a `text`/`event`/`log`/`thought` stream and return its id and a
* helper to push chunks. `binary` is supported as base64 only.
*
* @return array{0: StreamId, 1: \Closure(string|array<string, mixed>|null, ?string=): void, 2: \Closure(?int=): void}
*/
public function openStream(StreamKind $kind, ?string $contentType = null, ?string $encoding = null): array
{
$sid = StreamId::random();
$this->runtime->emit($this->session, new StreamOpen($kind, $contentType, $encoding), [
'job_id' => $this->jobId,
'trace_id' => $this->traceId,
'stream_id' => $sid,
]);
$sequence = 0;
$emitChunk = function (string|array|null $body, ?string $extraContentType = null) use ($sid, &$sequence): void {
$payload = match (true) {
\is_string($body) => new StreamChunk(
sequence: $sequence++,
contentType: $extraContentType,
content: $body,
),
\is_array($body) => new StreamChunk(
sequence: $sequence++,
data: $body,
contentType: $extraContentType,
),
default => new StreamChunk(sequence: $sequence++),
};
$this->runtime->emit($this->session, $payload, [
'job_id' => $this->jobId,
'trace_id' => $this->traceId,
'stream_id' => $sid,
]);
};
$closeFn = function (?int $totalChunks = null) use ($sid, &$sequence): void {
$this->runtime->emit($this->session, new StreamClose($totalChunks ?? $sequence), [
'job_id' => $this->jobId,
'trace_id' => $this->traceId,
'stream_id' => $sid,
]);
};
return [$sid, $emitChunk, $closeFn];
}
/**
* Ask the human a free-form question and return the validated value.
* RFC §12.1 — runtime moves the job to `blocked` while waiting.
*
* @param array<string, mixed> $responseSchema
* @param array<string, mixed>|null $default
*/
public function requestHumanInput(
string $prompt,
array $responseSchema,
\DateTimeImmutable $expiresAt,
?array $default = null,
?Cancellation $cancellation = null,
): HumanInputResponse {
$req = new HumanInputRequest($prompt, $responseSchema, $expiresAt, $default);
$msgId = $this->runtime->emit($this->session, $req, [
'job_id' => $this->jobId,
'trace_id' => $this->traceId,
'priority' => Priority::High,
]);
$deadline = max(0.001, $expiresAt->getTimestamp() - $this->runtime->clock->now()->getTimestamp());
try {
/** @var HumanInputResponse $response */
$response = $this->runtime->pending->awaitResponse($msgId, $deadline, $cancellation);
return $response;
} catch (\Arcp\Errors\DeadlineExceededException $e) {
if ($default !== null) {
return new HumanInputResponse($default, 'default', $this->runtime->clock->now());
}
$this->runtime->emit($this->session, new \Arcp\Messages\Human\HumanInputCancelled('DEADLINE_EXCEEDED'), [
'job_id' => $this->jobId,
'trace_id' => $this->traceId,
'correlation_id' => $msgId,
]);
throw $e;
}
}
/** @param list<array{id: string, label: string}> $options */
public function requestHumanChoice(
string $prompt,
array $options,
\DateTimeImmutable $expiresAt,
?Cancellation $cancellation = null,
): HumanChoiceResponse {
$req = new HumanChoiceRequest($prompt, $options, $expiresAt);
$msgId = $this->runtime->emit($this->session, $req, [
'job_id' => $this->jobId,
'trace_id' => $this->traceId,
'priority' => Priority::High,
]);
$deadline = max(0.001, $expiresAt->getTimestamp() - $this->runtime->clock->now()->getTimestamp());
/** @var HumanChoiceResponse $response */
$response = $this->runtime->pending->awaitResponse($msgId, $deadline, $cancellation);
return $response;
}
public function requestPermission(
string $permission,
string $resource,
string $operation,
string $reason = '',
int $requestedLeaseSeconds = 300,
?Cancellation $cancellation = null,
): LeaseId {
$req = new PermissionRequest($permission, $resource, $operation, $reason, $requestedLeaseSeconds);
$msgId = $this->runtime->emit($this->session, $req, [
'job_id' => $this->jobId,
'trace_id' => $this->traceId,
'priority' => Priority::Critical,
]);
$response = $this->runtime->pending->awaitResponse($msgId, (float) $requestedLeaseSeconds + 60.0, $cancellation);
if ($response instanceof PermissionDeny) {
throw new PermissionDeniedException($permission, $resource);
}
if (!$response instanceof PermissionGrant) {
throw new PermissionDeniedException($permission, $resource, 'unexpected response type ' . $response::class);
}
$leaseId = LeaseId::random();
$expiresAt = $this->runtime->clock->now()->modify('+' . ($response->leaseSeconds ?? $requestedLeaseSeconds) . ' seconds');
$granted = new LeaseGranted(
leaseId: $leaseId,
permission: $permission,
resource: $resource,
operation: $operation,
expiresAt: $expiresAt,
);
$this->runtime->leases->register($granted);
$this->runtime->emit($this->session, $granted, [
'job_id' => $this->jobId,
'trace_id' => $this->traceId,
]);
return $leaseId;
}
public function putArtifact(string $mediaType, string $bytes, ?int $retentionSeconds = null): ArtifactRef
{
return $this->runtime->artifacts->put($this->session, $mediaType, $bytes, $retentionSeconds);
}
/**
* Emit `job.heartbeat` (RFC §10.3). The runtime expects callers to
* heartbeat at least every `heartbeat_interval_seconds`; the deadline
* defaults to twice the interval so a single drop is forgiven.
*/
public function heartbeat(int $deadlineMs = 60000, string $state = 'running'): void
{
$job = $this->runtime->jobs->tryGet($this->jobId);
if ($job === null) {
return;
}
$sequence = ++$job->heartbeatSequence;
$this->runtime->emit(
$this->session,
new \Arcp\Messages\Execution\JobHeartbeat($sequence, $deadlineMs, $state),
['job_id' => $this->jobId, 'trace_id' => $this->traceId],
);
}
}