-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJobContext.php
More file actions
347 lines (328 loc) · 12 KB
/
JobContext.php
File metadata and controls
347 lines (328 loc) · 12 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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
<?php
declare(strict_types=1);
namespace Arcp\Runtime;
use Amp\Cancellation;
use Amp\DeferredCancellation;
use Arcp\Envelope\Priority;
use Arcp\Errors\DeadlineExceededException;
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\Internal\Runtime\PermissionRequestSpec;
use Arcp\Messages\Artifacts\ArtifactRef;
use Arcp\Messages\Execution\JobHeartbeat;
use Arcp\Messages\Execution\JobProgress;
use Arcp\Messages\Execution\ResultChunk;
use Arcp\Messages\Human\HumanChoiceRequest;
use Arcp\Messages\Human\HumanChoiceResponse;
use Arcp\Messages\Human\HumanInputCancelled;
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;
use Arcp\Messages\Telemetry\LogEvent;
use Arcp\Messages\Telemetry\MetricEvent;
/**
* 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 emitResultChunk(
string $resultId,
string $data,
bool $more = true,
string $encoding = 'utf8',
): void {
$job = $this->runtime->jobs->tryGet($this->jobId);
$seq = $job instanceof Job ? $job->nextResultChunkSeq($resultId) : 0;
$this->runtime->emit(
$this->session,
new ResultChunk($resultId, $seq, $data, $encoding, $more),
['job_id' => $this->jobId, 'trace_id' => $this->traceId],
);
}
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 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
{
$job = $this->runtime->jobs->tryGet($this->jobId);
$remaining = $job?->budget?->consume($name, $value, $unit);
if ($remaining !== null) {
$dims['budget_remaining'] = $remaining;
}
$this->runtime->emit($this->session, new 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;
return [$sid, $this->makeChunkEmitter($sid, $sequence), $this->makeCloser($sid, $sequence)];
}
/**
* @return \Closure(string|array<string, mixed>|null, ?string=): void
*/
private function makeChunkEmitter(StreamId $sid, int &$sequence): \Closure
{
return 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,
]);
};
}
/** @return \Closure(?int=): void */
private function makeCloser(StreamId $sid, int &$sequence): \Closure
{
return 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,
]);
};
}
/**
* 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
*
* @size-check-suppress public BC; mirrors RFC §12.1 human.input.request.
*/
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 (DeadlineExceededException $e) {
if ($default !== null) {
return new HumanInputResponse($default, 'default', $this->runtime->clock->now());
}
$this->runtime->emit($this->session, new HumanInputCancelled('DEADLINE_EXCEEDED'), [
'job_id' => $this->jobId,
'trace_id' => $this->traceId,
'correlation_id' => $msgId,
]);
throw $e;
}
}
/**
* @param list<array{id: string, label: string}> $options
*
* @size-check-suppress public BC; mirrors RFC §12.1 human.choice.request.
*/
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;
}
/**
* @size-check-suppress public BC; protocol-level permission request fields.
*/
public function requestPermission(
string $permission,
string $resource,
string $operation,
string $reason = '',
int $requestedLeaseSeconds = 300,
?Cancellation $cancellation = null,
): LeaseId {
$spec = new PermissionRequestSpec(
$permission,
$resource,
$operation,
$reason,
$requestedLeaseSeconds,
);
$response = $this->awaitPermissionDecision($spec, $cancellation);
return $this->registerGrantedLease($spec, $response);
}
private function awaitPermissionDecision(
PermissionRequestSpec $spec,
?Cancellation $cancellation,
): PermissionGrant {
$req = new PermissionRequest(
$spec->permission,
$spec->resource,
$spec->operation,
$spec->reason,
$spec->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) $spec->requestedLeaseSeconds + 60.0,
$cancellation,
);
if ($response instanceof PermissionDeny) {
throw new PermissionDeniedException($spec->permission, $spec->resource);
}
if (!$response instanceof PermissionGrant) {
throw new PermissionDeniedException(
$spec->permission,
$spec->resource,
'unexpected response type ' . $response::class,
);
}
return $response;
}
private function registerGrantedLease(
PermissionRequestSpec $spec,
PermissionGrant $response,
): LeaseId {
$leaseId = LeaseId::random();
$leaseSeconds = $response->leaseSeconds ?? $spec->requestedLeaseSeconds;
$expiresAt = $this->runtime->clock->now()->modify('+' . $leaseSeconds . ' seconds');
$granted = new LeaseGranted(
leaseId: $leaseId,
permission: $spec->permission,
resource: $spec->resource,
operation: $spec->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,
new ArtifactBlob($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 instanceof Job) {
return;
}
$sequence = ++$job->heartbeatSequence;
$this->runtime->emit(
$this->session,
new JobHeartbeat($sequence, $deadlineMs, $state),
['job_id' => $this->jobId, 'trace_id' => $this->traceId],
);
}
}