Files
pipelines/app/lib/features/runs/data/runs_repository.dart
T
alan b3c9575fde Runs park on usage limits; failure classes, harness error policy, run budgets
- A stage refused for a Claude usage limit no longer fails its run: the
  runner tries the chats' Claude account auto-switch (per-home setting) and
  reruns the visit, else parks the run in the new waiting_quota status
  (persisted, with reset/resume time in run summaries, details and events)
  and resumes the same visit at reset + 1 min, also after a restart.
  resume_run / `pipelines resume` resumes now; cancel works on parked runs.
  The rerun visit gets a "# Previous attempt" interruption note. Subscription
  limits no longer say "top up the provider account".
- run/retry into an account known to be limited are deferred (quota_policy
  defer/refuse/now; CLI refuses under --json/--yes unless --defer or --now).
- failure_class on runs (quota, loop_exhausted, timeout, permission_denied,
  harness_error, blocked, environment, canceled, interrupted, budget,
  check_failed, other) in RunSummary/RunDetail/events, CLI inspect/runs/wait/
  stats and the app failure line.
- Claude permission denials (permission_denials / refused tool results) fail
  a blocked visit with permission_denied naming the tool use.
- Harness failures are classified transient vs deterministic; deterministic
  ones (and a repeated empty readback) skip error self-loops; transient
  self-loops back off 15 s, 1 min, 4 min.
- Whole-run USD budget: run --budget, server default (run-budget /
  get/set_run_settings); 80% warning notification, stop with class budget.
- App: waiting_quota status/filter with resume time, Resume now and Cancel,
  failure class wording. Docs and skill references updated.

Merges main (check stage, delivery gate, Claude stage restart survival,
schedule changes).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 14:34:53 +00:00

196 lines
6.6 KiB
Dart

import '../../../core/api_gateway.dart';
import '../domain/run_deletion.dart';
import '../domain/run_models.dart';
/// Protocol failure kept separate from transport errors; server error envelopes
/// are otherwise propagated unchanged by [ApiGateway].
class RunsRepositoryException implements Exception {
const RunsRepositoryException(this.message);
final String message;
@override
String toString() => message;
}
/// The most run ids one `delete_runs` request may carry.
const deleteRunsBatch = 1000;
/// Run protocol requests over the application's shared gateway.
class RunsRepository {
RunsRepository(this._gateway);
final ApiGateway _gateway;
/// Composition/actions reuse this feature's existing gateway, never a socket.
ApiGateway get gateway => _gateway;
Future<RunListResult> listRuns() async {
final reply = await _gateway.call('list_runs');
final runs = reply['runs'];
return RunListResult(
runs is List
? runs
.whereType<Map>()
.map((r) => Map<String, dynamic>.from(r))
.toList()
: const [],
reply['usage'] is Map
? Map<String, dynamic>.from(reply['usage'] as Map)
: null,
);
}
Future<JsonMap> getRun(num id) async =>
_required(await _gateway.call('get_run', {'run_id': id}), 'run_detail');
Future<JsonMap> cancelRun(num id) async => _required(
await _gateway.call('cancel_run', {'run_id': id}),
'run_detail',
);
/// Resumes a run parked in `waiting_quota` now instead of at its reset.
Future<JsonMap> resumeRun(num id) async => _required(
await _gateway.call('resume_run', {'run_id': id}),
'run_detail',
);
/// Deletes finished runs and their recorded data. The server answers
/// `runs_deleted` with the ids it removed, the ones it refused (with its
/// reason) and the bytes it freed.
///
/// The server accepts at most [deleteRunsBatch] ids per request, so a larger
/// selection is sent in consecutive batches and the replies combined. A
/// failing batch stops the rest; batches already answered are kept.
Future<RunsDeletion> deleteRuns(List<int> ids) async {
if (ids.isEmpty) {
throw const RunsRepositoryException('Choose runs to delete.');
}
RunsDeletion? result;
for (var start = 0; start < ids.length; start += deleteRunsBatch) {
final batch = ids.sublist(
start,
(start + deleteRunsBatch).clamp(0, ids.length),
);
final RunsDeletion deletion;
try {
final reply = await _gateway.call('delete_runs', {'run_ids': batch});
deletion =
RunsDeletion.fromReply(reply) ??
(throw const RunsRepositoryException(
'The server returned no runs_deleted reply.',
));
} catch (error) {
if (result == null) rethrow;
// Report what earlier batches deleted, and the rest as not deleted.
return result.merge(
RunsDeletion(
deleted: const [],
refused: [
for (final id in ids.sublist(start))
(runId: id, reason: '$error'),
],
),
);
}
result = result == null ? deletion : result.merge(deletion);
}
return result!;
}
/// Reads the exact recorded visit again; it never reruns its stage or tools.
///
/// The body is the web client's `repair_session_export` request: the run and
/// the recorded export sequence only. The reply is the whole run detail, so
/// the caller can show exactly what the server recorded next.
Future<JsonMap> repairSessionExport(num id, int sequence) async {
if (id is! int || id < 1 || sequence < 1) {
throw const RunsRepositoryException(
'An exact run and visit are required.',
);
}
return _required(
await _gateway.call('repair_session_export', {
'run_id': id,
'export_sequence': sequence,
}),
'run_detail',
);
}
Future<JsonMap> retryRun(
num id, {
required String requestKey,
String? mode,
}) async {
final fields = <String, dynamic>{'run_id': id, 'request_key': requestKey};
if (mode == 'restart') fields['retry_mode'] = mode;
return _required(await _gateway.call('retry_run', fields), 'run_detail');
}
Future<JsonMap> decideRun(
num id, {
String? stage,
required String option,
String feedback = '',
}) async {
final selected = option.trim();
if (selected.isEmpty) {
throw const RunsRepositoryException(
'Choose an option before continuing.',
);
}
final fields = <String, dynamic>{'run_id': id, 'option': selected};
if (stage != null && stage.trim().isNotEmpty) fields['stage'] = stage;
if (feedback.trim().isNotEmpty) fields['feedback'] = feedback.trim();
return _required(await _gateway.call('decide_run', fields), 'run_detail');
}
Future<JsonMap> setRunTitle(num id, String title) async => _required(
await _gateway.call('set_run_title', {'run_id': id, 'title': title}),
'run_detail',
);
/// Reads a run by the idempotency key of a launch whose reply was lost.
///
/// This is a read, not a launch: a server that never admitted the key answers
/// without a run detail, which is reported as null rather than invented.
Future<JsonMap?> runByRequestKey(String requestKey) async {
final key = requestKey.trim();
if (key.isEmpty) {
throw const RunsRepositoryException('A launch request key is required.');
}
final reply = await _gateway.call('get_run', {'request_key': key});
final detail = reply['run_detail'];
return detail is Map ? Map<String, dynamic>.from(detail) : null;
}
Future<JsonMap> startRun({
required num pipelineId,
required num version,
required String prompt,
required String workspace,
required String requestKey,
String title = '',
String outputFormat = '',
String? notifyMode,
}) async {
final fields = <String, dynamic>{
'pipeline_id': pipelineId,
'version': version,
'request_key': requestKey,
'workspace': workspace.trim(),
'input': {'prompt': prompt},
};
if (title.trim().isNotEmpty) fields['title'] = title.trim();
if (outputFormat.isNotEmpty) fields['output_format'] = outputFormat;
final mode = (notifyMode ?? '').trim().toLowerCase();
if (mode == 'on' || mode == 'off') fields['notify_mode'] = mode;
return _required(await _gateway.call('run_pipeline', fields), 'run_detail');
}
JsonMap _required(JsonMap reply, String key) {
final value = reply[key];
if (value is! Map) {
throw RunsRepositoryException('The server returned no $key.');
}
return Map<String, dynamic>.from(value);
}
}