@parcha/agentrun-client 0.1.0-beta.47 → 0.1.0-beta.48
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 +61 -5
- package/dist/claude.d.ts +1 -1
- package/dist/claude.js +9 -3
- package/dist/codex.js +7 -3
- package/dist/learning.d.ts +93 -8
- package/dist/learning.js +200 -33
- package/dist/operations.generated.d.ts +51 -0
- package/dist/operations.generated.js +3 -0
- package/dist/workflows.d.ts +27 -5
- package/dist/workflows.js +358 -65
- package/package.json +11 -3
package/dist/learning.js
CHANGED
|
@@ -86,7 +86,9 @@ export class BackendLearningClient {
|
|
|
86
86
|
this.#config = { ...config };
|
|
87
87
|
this.#owner = new AgentRun(config);
|
|
88
88
|
}
|
|
89
|
-
async begin(source, signal) {
|
|
89
|
+
async begin(source, signal, options = {}) {
|
|
90
|
+
if (options.idempotencyKey !== undefined && (!options.idempotencyKey.trim() || options.idempotencyKey.length > 256 || /[^\x21-\x7e]/.test(options.idempotencyKey)))
|
|
91
|
+
throw new AgentRunUsage('idempotencyKey must be a nonempty printable ASCII string of at most 256 characters.');
|
|
90
92
|
signal?.throwIfAborted();
|
|
91
93
|
if (source.runtime !== 'claude-agent-sdk' && source.runtime !== 'codex-sdk' && source.runtime !== 'eve')
|
|
92
94
|
throw new AgentRunUsage('Unsupported backend SDK runtime.');
|
|
@@ -100,7 +102,7 @@ export class BackendLearningClient {
|
|
|
100
102
|
this.#registration ??= this.#register(start).catch(error => { this.#registration = undefined; throw error; });
|
|
101
103
|
await waitFor(this.#registration, signal);
|
|
102
104
|
signal?.throwIfAborted();
|
|
103
|
-
const pending = this.#start(start);
|
|
105
|
+
const pending = this.#start(start, options.idempotencyKey);
|
|
104
106
|
return waitFor(pending, signal, () => {
|
|
105
107
|
// The POST may already have committed. Keep its answer observed and close a late receipt; flushLearning()
|
|
106
108
|
// waits for this cleanup and reports a failed write without delaying or replacing the caller's abort.
|
|
@@ -108,8 +110,8 @@ export class BackendLearningClient {
|
|
|
108
110
|
error: 'The backend task was cancelled before native SDK dispatch.' })));
|
|
109
111
|
});
|
|
110
112
|
}
|
|
111
|
-
async #start(start) {
|
|
112
|
-
const receipt = await this.#owner.sdkRuns.start(this.#config.agentId, start, { 'Idempotency-Key':
|
|
113
|
+
async #start(start, idempotencyKey = uuid()) {
|
|
114
|
+
const receipt = await this.#owner.sdkRuns.start(this.#config.agentId, start, { 'Idempotency-Key': idempotencyKey });
|
|
113
115
|
if (!receipt || typeof receipt.run_id !== 'string' || typeof receipt.token !== 'string' || receipt.agent_id !== this.#config.agentId || !receipt.learning) {
|
|
114
116
|
throw new AgentRunUsage('The SDK start response is missing its scoped run receipt.');
|
|
115
117
|
}
|
|
@@ -118,12 +120,7 @@ export class BackendLearningClient {
|
|
|
118
120
|
fetch: this.#config.fetch, timeoutMs: this.#config.timeoutMs, maxRetries: this.#config.maxRetries,
|
|
119
121
|
});
|
|
120
122
|
try {
|
|
121
|
-
return
|
|
122
|
-
runId: receipt.run_id, consoleUrl: receipt.console_url,
|
|
123
|
-
learningEnabled: receipt.learning.enabled, revision: receipt.learning.revision,
|
|
124
|
-
context: receipt.learning.context,
|
|
125
|
-
workflows: receipt.learning.workflows ?? [],
|
|
126
|
-
}, this.#config);
|
|
123
|
+
return this.resume({ baseUrl: this.#owner.baseUrl, agentId: this.#config.agentId, source: start, receipt });
|
|
127
124
|
}
|
|
128
125
|
catch (error) {
|
|
129
126
|
// Registration happened, but no native task was dispatched. Close its receipt rather than leaving it live.
|
|
@@ -132,6 +129,28 @@ export class BackendLearningClient {
|
|
|
132
129
|
throw error;
|
|
133
130
|
}
|
|
134
131
|
}
|
|
132
|
+
/** Restore a persisted receipt without registering or admitting a second native turn. */
|
|
133
|
+
resume(checkpoint) {
|
|
134
|
+
const saved = clone(checkpoint), { receipt, source } = saved;
|
|
135
|
+
if (saved.baseUrl !== this.#owner.baseUrl || saved.agentId !== this.#config.agentId || receipt?.agent_id !== saved.agentId ||
|
|
136
|
+
typeof receipt.run_id !== 'string' || !receipt.run_id || typeof receipt.token !== 'string' || !receipt.token || !receipt.learning ||
|
|
137
|
+
!source || !['claude-agent-sdk', 'codex-sdk', 'eve'].includes(source.runtime) || typeof source.input !== 'string' || typeof source.instructions !== 'string')
|
|
138
|
+
throw new AgentRunUsage('The SDK receipt belongs to another server or agent, or has no original source.');
|
|
139
|
+
if (this.#runtime !== undefined && this.#runtime !== source.runtime)
|
|
140
|
+
throw new AgentRunUsage('A backend learning client belongs to one SDK runtime.');
|
|
141
|
+
this.#runtime = source.runtime;
|
|
142
|
+
const scoped = new AgentRun({ baseUrl: saved.baseUrl, apiKey: receipt.token,
|
|
143
|
+
fetch: this.#config.fetch, timeoutMs: this.#config.timeoutMs, maxRetries: this.#config.maxRetries });
|
|
144
|
+
const session = new BackendLearningSession(scoped, {
|
|
145
|
+
runId: receipt.run_id, consoleUrl: receipt.console_url,
|
|
146
|
+
learningEnabled: receipt.learning.enabled, revision: receipt.learning.revision,
|
|
147
|
+
context: receipt.learning.context, workflows: receipt.learning.workflows ?? [],
|
|
148
|
+
...('check' in receipt.learning && receipt.learning.check ? { check: receipt.learning.check } : {}),
|
|
149
|
+
input: source.input,
|
|
150
|
+
}, this.#config, saved);
|
|
151
|
+
session.protect([this.#config.apiKey ?? '', receipt.token]);
|
|
152
|
+
return session;
|
|
153
|
+
}
|
|
135
154
|
async #register(source) {
|
|
136
155
|
const { agentId } = this.#config;
|
|
137
156
|
const read = () => this.#owner.agents.get(agentId);
|
|
@@ -148,7 +167,7 @@ export class BackendLearningClient {
|
|
|
148
167
|
const on = learning === true || (typeof learning === 'object' && learning !== null);
|
|
149
168
|
const definition = {
|
|
150
169
|
id: agentId, name: this.#config.name ?? agentId, instructions: source.instructions,
|
|
151
|
-
sdk: { runtime: source.runtime }, learning: on ? (learning === true ? true : { ...learning }) : false,
|
|
170
|
+
sdk: { runtime: source.runtime }, learning: on ? (learning === true ? true : { ...learning, agree_on: learning.agree_on ? [...learning.agree_on] : undefined }) : false,
|
|
152
171
|
};
|
|
153
172
|
try {
|
|
154
173
|
await this.#owner.agents.create({ definition }, { 'Idempotency-Key': uuid() });
|
|
@@ -179,7 +198,7 @@ export class BackendLearningClient {
|
|
|
179
198
|
throw new AggregateError(this.#errors.splice(0), 'AgentRun could not finish one or more SDK learning runs.');
|
|
180
199
|
}
|
|
181
200
|
}
|
|
182
|
-
/** One immutable source
|
|
201
|
+
/** One immutable source snapshot and ordered evidence. Only checkpoint() exposes private durable receipt state. */
|
|
183
202
|
export class BackendLearningSession {
|
|
184
203
|
runId;
|
|
185
204
|
consoleUrl;
|
|
@@ -193,9 +212,23 @@ export class BackendLearningSession {
|
|
|
193
212
|
#nativeEnvelopes = new Map();
|
|
194
213
|
#protected = new Set();
|
|
195
214
|
#abortCleanups = [];
|
|
215
|
+
#checkController = new AbortController();
|
|
196
216
|
#scoped;
|
|
197
217
|
#pollIntervalMs;
|
|
198
218
|
#learningTimeoutMs;
|
|
219
|
+
#checkpoint;
|
|
220
|
+
#check;
|
|
221
|
+
#workflowBridge;
|
|
222
|
+
#input;
|
|
223
|
+
#nativeEvents = [];
|
|
224
|
+
#nativeBytes = 0;
|
|
225
|
+
#nativeComplete = true;
|
|
226
|
+
#comparisonRedacted = false;
|
|
227
|
+
#sourceIncomplete = false;
|
|
228
|
+
#waitForLearning = true;
|
|
229
|
+
#submission;
|
|
230
|
+
#submissionBody;
|
|
231
|
+
#onCheckpoint;
|
|
199
232
|
#queue = Promise.resolve();
|
|
200
233
|
#sequence = 0;
|
|
201
234
|
#pending = 0;
|
|
@@ -204,8 +237,13 @@ export class BackendLearningSession {
|
|
|
204
237
|
#completion;
|
|
205
238
|
#outcome;
|
|
206
239
|
#status;
|
|
207
|
-
constructor(scoped, snapshot, config) {
|
|
240
|
+
constructor(scoped, snapshot, config, checkpoint) {
|
|
208
241
|
this.#scoped = scoped;
|
|
242
|
+
this.#checkpoint = checkpoint && clone(checkpoint);
|
|
243
|
+
this.#comparisonRedacted = checkpoint?.shadow?.redacted === true;
|
|
244
|
+
this.#check = snapshot.learningEnabled && snapshot.check ? clone(snapshot.check) : undefined;
|
|
245
|
+
this.#input = snapshot.input ?? '';
|
|
246
|
+
this.#workflowBridge = config.workflows;
|
|
209
247
|
this.runId = snapshot.runId;
|
|
210
248
|
this.consoleUrl = snapshot.consoleUrl;
|
|
211
249
|
this.learningEnabled = snapshot.learningEnabled;
|
|
@@ -219,13 +257,92 @@ export class BackendLearningSession {
|
|
|
219
257
|
this.#workflowEvidenceBinding = this.#workflowBinding;
|
|
220
258
|
this.workflowContext = this.#workflowBinding?.context ?? '';
|
|
221
259
|
}
|
|
260
|
+
checkpoint() {
|
|
261
|
+
if (!this.#checkpoint)
|
|
262
|
+
throw new AgentRunUsage('This session has no durable receipt checkpoint.');
|
|
263
|
+
return clone(this.#checkpoint);
|
|
264
|
+
}
|
|
265
|
+
#captureNative(event, detail = {}) {
|
|
266
|
+
if (!this.#check || event.type !== 'tool' || !this.#nativeComplete)
|
|
267
|
+
return;
|
|
268
|
+
try {
|
|
269
|
+
const captured = clone({ ...event, ...(detail.input !== undefined ? { input: detail.input } : {}),
|
|
270
|
+
...(detail.output !== undefined ? { output: detail.output } : {}), ...(detail.orderUnknown ? { orderUnknown: true } : {}),
|
|
271
|
+
...(detail.outputFormat ? { outputFormat: detail.outputFormat } : {}) });
|
|
272
|
+
const bytes = size(JSON.stringify(captured));
|
|
273
|
+
if (bytes > 250_000 || this.#nativeBytes + bytes > 3_000_000 || this.#nativeEvents.length >= 10_000)
|
|
274
|
+
throw new Error('native_evidence_limit');
|
|
275
|
+
this.#safe(captured, true);
|
|
276
|
+
this.#nativeBytes += bytes;
|
|
277
|
+
this.#nativeEvents.push(captured);
|
|
278
|
+
}
|
|
279
|
+
catch {
|
|
280
|
+
this.#nativeComplete = false;
|
|
281
|
+
this.#nativeEvents.length = 0;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
/** Deliver one finite recorded turn. Retry through a restored checkpoint; identical batches retain their keys. */
|
|
285
|
+
submit(events, outcome, options = {}) {
|
|
286
|
+
let body, savedEvents, savedOutcome, savedOptions;
|
|
287
|
+
try {
|
|
288
|
+
savedEvents = clone(events);
|
|
289
|
+
savedOutcome = clone(outcome);
|
|
290
|
+
savedOptions = { ...clone(options), onCheckpoint: options.onCheckpoint };
|
|
291
|
+
body = JSON.stringify([savedEvents, savedOutcome, savedOptions]);
|
|
292
|
+
}
|
|
293
|
+
catch (error) {
|
|
294
|
+
return reject(error);
|
|
295
|
+
}
|
|
296
|
+
if (this.#submission)
|
|
297
|
+
return body === this.#submissionBody ? this.#submission : reject(new AgentRunUsage('SDK submission is immutable.'));
|
|
298
|
+
if (this.#sequence || this.#completion)
|
|
299
|
+
return reject(new AgentRunUsage('Recorded submission cannot follow streamed evidence.'));
|
|
300
|
+
this.#submissionBody = body;
|
|
301
|
+
this.#submission = this.#submit(savedEvents, savedOutcome, savedOptions);
|
|
302
|
+
void this.#submission.catch(() => undefined);
|
|
303
|
+
return this.#submission;
|
|
304
|
+
}
|
|
305
|
+
async #submit(events, outcome, options) {
|
|
306
|
+
this.#sourceIncomplete = options.evidenceComplete === false;
|
|
307
|
+
this.#waitForLearning = options.waitForLearning !== false;
|
|
308
|
+
this.#onCheckpoint = options.onCheckpoint;
|
|
309
|
+
for (const event of options.nativeEvents ?? events)
|
|
310
|
+
this.#captureNative(event);
|
|
311
|
+
let batch = [];
|
|
312
|
+
for (const event of events) {
|
|
313
|
+
const bytes = size(JSON.stringify(event)) + 100;
|
|
314
|
+
if (bytes > 220_000 || event.type === 'text' && event.text.length > 128_000 || this.#evidenceBytes + size(JSON.stringify(batch)) + bytes > 3_000_000) {
|
|
315
|
+
this.#sourceIncomplete = true;
|
|
316
|
+
continue;
|
|
317
|
+
}
|
|
318
|
+
if (batch.length >= 100 || size(JSON.stringify([...batch, event])) > 220_000) {
|
|
319
|
+
await this.#enqueue(batch);
|
|
320
|
+
batch = [];
|
|
321
|
+
}
|
|
322
|
+
batch.push(event);
|
|
323
|
+
}
|
|
324
|
+
if (batch.length)
|
|
325
|
+
await this.#enqueue(batch);
|
|
326
|
+
await this.complete(outcome);
|
|
327
|
+
}
|
|
222
328
|
/** Keep ephemeral bridge capabilities out of stored evidence without changing native SDK results. */
|
|
223
|
-
protect(values) {
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
329
|
+
protect(values) {
|
|
330
|
+
for (const value of values)
|
|
331
|
+
if (value)
|
|
332
|
+
this.#protected.add(value);
|
|
333
|
+
this.#safe({ source: this.#checkpoint?.source, input: this.#input, events: this.#nativeEvents }, true);
|
|
334
|
+
}
|
|
335
|
+
#safe(value, comparisonEvidence = false) {
|
|
336
|
+
const visit = (item) => {
|
|
337
|
+
if (typeof item === 'string') {
|
|
338
|
+
const safe = [...this.#protected].reduce((text, secret) => text.split(secret).join('[withheld]'), item);
|
|
339
|
+
if (comparisonEvidence && safe !== item)
|
|
340
|
+
this.#comparisonRedacted = true;
|
|
341
|
+
return safe;
|
|
342
|
+
}
|
|
343
|
+
return Array.isArray(item) ? item.map(visit) : item && typeof item === 'object'
|
|
344
|
+
? Object.fromEntries(Object.entries(item).map(([key, v]) => [key, visit(v)])) : item;
|
|
345
|
+
};
|
|
229
346
|
return visit(clone(value));
|
|
230
347
|
}
|
|
231
348
|
/** Stop admitting work immediately; evidence can still drain before durable completion. */
|
|
@@ -236,9 +353,9 @@ export class BackendLearningSession {
|
|
|
236
353
|
}
|
|
237
354
|
/** Revoke workflow capabilities as soon as the native SDK cancels, including an idle stream. */
|
|
238
355
|
followAbort(signal) {
|
|
239
|
-
if (!signal || !this.#workflowBinding)
|
|
356
|
+
if (!signal || !this.#workflowBinding && !this.#check)
|
|
240
357
|
return;
|
|
241
|
-
const stop = () => this.closeWorkflows();
|
|
358
|
+
const stop = () => { this.closeWorkflows(); this.#checkController.abort(signal.reason); };
|
|
242
359
|
if (signal.aborted)
|
|
243
360
|
stop();
|
|
244
361
|
else {
|
|
@@ -259,6 +376,7 @@ export class BackendLearningSession {
|
|
|
259
376
|
nativeEvent(event, detail = {}) {
|
|
260
377
|
if (this.#completion)
|
|
261
378
|
return reject(new AgentRunUsage('Cannot add SDK evidence after completion.'));
|
|
379
|
+
this.#captureNative(event, detail);
|
|
262
380
|
if (event.type !== 'tool')
|
|
263
381
|
return this.event(event);
|
|
264
382
|
const pending = this.#nativeEnvelopes.get(event.id), binding = this.#workflowEvidenceBinding;
|
|
@@ -280,7 +398,8 @@ export class BackendLearningSession {
|
|
|
280
398
|
try {
|
|
281
399
|
if (event.status !== 'started' && pending.event.type === 'tool' && event.name === pending.event.name &&
|
|
282
400
|
(detail.input === undefined || JSON.stringify(detail.input) === pending.serialized) &&
|
|
283
|
-
binding?.claimNativeEnvelope?.(event.name, pending.input, event.status, detail.output
|
|
401
|
+
binding?.claimNativeEnvelope?.(event.name, pending.input, event.status, detail.outputFormat === 'mcp' && detail.output && typeof detail.output === 'object'
|
|
402
|
+
? detail.output.content : detail.output))
|
|
284
403
|
return Promise.resolve();
|
|
285
404
|
}
|
|
286
405
|
catch { /* A malformed result or binding remains real native tool evidence. */ }
|
|
@@ -291,16 +410,19 @@ export class BackendLearningSession {
|
|
|
291
410
|
event(event) {
|
|
292
411
|
if (this.#completion)
|
|
293
412
|
return reject(new AgentRunUsage('Cannot add SDK evidence after completion.'));
|
|
413
|
+
return this.#enqueue([event]);
|
|
414
|
+
}
|
|
415
|
+
#enqueue(events) {
|
|
294
416
|
if (this.#evidenceError !== undefined)
|
|
295
417
|
return reject(this.#evidenceError);
|
|
296
418
|
let body;
|
|
297
419
|
let bytes;
|
|
298
420
|
try {
|
|
299
|
-
const frozen = this.#safe(
|
|
300
|
-
body = { sequence: this.#sequence + 1, events:
|
|
421
|
+
const frozen = this.#safe(events, true);
|
|
422
|
+
body = { sequence: this.#sequence + 1, events: frozen };
|
|
301
423
|
bytes = size(JSON.stringify(body));
|
|
302
424
|
// Count the complete persisted batch, reserving room for the final answer and inbox metadata.
|
|
303
|
-
if (bytes > 250_000 || (event.type === 'text' && event.text.length > 128_000) || this.#pending >= 256 || this.#evidenceBytes + bytes > 3_000_000) {
|
|
425
|
+
if (bytes > 250_000 || events.some(event => event.type === 'text' && event.text.length > 128_000) || this.#pending >= 256 || this.#evidenceBytes + bytes > 3_000_000) {
|
|
304
426
|
throw new AgentRunUsage('SDK evidence exceeds its bounded upload queue or transcript size; self-improvement will be skipped.');
|
|
305
427
|
}
|
|
306
428
|
}
|
|
@@ -321,25 +443,30 @@ export class BackendLearningSession {
|
|
|
321
443
|
/** Persist the caller's outcome, then wait for the server's independent checked-learning verdict. */
|
|
322
444
|
complete(outcome) {
|
|
323
445
|
let frozen;
|
|
446
|
+
let serialized;
|
|
324
447
|
try {
|
|
325
448
|
if (!this.#completion) {
|
|
326
|
-
for (const cleanup of this.#abortCleanups.splice(0))
|
|
327
|
-
cleanup();
|
|
328
449
|
this.closeWorkflows();
|
|
329
450
|
for (const pending of this.#nativeEnvelopes.values())
|
|
330
451
|
void this.event(pending.event).catch(() => undefined);
|
|
331
452
|
this.#nativeEnvelopes.clear();
|
|
332
453
|
}
|
|
333
|
-
|
|
454
|
+
// Compare and identify the original native outcome before redaction: distinct secrets must never
|
|
455
|
+
// become apparently agreeing answers or identical durable completion fingerprints.
|
|
456
|
+
serialized = JSON.stringify(outcome);
|
|
457
|
+
frozen = this.#safe(outcome, true);
|
|
334
458
|
}
|
|
335
459
|
catch (error) {
|
|
336
460
|
return reject(error);
|
|
337
461
|
}
|
|
338
|
-
const serialized = JSON.stringify(frozen);
|
|
339
462
|
if (this.#completion)
|
|
340
463
|
return serialized === this.#outcome ? this.#completion : reject(new AgentRunUsage('SDK completion is immutable.'));
|
|
341
464
|
this.#outcome = serialized;
|
|
342
|
-
this.#completion = this.#complete(frozen)
|
|
465
|
+
this.#completion = this.#complete(frozen).finally(() => {
|
|
466
|
+
this.#nativeEvents.length = 0;
|
|
467
|
+
for (const cleanup of this.#abortCleanups.splice(0))
|
|
468
|
+
cleanup();
|
|
469
|
+
});
|
|
343
470
|
void this.#completion.catch(() => undefined);
|
|
344
471
|
return this.#completion;
|
|
345
472
|
}
|
|
@@ -349,15 +476,55 @@ export class BackendLearningSession {
|
|
|
349
476
|
this.#evidenceError ??= new AgentRunUsage('The SDK answer exceeded the AgentRun storage limit; self-improvement was skipped.');
|
|
350
477
|
outcome = { ...outcome, answer: '[The SDK answer exceeded the AgentRun storage limit and was not stored. The original result remains available in the backend.]' };
|
|
351
478
|
}
|
|
479
|
+
if (this.#check && this.#workflowBridge?.check && outcome.status === 'completed' && !this.#sourceIncomplete && this.#evidenceError === undefined) {
|
|
480
|
+
const fingerprint = Array.from(new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify([this.#check, this.#input, this.#nativeEvents, this.#outcome, this.#nativeComplete])))), byte => byte.toString(16).padStart(2, '0')).join('');
|
|
481
|
+
let result;
|
|
482
|
+
const saved = this.#checkpoint?.shadow;
|
|
483
|
+
if (saved) {
|
|
484
|
+
if (saved.fingerprint !== fingerprint || saved.state === 'complete' && (saved.event.id !== this.#check.id || saved.event.digest !== this.#check.digest))
|
|
485
|
+
throw new AgentRunUsage('The recorded shadow result belongs to different native evidence. Inspect the original turn before retrying.');
|
|
486
|
+
result = saved.state === 'complete' ? clone(saved.event)
|
|
487
|
+
: { type: 'workflow_check', id: this.#check.id, digest: this.#check.digest, outcome: 'failed', reason: 'shadow_outcome_unknown' };
|
|
488
|
+
}
|
|
489
|
+
else {
|
|
490
|
+
if (this.#checkpoint)
|
|
491
|
+
this.#checkpoint.shadow = { fingerprint, state: 'started', ...(this.#comparisonRedacted ? { redacted: true } : {}) };
|
|
492
|
+
if (this.#onCheckpoint)
|
|
493
|
+
await this.#onCheckpoint(this.checkpoint());
|
|
494
|
+
try {
|
|
495
|
+
result = this.#comparisonRedacted
|
|
496
|
+
? { type: 'workflow_check', id: this.#check.id, digest: this.#check.digest, outcome: 'failed', reason: 'client_redacted_evidence' }
|
|
497
|
+
: this.#nativeComplete
|
|
498
|
+
? await this.#workflowBridge.check(clone(this.#check), { runId: this.runId, input: this.#input, events: clone(this.#nativeEvents), outcome: clone(outcome), signal: this.#checkController.signal })
|
|
499
|
+
: { type: 'workflow_check', id: this.#check.id, digest: this.#check.digest, outcome: 'failed', reason: 'native_evidence_unavailable' };
|
|
500
|
+
}
|
|
501
|
+
catch {
|
|
502
|
+
result = { type: 'workflow_check', id: this.#check.id, digest: this.#check.digest, outcome: 'failed', reason: 'shadow_execution_failed' };
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
// The check result itself can introduce a protected value. Invalidate before checkpointing or
|
|
506
|
+
// uploading; sending '[withheld]' as an answer could make two different secrets compare equal.
|
|
507
|
+
result = this.#safe(result, true);
|
|
508
|
+
if (this.#comparisonRedacted)
|
|
509
|
+
result = { type: 'workflow_check', id: this.#check.id, digest: this.#check.digest,
|
|
510
|
+
outcome: 'failed', reason: 'client_redacted_evidence' };
|
|
511
|
+
if (this.#checkpoint)
|
|
512
|
+
this.#checkpoint.shadow = { fingerprint, state: 'complete', event: clone(result), ...(this.#comparisonRedacted ? { redacted: true } : {}) };
|
|
513
|
+
if (this.#onCheckpoint)
|
|
514
|
+
await this.#onCheckpoint(this.checkpoint());
|
|
515
|
+
await this.#enqueue([result]).catch(() => undefined);
|
|
516
|
+
}
|
|
517
|
+
this.#nativeEvents.length = 0;
|
|
352
518
|
const usage = outcome.usage && {
|
|
353
519
|
input_tokens: outcome.usage.input_tokens ?? null, output_tokens: outcome.usage.output_tokens ?? null,
|
|
354
520
|
cache_read_tokens: outcome.usage.cache_read_tokens ?? null, cache_write_tokens: outcome.usage.cache_write_tokens ?? null,
|
|
355
521
|
cost_usd: outcome.usage.cost_usd ?? null,
|
|
356
522
|
};
|
|
357
523
|
await this.#scoped.sdkRuns.complete(this.runId, {
|
|
358
|
-
...outcome, ...(usage ? { usage } : {}),
|
|
524
|
+
...outcome, ...(usage ? { usage } : {}), evidence_complete: !this.#sourceIncomplete && this.#evidenceError === undefined,
|
|
359
525
|
}, { 'Idempotency-Key': `${this.runId}:complete` });
|
|
360
|
-
|
|
526
|
+
if (this.#waitForLearning)
|
|
527
|
+
await this.#wait(outcome);
|
|
361
528
|
if (this.#evidenceError !== undefined)
|
|
362
529
|
throw this.#evidenceError;
|
|
363
530
|
}
|
|
@@ -380,7 +547,7 @@ export class BackendLearningSession {
|
|
|
380
547
|
this.#status = status;
|
|
381
548
|
if (!['running', 'processing'].includes(status.state)) {
|
|
382
549
|
const learning = status.learning;
|
|
383
|
-
const shouldLearn = this.learningEnabled && outcome.status === 'completed' && this.#evidenceError === undefined;
|
|
550
|
+
const shouldLearn = this.learningEnabled && outcome.status === 'completed' && !this.#sourceIncomplete && this.#evidenceError === undefined;
|
|
384
551
|
if (outcome.status === 'completed' && status.state !== 'completed')
|
|
385
552
|
throw new BackendLearningError(this.runId, 'server_run_failed');
|
|
386
553
|
if (!shouldLearn || learning?.state === 'merged' || learning?.state === 'dropped') {
|
|
@@ -916,6 +916,13 @@ export type Capabilities = {
|
|
|
916
916
|
features: Features;
|
|
917
917
|
regions: Array<Region>;
|
|
918
918
|
limits: Limits;
|
|
919
|
+
learning_model: {
|
|
920
|
+
location: "server" | "native";
|
|
921
|
+
ready: boolean;
|
|
922
|
+
model: string | null;
|
|
923
|
+
needs: "key" | "model" | null;
|
|
924
|
+
reason: string | null;
|
|
925
|
+
};
|
|
919
926
|
learning: {
|
|
920
927
|
pending: true;
|
|
921
928
|
approve: boolean;
|
|
@@ -1479,11 +1486,14 @@ export type ListLearningPromotionsResponse = {
|
|
|
1479
1486
|
differs_on?: string;
|
|
1480
1487
|
}>;
|
|
1481
1488
|
stopped?: true;
|
|
1489
|
+
released?: number;
|
|
1490
|
+
fresh_reads?: number;
|
|
1482
1491
|
};
|
|
1483
1492
|
runs?: Array<string>;
|
|
1484
1493
|
inputs?: Array<string>;
|
|
1485
1494
|
replay_id?: string;
|
|
1486
1495
|
commit?: string;
|
|
1496
|
+
via?: "sdk";
|
|
1487
1497
|
audit?: {
|
|
1488
1498
|
window: number;
|
|
1489
1499
|
disagree: number;
|
|
@@ -1565,6 +1575,8 @@ export type ListLearningPromotionsResponse = {
|
|
|
1565
1575
|
differs_on?: string;
|
|
1566
1576
|
}>;
|
|
1567
1577
|
stopped?: true;
|
|
1578
|
+
released?: number;
|
|
1579
|
+
fresh_reads?: number;
|
|
1568
1580
|
} | null;
|
|
1569
1581
|
} | null;
|
|
1570
1582
|
}>;
|
|
@@ -1985,6 +1997,13 @@ export type GetLearningCostResponse = {
|
|
|
1985
1997
|
};
|
|
1986
1998
|
/** What the agent has learned: its corrections, workflow drafts, log of changes and counts (GET /agents/{agent_id}/learning). */
|
|
1987
1999
|
export type GetAgentLearningResponse = {
|
|
2000
|
+
learning_model: {
|
|
2001
|
+
location: "server" | "native";
|
|
2002
|
+
ready: boolean;
|
|
2003
|
+
model: string | null;
|
|
2004
|
+
needs: "key" | "model" | null;
|
|
2005
|
+
reason: string | null;
|
|
2006
|
+
};
|
|
1988
2007
|
agent: string;
|
|
1989
2008
|
main: string | null;
|
|
1990
2009
|
corrections: string;
|
|
@@ -2413,6 +2432,7 @@ export type ListComputersResponse = {
|
|
|
2413
2432
|
required: Array<string>;
|
|
2414
2433
|
ready: boolean;
|
|
2415
2434
|
runs_refused: string | null;
|
|
2435
|
+
folder: "bind" | "archil" | "sync" | null;
|
|
2416
2436
|
shell: "computer" | "local" | "none";
|
|
2417
2437
|
host_tools: Array<string>;
|
|
2418
2438
|
why?: string;
|
|
@@ -2600,6 +2620,7 @@ export type SaveComputerKeysResponse = {
|
|
|
2600
2620
|
required: Array<string>;
|
|
2601
2621
|
ready: boolean;
|
|
2602
2622
|
runs_refused: string | null;
|
|
2623
|
+
folder: "bind" | "archil" | "sync" | null;
|
|
2603
2624
|
shell: "computer" | "local" | "none";
|
|
2604
2625
|
host_tools: Array<string>;
|
|
2605
2626
|
why?: string;
|
|
@@ -3200,6 +3221,12 @@ export interface CreateInlineRunParams {
|
|
|
3200
3221
|
"Idempotency-Key"?: string;
|
|
3201
3222
|
}
|
|
3202
3223
|
export type CreateInlineRunResponse = Run;
|
|
3224
|
+
/** Mint a link to the run's live view for the backend's user (POST /runs/{run_id}/computer/viewer). */
|
|
3225
|
+
export type CreateRunComputerViewerBody = Record<string, never>;
|
|
3226
|
+
export type CreateRunComputerViewerResponse = {
|
|
3227
|
+
url: string;
|
|
3228
|
+
expires_at: string;
|
|
3229
|
+
};
|
|
3203
3230
|
/** The files the run wrote (GET /runs/{run_id}/files). */
|
|
3204
3231
|
export type ListRunFilesResponse = RunFileList;
|
|
3205
3232
|
/** One run (GET /runs/{run_id}). */
|
|
@@ -3506,6 +3533,18 @@ export type SdkRunEventsBody = {
|
|
|
3506
3533
|
} | {
|
|
3507
3534
|
type: "session";
|
|
3508
3535
|
session_id: string;
|
|
3536
|
+
} | {
|
|
3537
|
+
type: "workflow_check";
|
|
3538
|
+
id: string;
|
|
3539
|
+
digest: string;
|
|
3540
|
+
outcome: "answered" | "handed_back" | "failed" | "skipped_write";
|
|
3541
|
+
answer?: string;
|
|
3542
|
+
reason?: string;
|
|
3543
|
+
skipped?: {
|
|
3544
|
+
tool: string;
|
|
3545
|
+
unmarked?: true;
|
|
3546
|
+
};
|
|
3547
|
+
fresh_reads?: number;
|
|
3509
3548
|
} | {
|
|
3510
3549
|
type: "tool";
|
|
3511
3550
|
id: string;
|
|
@@ -3562,6 +3601,16 @@ export type StartSdkRunResponse = {
|
|
|
3562
3601
|
workflow: string;
|
|
3563
3602
|
description: string;
|
|
3564
3603
|
}>;
|
|
3604
|
+
check?: {
|
|
3605
|
+
id: string;
|
|
3606
|
+
revision: string;
|
|
3607
|
+
digest: string;
|
|
3608
|
+
workflow: {
|
|
3609
|
+
name: string;
|
|
3610
|
+
workflow: string;
|
|
3611
|
+
description: string;
|
|
3612
|
+
};
|
|
3613
|
+
};
|
|
3565
3614
|
};
|
|
3566
3615
|
};
|
|
3567
3616
|
/** What this backend offers (GET /capabilities). */
|
|
@@ -5528,6 +5577,8 @@ export declare function resources(call: Call): {
|
|
|
5528
5577
|
computerRelease: (runId: string, body?: ReleaseRunComputerBody, options?: RequestOptions) => Promise<ReleaseRunComputerResponse>;
|
|
5529
5578
|
/** Start a run of an agent another system owns, given inline (POST /runs). */
|
|
5530
5579
|
createInlineRun: (body: CreateInlineRunBody, params?: CreateInlineRunParams, options?: RequestOptions) => Promise<CreateInlineRunResponse>;
|
|
5580
|
+
/** Mint a link to the run's live view for the backend's user (POST /runs/{run_id}/computer/viewer). */
|
|
5581
|
+
createRunComputerViewer: (runId: string, body?: CreateRunComputerViewerBody, options?: RequestOptions) => Promise<CreateRunComputerViewerResponse>;
|
|
5531
5582
|
/** The files the run wrote (GET /runs/{run_id}/files). */
|
|
5532
5583
|
files: (runId: string, options?: RequestOptions) => Promise<ListRunFilesResponse>;
|
|
5533
5584
|
/** One run (GET /runs/{run_id}). */
|
|
@@ -105,6 +105,7 @@ export const OPERATIONS = {
|
|
|
105
105
|
callRunComputer: { "method": "POST", "path": "/runs/{run_id}/computer/call", "pathParams": ["run_id"], "multiSegment": [], "query": [], "headers": [], "body": { "required": true, "types": ["application/json"] }, "answer": "json", "secret": false, "publicFields": [], "tagged": false },
|
|
106
106
|
releaseRunComputer: { "method": "POST", "path": "/runs/{run_id}/computer/release", "pathParams": ["run_id"], "multiSegment": [], "query": [], "headers": [], "body": { "required": false, "types": ["application/json"] }, "answer": "json", "secret": false, "publicFields": [], "tagged": false },
|
|
107
107
|
createInlineRun: { "method": "POST", "path": "/runs", "pathParams": [], "multiSegment": [], "query": [], "headers": ["Idempotency-Key"], "body": { "required": true, "types": ["application/json"] }, "answer": "json", "secret": false, "publicFields": [], "tagged": false },
|
|
108
|
+
createRunComputerViewer: { "method": "POST", "path": "/runs/{run_id}/computer/viewer", "pathParams": ["run_id"], "multiSegment": [], "query": [], "headers": [], "body": { "required": false, "types": ["application/json"] }, "answer": "json", "secret": false, "publicFields": [], "tagged": false },
|
|
108
109
|
listRunFiles: { "method": "GET", "path": "/runs/{run_id}/files", "pathParams": ["run_id"], "multiSegment": [], "query": [], "headers": [], "body": null, "answer": "json", "secret": false, "publicFields": [], "tagged": false },
|
|
109
110
|
getRun: { "method": "GET", "path": "/runs/{run_id}", "pathParams": ["run_id"], "multiSegment": [], "query": [], "headers": [], "body": null, "answer": "json", "secret": false, "publicFields": [], "tagged": false },
|
|
110
111
|
gradeRun: { "method": "PUT", "path": "/runs/{run_id}/grade", "pathParams": ["run_id"], "multiSegment": [], "query": [], "headers": [], "body": { "required": true, "types": ["application/json"] }, "answer": "json", "secret": false, "publicFields": [], "tagged": false },
|
|
@@ -391,6 +392,8 @@ export function resources(call) {
|
|
|
391
392
|
computerRelease: (runId, body, options) => call("releaseRunComputer", [runId], body, undefined, options),
|
|
392
393
|
/** Start a run of an agent another system owns, given inline (POST /runs). */
|
|
393
394
|
createInlineRun: (body, params, options) => call("createInlineRun", [], body, params, options),
|
|
395
|
+
/** Mint a link to the run's live view for the backend's user (POST /runs/{run_id}/computer/viewer). */
|
|
396
|
+
createRunComputerViewer: (runId, body, options) => call("createRunComputerViewer", [runId], body, undefined, options),
|
|
394
397
|
/** The files the run wrote (GET /runs/{run_id}/files). */
|
|
395
398
|
files: (runId, options) => call("listRunFiles", [runId], undefined, undefined, options),
|
|
396
399
|
/** One run (GET /runs/{run_id}). */
|
package/dist/workflows.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { BackendWorkflowSession, BackendWorkflowBinding, BackendWorkflowBridge, BackendWorkflowToolManifest } from './learning.js';
|
|
1
|
+
import type { BackendWorkflowSession, BackendWorkflowBinding, BackendWorkflowBridge, BackendWorkflowToolManifest, BackendWorkflowCheck, BackendNativeEvent } from './learning.js';
|
|
2
2
|
export interface WorkflowToolContext {
|
|
3
3
|
signal: AbortSignal;
|
|
4
4
|
runId: string;
|
|
@@ -94,22 +94,44 @@ export interface WorkflowMcpBridgeOptions<Document extends WorkflowEngineDocumen
|
|
|
94
94
|
leaseDurationMs?: number;
|
|
95
95
|
/** Local metadata only; callback inputs/results and capability tokens are never emitted. */
|
|
96
96
|
onEvent?(event: WorkflowBridgeEvent): void;
|
|
97
|
+
/** Opt in to fresh, explicitly read-only observations when the native recording has no match. Default false. */
|
|
98
|
+
shadowReadFallback?: boolean;
|
|
99
|
+
/** Optional host mapping for a draft's typed input. The default accepts the task's JSON object or one
|
|
100
|
+
* unambiguous recorded tool input matching the schema. It never guesses semantic fields. */
|
|
101
|
+
resolveCheckInput?(check: BackendWorkflowCheck, turn: {
|
|
102
|
+
input: string;
|
|
103
|
+
events: readonly BackendNativeEvent[];
|
|
104
|
+
signal: AbortSignal;
|
|
105
|
+
}): Promise<Record<string, unknown> | null> | Record<string, unknown> | null;
|
|
97
106
|
}
|
|
98
107
|
/** Private host handle. Never expose its arguments or capability in model-visible results or logs. */
|
|
99
108
|
export interface WorkflowMcpBinding extends BackendWorkflowBinding {
|
|
109
|
+
execute(name: string, input: Record<string, unknown>, signal: AbortSignal): Promise<WorkflowToolResult>;
|
|
100
110
|
mcpArguments(name: string, input: Record<string, unknown>): {
|
|
101
111
|
capability: string;
|
|
102
112
|
name: string;
|
|
103
113
|
input: Record<string, unknown>;
|
|
104
114
|
};
|
|
105
115
|
}
|
|
106
|
-
export
|
|
116
|
+
export type WorkflowToolResult = {
|
|
117
|
+
content: {
|
|
118
|
+
type: 'text';
|
|
119
|
+
text: string;
|
|
120
|
+
}[];
|
|
121
|
+
isError?: boolean;
|
|
122
|
+
};
|
|
123
|
+
export interface WorkflowBridge extends BackendWorkflowBridge {
|
|
124
|
+
bind(session: BackendWorkflowSession): WorkflowMcpBinding;
|
|
125
|
+
check: NonNullable<BackendWorkflowBridge['check']>;
|
|
126
|
+
close(): Promise<void>;
|
|
127
|
+
}
|
|
128
|
+
export interface WorkflowMcpBridge extends WorkflowBridge {
|
|
107
129
|
bind(session: BackendWorkflowSession): WorkflowMcpBinding;
|
|
108
130
|
readonly url: string;
|
|
109
131
|
readonly headers: Readonly<Record<string, string>>;
|
|
110
132
|
close(): Promise<void>;
|
|
111
133
|
}
|
|
112
|
-
/**
|
|
113
|
-
|
|
114
|
-
|
|
134
|
+
/** In-process host binding; opens no port or MCP connection. */
|
|
135
|
+
export declare function createWorkflowBridge<Document extends WorkflowEngineDocument, NodeRequest extends WorkflowModelRequest, JudgeRequest extends WorkflowJudgeRequest, JudgeResult>(options: WorkflowMcpBridgeOptions<Document, NodeRequest, JudgeRequest, JudgeResult>): WorkflowBridge;
|
|
136
|
+
/** Optional authenticated loopback transport over the same host-owned execution path. */
|
|
115
137
|
export declare function createWorkflowMcpBridge<Document extends WorkflowEngineDocument, NodeRequest extends WorkflowModelRequest, JudgeRequest extends WorkflowJudgeRequest, JudgeResult>(options: WorkflowMcpBridgeOptions<Document, NodeRequest, JudgeRequest, JudgeResult>): Promise<WorkflowMcpBridge>;
|