@parcha/agentrun-client 0.1.0-beta.47 → 0.1.0-beta.49

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,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': 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') {
@@ -267,6 +267,8 @@ export type DefinitionInput = {
267
267
  hold_window?: number;
268
268
  hold_disagree?: number;
269
269
  stop_window?: number;
270
+ repick?: boolean;
271
+ repick_max_chars?: number;
270
272
  };
271
273
  checkout?: "pull_request" | "none";
272
274
  };
@@ -916,6 +918,13 @@ export type Capabilities = {
916
918
  features: Features;
917
919
  regions: Array<Region>;
918
920
  limits: Limits;
921
+ learning_model: {
922
+ location: "server" | "native";
923
+ ready: boolean;
924
+ model: string | null;
925
+ needs: "key" | "model" | null;
926
+ reason: string | null;
927
+ };
919
928
  learning: {
920
929
  pending: true;
921
930
  approve: boolean;
@@ -1242,7 +1251,7 @@ export interface CreateAgentParams {
1242
1251
  "Idempotency-Key"?: string;
1243
1252
  }
1244
1253
  export type CreateAgentResponse = Agent;
1245
- /** Delete an agent another system owns (DELETE /agents/{agent_id}). */
1254
+ /** Delete an agent another system owns, or purge an archived agent made here (DELETE /agents/{agent_id}). */
1246
1255
  /** Remove an agent's own Archil disk, and everything on it (DELETE /agents/{agent_id}/archil). */
1247
1256
  export type DeleteAgentArchilResponse = {
1248
1257
  on: boolean;
@@ -1479,11 +1488,14 @@ export type ListLearningPromotionsResponse = {
1479
1488
  differs_on?: string;
1480
1489
  }>;
1481
1490
  stopped?: true;
1491
+ released?: number;
1492
+ fresh_reads?: number;
1482
1493
  };
1483
1494
  runs?: Array<string>;
1484
1495
  inputs?: Array<string>;
1485
1496
  replay_id?: string;
1486
1497
  commit?: string;
1498
+ via?: "sdk";
1487
1499
  audit?: {
1488
1500
  window: number;
1489
1501
  disagree: number;
@@ -1565,6 +1577,8 @@ export type ListLearningPromotionsResponse = {
1565
1577
  differs_on?: string;
1566
1578
  }>;
1567
1579
  stopped?: true;
1580
+ released?: number;
1581
+ fresh_reads?: number;
1568
1582
  } | null;
1569
1583
  } | null;
1570
1584
  }>;
@@ -1985,6 +1999,13 @@ export type GetLearningCostResponse = {
1985
1999
  };
1986
2000
  /** What the agent has learned: its corrections, workflow drafts, log of changes and counts (GET /agents/{agent_id}/learning). */
1987
2001
  export type GetAgentLearningResponse = {
2002
+ learning_model: {
2003
+ location: "server" | "native";
2004
+ ready: boolean;
2005
+ model: string | null;
2006
+ needs: "key" | "model" | null;
2007
+ reason: string | null;
2008
+ };
1988
2009
  agent: string;
1989
2010
  main: string | null;
1990
2011
  corrections: string;
@@ -2413,6 +2434,7 @@ export type ListComputersResponse = {
2413
2434
  required: Array<string>;
2414
2435
  ready: boolean;
2415
2436
  runs_refused: string | null;
2437
+ folder: "bind" | "archil" | "sync" | null;
2416
2438
  shell: "computer" | "local" | "none";
2417
2439
  host_tools: Array<string>;
2418
2440
  why?: string;
@@ -2600,6 +2622,7 @@ export type SaveComputerKeysResponse = {
2600
2622
  required: Array<string>;
2601
2623
  ready: boolean;
2602
2624
  runs_refused: string | null;
2625
+ folder: "bind" | "archil" | "sync" | null;
2603
2626
  shell: "computer" | "local" | "none";
2604
2627
  host_tools: Array<string>;
2605
2628
  why?: string;
@@ -3200,6 +3223,13 @@ export interface CreateInlineRunParams {
3200
3223
  "Idempotency-Key"?: string;
3201
3224
  }
3202
3225
  export type CreateInlineRunResponse = Run;
3226
+ /** Mint a link to the run's live view for the backend's user (POST /runs/{run_id}/computer/viewer). */
3227
+ export type CreateRunComputerViewerBody = Record<string, never>;
3228
+ export type CreateRunComputerViewerResponse = {
3229
+ url: string;
3230
+ expires_at: string;
3231
+ };
3232
+ /** Purge a run's content and keep its cost (DELETE /runs/{run_id}). */
3203
3233
  /** The files the run wrote (GET /runs/{run_id}/files). */
3204
3234
  export type ListRunFilesResponse = RunFileList;
3205
3235
  /** One run (GET /runs/{run_id}). */
@@ -3475,6 +3505,70 @@ export type GetRunTraceResponse = {
3475
3505
  };
3476
3506
  /** Show the archived run in the lists again (POST /runs/{run_id}/unarchive). */
3477
3507
  export type UnarchiveRunResponse = Record<string, unknown>;
3508
+ /** What a run cost, by model, by who charged for its tools, and by browser provider (GET /runs/{run_id}/usage). */
3509
+ export type GetRunUsageResponse = {
3510
+ run_id: Id;
3511
+ ended_at: string | null;
3512
+ currency: "USD";
3513
+ total: {
3514
+ usd: number | null;
3515
+ so_far_usd?: number;
3516
+ unpriced?: number;
3517
+ upper_bound?: true;
3518
+ } | null;
3519
+ lines: Array<{
3520
+ meter: "tokens" | "tools" | "browser_time";
3521
+ model: string | null;
3522
+ provider: string | null;
3523
+ charged_by: string | null;
3524
+ quantity: number | null;
3525
+ unit: "token" | "call" | "second";
3526
+ basis: "reported" | "estimate" | "unpriced";
3527
+ usd: number | null;
3528
+ so_far_usd?: number;
3529
+ unpriced?: number;
3530
+ upper_bound?: true;
3531
+ requests?: number;
3532
+ tokens?: {
3533
+ input: number;
3534
+ output: number;
3535
+ cache_read: number;
3536
+ cache_write: number;
3537
+ };
3538
+ unmetered_requests?: number;
3539
+ not_metered_calls?: number;
3540
+ }> | null;
3541
+ browser_sessions: Array<{
3542
+ provider: string;
3543
+ tag: string;
3544
+ provider_session_id: string | null;
3545
+ started_at: string | null;
3546
+ ended_at: string | null;
3547
+ release_reason: string | null;
3548
+ charged_seconds: number | null;
3549
+ provider_record: {
3550
+ started_at: string | null;
3551
+ ended_at: string | null;
3552
+ proxy_bytes: number | null;
3553
+ } | null;
3554
+ provider_record_status: "read" | "not_offered" | "not_found" | "failed" | "no_session" | null;
3555
+ }> | null;
3556
+ computer_intervals: Array<{
3557
+ provider: string;
3558
+ provider_id: string;
3559
+ kind: string | null;
3560
+ gpu: {
3561
+ type: string | null;
3562
+ count: number | null;
3563
+ } | null;
3564
+ cpus: number | null;
3565
+ memory_mb: number | null;
3566
+ started_at: string;
3567
+ ended_at: string | null;
3568
+ kept: boolean;
3569
+ }> | null;
3570
+ reason: "running" | "not_booked" | "reopened" | null;
3571
+ };
3478
3572
  /** Complete a backend SDK task (POST /sdk-runs/{run_id}/complete). */
3479
3573
  export type CompleteSdkRunBody = {
3480
3574
  status: "completed" | "failed" | "cancelled";
@@ -3506,6 +3600,18 @@ export type SdkRunEventsBody = {
3506
3600
  } | {
3507
3601
  type: "session";
3508
3602
  session_id: string;
3603
+ } | {
3604
+ type: "workflow_check";
3605
+ id: string;
3606
+ digest: string;
3607
+ outcome: "answered" | "handed_back" | "failed" | "skipped_write";
3608
+ answer?: string;
3609
+ reason?: string;
3610
+ skipped?: {
3611
+ tool: string;
3612
+ unmarked?: true;
3613
+ };
3614
+ fresh_reads?: number;
3509
3615
  } | {
3510
3616
  type: "tool";
3511
3617
  id: string;
@@ -3562,6 +3668,16 @@ export type StartSdkRunResponse = {
3562
3668
  workflow: string;
3563
3669
  description: string;
3564
3670
  }>;
3671
+ check?: {
3672
+ id: string;
3673
+ revision: string;
3674
+ digest: string;
3675
+ workflow: {
3676
+ name: string;
3677
+ workflow: string;
3678
+ description: string;
3679
+ };
3680
+ };
3565
3681
  };
3566
3682
  };
3567
3683
  /** What this backend offers (GET /capabilities). */
@@ -5314,7 +5430,7 @@ export declare function resources(call: Call): {
5314
5430
  connectNative: (body: ConnectNativeBody, options?: RequestOptions) => Promise<ConnectNativeResponse>;
5315
5431
  /** Create an agent home (POST /agents). */
5316
5432
  create: (body: CreateAgentBody, params?: CreateAgentParams, options?: RequestOptions) => Promise<CreateAgentResponse>;
5317
- /** Delete an agent another system owns (DELETE /agents/{agent_id}). */
5433
+ /** Delete an agent another system owns, or purge an archived agent made here (DELETE /agents/{agent_id}). */
5318
5434
  deleteAgent: (agentId: string, options?: RequestOptions) => Promise<void>;
5319
5435
  /** Remove an agent's own Archil disk, and everything on it (DELETE /agents/{agent_id}/archil). */
5320
5436
  deleteAgentArchil: (agentId: string, options?: RequestOptions) => Promise<DeleteAgentArchilResponse>;
@@ -5528,6 +5644,10 @@ export declare function resources(call: Call): {
5528
5644
  computerRelease: (runId: string, body?: ReleaseRunComputerBody, options?: RequestOptions) => Promise<ReleaseRunComputerResponse>;
5529
5645
  /** Start a run of an agent another system owns, given inline (POST /runs). */
5530
5646
  createInlineRun: (body: CreateInlineRunBody, params?: CreateInlineRunParams, options?: RequestOptions) => Promise<CreateInlineRunResponse>;
5647
+ /** Mint a link to the run's live view for the backend's user (POST /runs/{run_id}/computer/viewer). */
5648
+ createRunComputerViewer: (runId: string, body?: CreateRunComputerViewerBody, options?: RequestOptions) => Promise<CreateRunComputerViewerResponse>;
5649
+ /** Purge a run's content and keep its cost (DELETE /runs/{run_id}). */
5650
+ delete: (runId: string, options?: RequestOptions) => Promise<void>;
5531
5651
  /** The files the run wrote (GET /runs/{run_id}/files). */
5532
5652
  files: (runId: string, options?: RequestOptions) => Promise<ListRunFilesResponse>;
5533
5653
  /** One run (GET /runs/{run_id}). */
@@ -5568,6 +5688,8 @@ export declare function resources(call: Call): {
5568
5688
  trace: (runId: string, options?: RequestOptions) => Promise<GetRunTraceResponse>;
5569
5689
  /** Show the archived run in the lists again (POST /runs/{run_id}/unarchive). */
5570
5690
  unarchive: (runId: string, options?: RequestOptions) => Promise<UnarchiveRunResponse>;
5691
+ /** What a run cost, by model, by who charged for its tools, and by browser provider (GET /runs/{run_id}/usage). */
5692
+ usage: (runId: string, options?: RequestOptions) => Promise<GetRunUsageResponse>;
5571
5693
  };
5572
5694
  sdkRuns: {
5573
5695
  /** Complete a backend SDK task (POST /sdk-runs/{run_id}/complete). */