@parcha/agentrun-client 0.1.0-beta.46 → 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/dist/learning.js CHANGED
@@ -86,9 +86,11 @@ 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
- if (source.runtime !== 'claude-agent-sdk' && source.runtime !== 'codex-sdk')
93
+ if (source.runtime !== 'claude-agent-sdk' && source.runtime !== 'codex-sdk' && source.runtime !== 'eve')
92
94
  throw new AgentRunUsage('Unsupported backend SDK runtime.');
93
95
  if (typeof source.input !== 'string' || typeof source.instructions !== 'string')
94
96
  throw new AgentRunUsage('SDK input and source instructions must be strings.');
@@ -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': uuid() });
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 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,
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/seed snapshot and its ordered evidence. The scoped token is never exposed to the wrapper. */
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) { for (const value of values)
224
- if (value)
225
- this.#protected.add(value); }
226
- #safe(value) {
227
- const visit = (item) => typeof item === 'string' ? [...this.#protected].reduce((text, secret) => text.split(secret).join('[withheld]'), item)
228
- : Array.isArray(item) ? item.map(visit) : item && typeof item === 'object' ? Object.fromEntries(Object.entries(item).map(([key, v]) => [key, visit(v)])) : item;
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(event);
300
- body = { sequence: this.#sequence + 1, events: [frozen] };
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
- frozen = this.#safe(outcome);
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 } : {}), ...(this.#evidenceError !== undefined ? { evidence_complete: false } : {}),
524
+ ...outcome, ...(usage ? { usage } : {}), evidence_complete: !this.#sourceIncomplete && this.#evidenceError === undefined,
359
525
  }, { 'Idempotency-Key': `${this.runId}:complete` });
360
- await this.#wait(outcome);
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') {