@parcha/agentrun-client 0.1.0-beta.38 → 0.1.0-beta.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -0
- package/dist/claude.d.ts +19 -0
- package/dist/claude.js +210 -0
- package/dist/codex.d.ts +23 -0
- package/dist/codex.js +198 -0
- package/dist/learning.d.ts +154 -0
- package/dist/learning.js +407 -0
- package/dist/operations.generated.d.ts +1525 -128
- package/dist/operations.generated.js +109 -4
- package/dist/workflows.d.ts +106 -0
- package/dist/workflows.js +381 -0
- package/package.json +29 -2
package/dist/learning.js
ADDED
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
// The application still owns its SDK, tools, credentials and job triggering. These helpers send only the source
|
|
2
|
+
// policy, task and selected execution evidence to AgentRun; reflection and checked learning run on the server.
|
|
3
|
+
import { AgentRun } from './client.js';
|
|
4
|
+
import { AgentRunRefused, AgentRunTimeout, AgentRunUsage } from './errors.js';
|
|
5
|
+
/** A persistence or grading failure, separate from the application's original SDK result or error. */
|
|
6
|
+
export class BackendLearningError extends Error {
|
|
7
|
+
runId;
|
|
8
|
+
reason;
|
|
9
|
+
constructor(runId, reason) {
|
|
10
|
+
super(`AgentRun could not finish checked learning for run ${runId}: ${reason}.`);
|
|
11
|
+
this.runId = runId;
|
|
12
|
+
this.reason = reason;
|
|
13
|
+
this.name = 'BackendLearningError';
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
const uuid = () => globalThis.crypto.randomUUID();
|
|
17
|
+
const duration = (value, fallback, name) => {
|
|
18
|
+
if (value !== undefined && (!Number.isFinite(value) || value < 1))
|
|
19
|
+
throw new AgentRunUsage(`${name} must be at least 1 ms.`);
|
|
20
|
+
return value ?? fallback;
|
|
21
|
+
};
|
|
22
|
+
const clone = (value) => JSON.parse(JSON.stringify(value));
|
|
23
|
+
const size = (text) => new TextEncoder().encode(text).byteLength;
|
|
24
|
+
const statusOf = (value, runId) => {
|
|
25
|
+
const row = value;
|
|
26
|
+
if (!row || row.run_id !== runId || !['running', 'processing', 'completed', 'failed', 'cancelled'].includes(row.state ?? '')) {
|
|
27
|
+
throw new AgentRunUsage('The SDK run status response is invalid.');
|
|
28
|
+
}
|
|
29
|
+
const learning = row.learning;
|
|
30
|
+
if (learning !== undefined && learning !== null && (typeof learning !== 'object' || typeof learning.state !== 'string' || (learning.reason !== undefined && learning.reason !== null && typeof learning.reason !== 'string'))) {
|
|
31
|
+
throw new AgentRunUsage('The SDK run learning response is invalid.');
|
|
32
|
+
}
|
|
33
|
+
return row;
|
|
34
|
+
};
|
|
35
|
+
const reject = (error) => {
|
|
36
|
+
const promise = Promise.reject(error);
|
|
37
|
+
void promise.catch(() => undefined);
|
|
38
|
+
return promise;
|
|
39
|
+
};
|
|
40
|
+
/** Cancel one caller's wait, not shared registration or a request that may already have issued a receipt. */
|
|
41
|
+
function waitFor(pending, signal, abandoned) {
|
|
42
|
+
if (!signal)
|
|
43
|
+
return pending;
|
|
44
|
+
return new Promise((resolve, reject) => {
|
|
45
|
+
let settled = false;
|
|
46
|
+
const stop = () => {
|
|
47
|
+
if (settled)
|
|
48
|
+
return;
|
|
49
|
+
settled = true;
|
|
50
|
+
signal.removeEventListener('abort', stop);
|
|
51
|
+
abandoned?.();
|
|
52
|
+
reject(signal.reason);
|
|
53
|
+
};
|
|
54
|
+
// Observe both late outcomes even after cancellation; a late refusal cannot replace the caller's reason.
|
|
55
|
+
pending.then(value => {
|
|
56
|
+
if (settled)
|
|
57
|
+
return;
|
|
58
|
+
settled = true;
|
|
59
|
+
signal.removeEventListener('abort', stop);
|
|
60
|
+
resolve(value);
|
|
61
|
+
}, error => {
|
|
62
|
+
if (settled)
|
|
63
|
+
return;
|
|
64
|
+
settled = true;
|
|
65
|
+
signal.removeEventListener('abort', stop);
|
|
66
|
+
reject(error);
|
|
67
|
+
});
|
|
68
|
+
signal.addEventListener('abort', stop, { once: true });
|
|
69
|
+
if (signal.aborted)
|
|
70
|
+
stop();
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
/** Coordinates registration and background persistence without changing the SDK's own result/error contract. */
|
|
74
|
+
export class BackendLearningClient {
|
|
75
|
+
#owner;
|
|
76
|
+
#config;
|
|
77
|
+
#pending = new Set();
|
|
78
|
+
#errors = [];
|
|
79
|
+
#registration;
|
|
80
|
+
#runtime;
|
|
81
|
+
constructor(config) {
|
|
82
|
+
if (typeof config.agentId !== 'string' || !config.agentId.trim())
|
|
83
|
+
throw new AgentRunUsage('agentId must be a stable, nonempty agent id.');
|
|
84
|
+
duration(config.pollIntervalMs, 250, 'pollIntervalMs');
|
|
85
|
+
duration(config.learningTimeoutMs, 120_000, 'learningTimeoutMs');
|
|
86
|
+
this.#config = { ...config };
|
|
87
|
+
this.#owner = new AgentRun(config);
|
|
88
|
+
}
|
|
89
|
+
async begin(source, signal) {
|
|
90
|
+
signal?.throwIfAborted();
|
|
91
|
+
if (source.runtime !== 'claude-agent-sdk' && source.runtime !== 'codex-sdk')
|
|
92
|
+
throw new AgentRunUsage('Unsupported backend SDK runtime.');
|
|
93
|
+
if (typeof source.input !== 'string' || typeof source.instructions !== 'string')
|
|
94
|
+
throw new AgentRunUsage('SDK input and source instructions must be strings.');
|
|
95
|
+
// Freeze the source before the registration request: caller mutation cannot change the policy after validation.
|
|
96
|
+
const start = clone({ ...source, ...(this.#config.workflows ? { workflow_tools: [...this.#config.workflows.catalog], workflow_adapters: [...this.#config.workflows.adapters] } : {}) });
|
|
97
|
+
if (this.#runtime !== undefined && this.#runtime !== start.runtime)
|
|
98
|
+
throw new AgentRunUsage('A backend learning client belongs to one SDK runtime.');
|
|
99
|
+
this.#runtime = start.runtime;
|
|
100
|
+
this.#registration ??= this.#register(start).catch(error => { this.#registration = undefined; throw error; });
|
|
101
|
+
await waitFor(this.#registration, signal);
|
|
102
|
+
signal?.throwIfAborted();
|
|
103
|
+
const pending = this.#start(start);
|
|
104
|
+
return waitFor(pending, signal, () => {
|
|
105
|
+
// The POST may already have committed. Keep its answer observed and close a late receipt; flushLearning()
|
|
106
|
+
// waits for this cleanup and reports a failed write without delaying or replacing the caller's abort.
|
|
107
|
+
this.track(pending.then(session => session.complete({ status: 'cancelled', answer: '',
|
|
108
|
+
error: 'The backend task was cancelled before native SDK dispatch.' })));
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
async #start(start) {
|
|
112
|
+
const receipt = await this.#owner.sdkRuns.start(this.#config.agentId, start, { 'Idempotency-Key': uuid() });
|
|
113
|
+
if (!receipt || typeof receipt.run_id !== 'string' || typeof receipt.token !== 'string' || receipt.agent_id !== this.#config.agentId || !receipt.learning) {
|
|
114
|
+
throw new AgentRunUsage('The SDK start response is missing its scoped run receipt.');
|
|
115
|
+
}
|
|
116
|
+
const scoped = new AgentRun({
|
|
117
|
+
baseUrl: this.#owner.baseUrl, apiKey: receipt.token,
|
|
118
|
+
fetch: this.#config.fetch, timeoutMs: this.#config.timeoutMs, maxRetries: this.#config.maxRetries,
|
|
119
|
+
});
|
|
120
|
+
try {
|
|
121
|
+
return new BackendLearningSession(scoped, {
|
|
122
|
+
runId: receipt.run_id, consoleUrl: receipt.console_url,
|
|
123
|
+
learningEnabled: receipt.learning.enabled, revision: receipt.learning.revision,
|
|
124
|
+
context: receipt.learning.context, skills: receipt.learning.skills,
|
|
125
|
+
workflows: receipt.learning.workflows ?? [],
|
|
126
|
+
}, this.#config);
|
|
127
|
+
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
// Registration happened, but no native task was dispatched. Close its receipt rather than leaving it live.
|
|
130
|
+
await scoped.sdkRuns.complete(receipt.run_id, { status: 'failed', answer: '', evidence_complete: false,
|
|
131
|
+
error: 'The backend workflow bridge could not bind this task.' }, { 'Idempotency-Key': `${receipt.run_id}:bind-failed` }).catch(() => undefined);
|
|
132
|
+
throw error;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
async #register(source) {
|
|
136
|
+
const { agentId } = this.#config;
|
|
137
|
+
const read = () => this.#owner.agents.get(agentId);
|
|
138
|
+
let agent;
|
|
139
|
+
try {
|
|
140
|
+
agent = (await read()).body;
|
|
141
|
+
}
|
|
142
|
+
catch (error) {
|
|
143
|
+
if (!(error instanceof AgentRunRefused) || error.status !== 404)
|
|
144
|
+
throw error;
|
|
145
|
+
const definition = {
|
|
146
|
+
id: agentId, name: this.#config.name ?? agentId, instructions: source.instructions,
|
|
147
|
+
sdk: { runtime: source.runtime }, learning: this.#config.learning === true ? (this.#config.workflows ? true : 'notes') : false,
|
|
148
|
+
};
|
|
149
|
+
try {
|
|
150
|
+
await this.#owner.agents.create({ definition }, { 'Idempotency-Key': uuid() });
|
|
151
|
+
}
|
|
152
|
+
catch (conflict) {
|
|
153
|
+
// Another backend process may have registered the same stable agent while this one was looking it up.
|
|
154
|
+
if (!(conflict instanceof AgentRunRefused) || conflict.status !== 409)
|
|
155
|
+
throw conflict;
|
|
156
|
+
}
|
|
157
|
+
agent = (await read()).body;
|
|
158
|
+
}
|
|
159
|
+
if (agent.definition.sdk?.runtime !== source.runtime)
|
|
160
|
+
throw new AgentRunUsage('The existing agent uses a different runtime; choose its matching SDK wrapper or a new agentId.');
|
|
161
|
+
}
|
|
162
|
+
/** Observe completion immediately; the original SDK call can return without waiting for reflection/grading. */
|
|
163
|
+
track(promise) {
|
|
164
|
+
const observed = promise.then(() => undefined, error => { this.#errors.push(error); });
|
|
165
|
+
this.#pending.add(observed);
|
|
166
|
+
void observed.finally(() => this.#pending.delete(observed));
|
|
167
|
+
}
|
|
168
|
+
/** Wait for tracked writes and checked learning. Does not retry or re-run the caller's SDK task. */
|
|
169
|
+
async flushLearning() {
|
|
170
|
+
while (this.#pending.size)
|
|
171
|
+
await Promise.all([...this.#pending]);
|
|
172
|
+
if (this.#errors.length === 1)
|
|
173
|
+
throw this.#errors.shift();
|
|
174
|
+
if (this.#errors.length)
|
|
175
|
+
throw new AggregateError(this.#errors.splice(0), 'AgentRun could not finish one or more SDK learning runs.');
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
/** One immutable source/seed snapshot and its ordered evidence. The scoped token is never exposed to the wrapper. */
|
|
179
|
+
export class BackendLearningSession {
|
|
180
|
+
runId;
|
|
181
|
+
consoleUrl;
|
|
182
|
+
learningEnabled;
|
|
183
|
+
revision;
|
|
184
|
+
context;
|
|
185
|
+
skills;
|
|
186
|
+
workflows;
|
|
187
|
+
workflowContext;
|
|
188
|
+
#workflowBinding;
|
|
189
|
+
#workflowEvidenceBinding;
|
|
190
|
+
#nativeEnvelopes = new Map();
|
|
191
|
+
#protected = new Set();
|
|
192
|
+
#abortCleanups = [];
|
|
193
|
+
#scoped;
|
|
194
|
+
#pollIntervalMs;
|
|
195
|
+
#learningTimeoutMs;
|
|
196
|
+
#queue = Promise.resolve();
|
|
197
|
+
#sequence = 0;
|
|
198
|
+
#pending = 0;
|
|
199
|
+
#evidenceBytes = 0;
|
|
200
|
+
#evidenceError;
|
|
201
|
+
#completion;
|
|
202
|
+
#outcome;
|
|
203
|
+
#status;
|
|
204
|
+
constructor(scoped, snapshot, config) {
|
|
205
|
+
this.#scoped = scoped;
|
|
206
|
+
this.runId = snapshot.runId;
|
|
207
|
+
this.consoleUrl = snapshot.consoleUrl;
|
|
208
|
+
this.learningEnabled = snapshot.learningEnabled;
|
|
209
|
+
this.revision = snapshot.revision;
|
|
210
|
+
this.context = snapshot.context;
|
|
211
|
+
this.skills = clone(snapshot.skills);
|
|
212
|
+
this.workflows = clone(snapshot.workflows ?? []);
|
|
213
|
+
this.#pollIntervalMs = duration(config.pollIntervalMs, 250, 'pollIntervalMs');
|
|
214
|
+
this.#learningTimeoutMs = duration(config.learningTimeoutMs, 120_000, 'learningTimeoutMs');
|
|
215
|
+
if (this.learningEnabled && config.workflows)
|
|
216
|
+
this.#workflowBinding = config.workflows.bind(this);
|
|
217
|
+
this.#workflowEvidenceBinding = this.#workflowBinding;
|
|
218
|
+
this.workflowContext = this.#workflowBinding?.context ?? '';
|
|
219
|
+
}
|
|
220
|
+
/** Keep ephemeral bridge capabilities out of stored evidence without changing native SDK results. */
|
|
221
|
+
protect(values) { for (const value of values)
|
|
222
|
+
if (value)
|
|
223
|
+
this.#protected.add(value); }
|
|
224
|
+
#safe(value) {
|
|
225
|
+
const visit = (item) => typeof item === 'string' ? [...this.#protected].reduce((text, secret) => text.split(secret).join('[withheld]'), item)
|
|
226
|
+
: Array.isArray(item) ? item.map(visit) : item && typeof item === 'object' ? Object.fromEntries(Object.entries(item).map(([key, v]) => [key, visit(v)])) : item;
|
|
227
|
+
return visit(clone(value));
|
|
228
|
+
}
|
|
229
|
+
/** Stop admitting work immediately; evidence can still drain before durable completion. */
|
|
230
|
+
closeWorkflows() {
|
|
231
|
+
const binding = this.#workflowBinding;
|
|
232
|
+
this.#workflowBinding = undefined;
|
|
233
|
+
binding?.close();
|
|
234
|
+
}
|
|
235
|
+
/** Revoke workflow capabilities as soon as the native SDK cancels, including an idle stream. */
|
|
236
|
+
followAbort(signal) {
|
|
237
|
+
if (!signal || !this.#workflowBinding)
|
|
238
|
+
return;
|
|
239
|
+
const stop = () => this.closeWorkflows();
|
|
240
|
+
if (signal.aborted)
|
|
241
|
+
stop();
|
|
242
|
+
else {
|
|
243
|
+
signal.addEventListener('abort', stop, { once: true });
|
|
244
|
+
this.#abortCleanups.push(() => signal.removeEventListener('abort', stop));
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
get status() { return this.#status; }
|
|
248
|
+
/** Keep the native task outcome, but refuse to learn from evidence the wrapper cannot faithfully capture. */
|
|
249
|
+
markEvidenceIncomplete(reason) {
|
|
250
|
+
if (this.#completion)
|
|
251
|
+
throw new AgentRunUsage('Cannot change SDK evidence after completion.');
|
|
252
|
+
this.#evidenceError ??= new AgentRunUsage(reason);
|
|
253
|
+
}
|
|
254
|
+
/** Observe native SDK tools without counting a positively correlated bridge envelope twice. Candidate starts wait
|
|
255
|
+
* for their result; every unmatched or unfinished candidate is still ordinary top-level evidence. Raw arguments
|
|
256
|
+
* and results stay local, and at most sixteen bounded candidates (the bridge's invocation bound) are retained. */
|
|
257
|
+
nativeEvent(event, detail = {}) {
|
|
258
|
+
if (this.#completion)
|
|
259
|
+
return reject(new AgentRunUsage('Cannot add SDK evidence after completion.'));
|
|
260
|
+
if (event.type !== 'tool')
|
|
261
|
+
return this.event(event);
|
|
262
|
+
const pending = this.#nativeEnvelopes.get(event.id), binding = this.#workflowEvidenceBinding;
|
|
263
|
+
if (event.status === 'started' && !pending && this.#nativeEnvelopes.size < 16) {
|
|
264
|
+
try {
|
|
265
|
+
if (binding?.matchesNativeEnvelope?.(event.name, detail.input)) {
|
|
266
|
+
const serialized = JSON.stringify(detail.input);
|
|
267
|
+
if (size(serialized) <= 131_072) {
|
|
268
|
+
this.#nativeEnvelopes.set(event.id, { event: clone(event), input: clone(detail.input), serialized });
|
|
269
|
+
return Promise.resolve();
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
catch { /* Unavailable correlation never removes evidence. */ }
|
|
274
|
+
}
|
|
275
|
+
if (!pending)
|
|
276
|
+
return this.event(event);
|
|
277
|
+
this.#nativeEnvelopes.delete(event.id);
|
|
278
|
+
try {
|
|
279
|
+
if (event.status !== 'started' && pending.event.type === 'tool' && event.name === pending.event.name &&
|
|
280
|
+
(detail.input === undefined || JSON.stringify(detail.input) === pending.serialized) &&
|
|
281
|
+
binding?.claimNativeEnvelope?.(event.name, pending.input, event.status, detail.output))
|
|
282
|
+
return Promise.resolve();
|
|
283
|
+
}
|
|
284
|
+
catch { /* A malformed result or binding remains real native tool evidence. */ }
|
|
285
|
+
// Queue both before yielding, so an immediately following completion cannot overtake the retained result.
|
|
286
|
+
return Promise.all([this.event(pending.event), this.event(event)]).then(() => undefined);
|
|
287
|
+
}
|
|
288
|
+
/** Await to apply backpressure. A failed/oversized batch prevents learning from an incomplete transcript. */
|
|
289
|
+
event(event) {
|
|
290
|
+
if (this.#completion)
|
|
291
|
+
return reject(new AgentRunUsage('Cannot add SDK evidence after completion.'));
|
|
292
|
+
if (this.#evidenceError !== undefined)
|
|
293
|
+
return reject(this.#evidenceError);
|
|
294
|
+
let body;
|
|
295
|
+
let bytes;
|
|
296
|
+
try {
|
|
297
|
+
const frozen = this.#safe(event);
|
|
298
|
+
body = { sequence: this.#sequence + 1, events: [frozen] };
|
|
299
|
+
bytes = size(JSON.stringify(body));
|
|
300
|
+
// Count the complete persisted batch, reserving room for the final answer and inbox metadata.
|
|
301
|
+
if (bytes > 250_000 || (event.type === 'text' && event.text.length > 128_000) || this.#pending >= 256 || this.#evidenceBytes + bytes > 3_000_000) {
|
|
302
|
+
throw new AgentRunUsage('SDK evidence exceeds its bounded upload queue or transcript size; self-improvement will be skipped.');
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
catch (error) {
|
|
306
|
+
this.#evidenceError = error;
|
|
307
|
+
return reject(error);
|
|
308
|
+
}
|
|
309
|
+
const sequence = ++this.#sequence;
|
|
310
|
+
this.#evidenceBytes += bytes;
|
|
311
|
+
this.#pending++;
|
|
312
|
+
const sent = this.#queue.then(async () => {
|
|
313
|
+
await this.#scoped.sdkRuns.events(this.runId, body, { 'Idempotency-Key': `${this.runId}:events:${sequence}` });
|
|
314
|
+
});
|
|
315
|
+
this.#queue = sent;
|
|
316
|
+
void sent.then(() => { this.#pending--; }, error => { this.#pending--; this.#evidenceError ??= error; });
|
|
317
|
+
return sent;
|
|
318
|
+
}
|
|
319
|
+
/** Persist the caller's outcome, then wait for the server's independent checked-learning verdict. */
|
|
320
|
+
complete(outcome) {
|
|
321
|
+
let frozen;
|
|
322
|
+
try {
|
|
323
|
+
if (!this.#completion) {
|
|
324
|
+
for (const cleanup of this.#abortCleanups.splice(0))
|
|
325
|
+
cleanup();
|
|
326
|
+
this.closeWorkflows();
|
|
327
|
+
for (const pending of this.#nativeEnvelopes.values())
|
|
328
|
+
void this.event(pending.event).catch(() => undefined);
|
|
329
|
+
this.#nativeEnvelopes.clear();
|
|
330
|
+
}
|
|
331
|
+
frozen = this.#safe(outcome);
|
|
332
|
+
}
|
|
333
|
+
catch (error) {
|
|
334
|
+
return reject(error);
|
|
335
|
+
}
|
|
336
|
+
const serialized = JSON.stringify(frozen);
|
|
337
|
+
if (this.#completion)
|
|
338
|
+
return serialized === this.#outcome ? this.#completion : reject(new AgentRunUsage('SDK completion is immutable.'));
|
|
339
|
+
this.#outcome = serialized;
|
|
340
|
+
this.#completion = this.#complete(frozen);
|
|
341
|
+
void this.#completion.catch(() => undefined);
|
|
342
|
+
return this.#completion;
|
|
343
|
+
}
|
|
344
|
+
async #complete(outcome) {
|
|
345
|
+
await this.#queue.catch(() => undefined);
|
|
346
|
+
if (outcome.answer.length > 128_000) {
|
|
347
|
+
this.#evidenceError ??= new AgentRunUsage('The SDK answer exceeded the AgentRun storage limit; self-improvement was skipped.');
|
|
348
|
+
outcome = { ...outcome, answer: '[The SDK answer exceeded the AgentRun storage limit and was not stored. The original result remains available in the backend.]' };
|
|
349
|
+
}
|
|
350
|
+
const usage = outcome.usage && {
|
|
351
|
+
input_tokens: outcome.usage.input_tokens ?? null, output_tokens: outcome.usage.output_tokens ?? null,
|
|
352
|
+
cache_read_tokens: outcome.usage.cache_read_tokens ?? null, cache_write_tokens: outcome.usage.cache_write_tokens ?? null,
|
|
353
|
+
cost_usd: outcome.usage.cost_usd ?? null,
|
|
354
|
+
};
|
|
355
|
+
await this.#scoped.sdkRuns.complete(this.runId, {
|
|
356
|
+
...outcome, ...(usage ? { usage } : {}), ...(this.#evidenceError !== undefined ? { evidence_complete: false } : {}),
|
|
357
|
+
}, { 'Idempotency-Key': `${this.runId}:complete` });
|
|
358
|
+
await this.#wait(outcome);
|
|
359
|
+
if (this.#evidenceError !== undefined)
|
|
360
|
+
throw this.#evidenceError;
|
|
361
|
+
}
|
|
362
|
+
async #wait(outcome) {
|
|
363
|
+
const deadline = Date.now() + this.#learningTimeoutMs;
|
|
364
|
+
for (;;) {
|
|
365
|
+
const left = deadline - Date.now();
|
|
366
|
+
if (left <= 0)
|
|
367
|
+
throw new AgentRunTimeout(this.runId, this.#learningTimeoutMs, undefined);
|
|
368
|
+
const signal = AbortSignal.timeout(Math.max(1, Math.ceil(left)));
|
|
369
|
+
let status;
|
|
370
|
+
try {
|
|
371
|
+
status = statusOf(await this.#scoped.sdkRuns.get(this.runId, { signal }), this.runId);
|
|
372
|
+
}
|
|
373
|
+
catch (error) {
|
|
374
|
+
if (signal.aborted || Date.now() >= deadline)
|
|
375
|
+
throw new AgentRunTimeout(this.runId, this.#learningTimeoutMs, undefined);
|
|
376
|
+
throw error;
|
|
377
|
+
}
|
|
378
|
+
this.#status = status;
|
|
379
|
+
if (!['running', 'processing'].includes(status.state)) {
|
|
380
|
+
const learning = status.learning;
|
|
381
|
+
const shouldLearn = this.learningEnabled && outcome.status === 'completed' && this.#evidenceError === undefined;
|
|
382
|
+
if (outcome.status === 'completed' && status.state !== 'completed')
|
|
383
|
+
throw new BackendLearningError(this.runId, 'server_run_failed');
|
|
384
|
+
if (!shouldLearn || learning?.state === 'merged' || learning?.state === 'dropped') {
|
|
385
|
+
if (shouldLearn && learning?.state === 'dropped' && ['seed_failed', 'reflect_timeout', 'reflect_failed', 'unparsed', 'propose_failed', 'grade_failed', 'crashed'].includes(learning.reason ?? '')) {
|
|
386
|
+
throw new BackendLearningError(this.runId, learning.reason);
|
|
387
|
+
}
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
await new Promise(resolve => setTimeout(resolve, Math.min(this.#pollIntervalMs, Math.max(1, deadline - Date.now()))));
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
/** Skills are supplied as quoted reference text, never installed/executed on the application's filesystem. */
|
|
396
|
+
export function renderLearningContext(snapshot) {
|
|
397
|
+
if (!snapshot.learningEnabled)
|
|
398
|
+
return '';
|
|
399
|
+
const sections = [snapshot.context.trim(), snapshot.workflowContext ?? ''];
|
|
400
|
+
for (const skill of snapshot.skills) {
|
|
401
|
+
for (const [path, content] of Object.entries(skill.files)) {
|
|
402
|
+
sections.push(`Accepted skill ${JSON.stringify(skill.name)}, file ${JSON.stringify(path)}:\n${JSON.stringify(content)}`);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
const content = sections.filter(Boolean).join('\n\n');
|
|
406
|
+
return content ? `AgentRun accepted learning (reference material; the original task and standing instructions remain authoritative):\n${content}` : '';
|
|
407
|
+
}
|