diff --git a/app/lib/features/artifacts/ui/artifact_gallery_action.dart b/app/lib/features/artifacts/ui/artifact_gallery_action.dart index e6bbe5fc..dbce6232 100644 --- a/app/lib/features/artifacts/ui/artifact_gallery_action.dart +++ b/app/lib/features/artifacts/ui/artifact_gallery_action.dart @@ -12,7 +12,12 @@ const ValueKey runArtifactsButtonKey = ValueKey( 'run-detail-artifacts', ); -const Set _executingStatuses = {'queued', 'running', 'waiting'}; +const Set _executingStatuses = { + 'queued', + 'running', + 'waiting', + 'waiting_quota', +}; /// The detail's `steps` exactly as returned by the server. The pushed page /// snapshots the returned list once, so it never re-derives on each rebuild. diff --git a/app/lib/features/chat/domain/chat_shown_run.dart b/app/lib/features/chat/domain/chat_shown_run.dart index 1d213a89..0b57b28b 100644 --- a/app/lib/features/chat/domain/chat_shown_run.dart +++ b/app/lib/features/chat/domain/chat_shown_run.dart @@ -1,6 +1,7 @@ import '../../../core/api_gateway.dart'; import '../../pipelines/pipeline_format.dart' show formatDuration; import '../../runs/domain/run_events.dart' show isTerminalRunStatus; +import '../../runs/domain/run_quota.dart'; import 'chat_shown_run_map.dart'; export 'chat_shown_run_map.dart'; @@ -57,6 +58,7 @@ class ChatShownRun { /// The status in words: the outcome of a finished run when it says more. String get statusLabel { + if (isWaitingQuotaStatus(status)) return runWaitingQuotaLabel; final word = status.isEmpty ? 'unknown' : status; final label = '${word[0].toUpperCase()}${word.substring(1)}'; return finished && outcome.isNotEmpty && outcome != status diff --git a/app/lib/features/chat/ui/transcript/shown/chat_shown_run_card.dart b/app/lib/features/chat/ui/transcript/shown/chat_shown_run_card.dart index 5080dcca..58ad262f 100644 --- a/app/lib/features/chat/ui/transcript/shown/chat_shown_run_card.dart +++ b/app/lib/features/chat/ui/transcript/shown/chat_shown_run_card.dart @@ -15,6 +15,7 @@ IconData chatShownRunIcon(String status) => switch (status) { 'canceled' => Icons.cancel_outlined, 'interrupted' => Icons.pause_circle_outline, 'waiting' => Icons.front_hand_outlined, + 'waiting_quota' => Icons.hourglass_bottom, 'queued' => Icons.schedule, _ => Icons.play_circle_outline, }; @@ -22,7 +23,7 @@ IconData chatShownRunIcon(String status) => switch (status) { Color _statusColor(ColorScheme colors, String status) => switch (status) { 'succeeded' => colors.primary, 'failed' || 'interrupted' => colors.error, - 'waiting' => colors.tertiary, + 'waiting' || 'waiting_quota' => colors.tertiary, _ => colors.onSurfaceVariant, }; diff --git a/app/lib/features/pipelines/pipeline_filter.dart b/app/lib/features/pipelines/pipeline_filter.dart index 77f5c3da..29658e8a 100644 --- a/app/lib/features/pipelines/pipeline_filter.dart +++ b/app/lib/features/pipelines/pipeline_filter.dart @@ -29,6 +29,7 @@ const runStatusFilters = [ 'queued', 'running', 'waiting', + 'waiting_quota', 'succeeded', 'failed', 'canceled', diff --git a/app/lib/features/pipelines/pipeline_format.dart b/app/lib/features/pipelines/pipeline_format.dart index ea1a1721..c57b5058 100644 --- a/app/lib/features/pipelines/pipeline_format.dart +++ b/app/lib/features/pipelines/pipeline_format.dart @@ -64,6 +64,7 @@ const _runStateAliases = { 'running': 'running', 'queued': 'queued', 'waiting': 'waiting', + 'waiting_quota': 'waiting_quota', 'active': 'active', 'succeeded': 'succeeded', 'success': 'succeeded', @@ -88,6 +89,7 @@ String runStateOf(String? status) { /// `Running`-style title for a run state. String runStateLabel(String? status) { final state = runStateOf(status); + if (state == 'waiting_quota') return 'Waiting for usage limit'; return state.isEmpty ? state : '${state[0].toUpperCase()}${state.substring(1)}'; diff --git a/app/lib/features/runs/actions/cancel_eligibility.dart b/app/lib/features/runs/actions/cancel_eligibility.dart index a8cbb620..670dc4f8 100644 --- a/app/lib/features/runs/actions/cancel_eligibility.dart +++ b/app/lib/features/runs/actions/cancel_eligibility.dart @@ -8,12 +8,14 @@ import '../../../core/api_gateway.dart'; /// /// The status word alone is not enough: a stale `running` status without /// `executing` is not cancellable, while a run waiting on a pending session -/// export is. +/// export is. A run parked in `waiting_quota` has no live executor but the +/// server cancels it directly, so it is cancellable too. bool canCancelRun(JsonMap? run) { if (run == null) return false; final exportPending = _number(run['export_pending_sequence']); return (run['executing'] == true || - (run['status'] == 'waiting' && exportPending > 0)) && + (run['status'] == 'waiting' && exportPending > 0) || + run['status'] == 'waiting_quota') && run['cancel_requested'] != true && run['cleanup_unconfirmed'] != true; } diff --git a/app/lib/features/runs/actions/resume_quota_action.dart b/app/lib/features/runs/actions/resume_quota_action.dart new file mode 100644 index 00000000..638ca596 --- /dev/null +++ b/app/lib/features/runs/actions/resume_quota_action.dart @@ -0,0 +1,90 @@ +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../data/runs_repository.dart'; +import '../domain/run_quota.dart'; + +const resumeQuotaActionLabel = 'Resume now'; +const resumeQuotaActionKey = ValueKey('resume-quota-run-action'); +const resumeQuotaErrorKey = ValueKey('resume-quota-run-error'); + +/// Whether [run] is parked for a usage limit and may be resumed now. +bool canResumeQuotaRun(JsonMap? run) => + run != null && + run['id'] is num && + isWaitingQuotaStatus(run['status']) && + run['cancel_requested'] != true; + +/// "Resume now" for a run parked in `waiting_quota`: one `resume_run` request +/// whose accepted `run_detail` reaches [onRunChanged]. A refusal is shown +/// beside the button verbatim and leaves the button for a deliberate retry. +class ResumeQuotaRunAction extends StatefulWidget { + const ResumeQuotaRunAction({ + super.key, + required this.run, + required this.gateway, + required this.onRunChanged, + }); + + final JsonMap run; + final ApiGateway gateway; + final ValueChanged onRunChanged; + + @override + State createState() => _ResumeQuotaRunActionState(); +} + +class _ResumeQuotaRunActionState extends State { + bool _sending = false; + String? _error; + + Future _resume() async { + final id = widget.run['id']; + if (_sending || id is! num || !canResumeQuotaRun(widget.run)) return; + setState(() { + _sending = true; + _error = null; + }); + try { + final run = await RunsRepository(widget.gateway).resumeRun(id); + if (mounted && widget.run['id'] == id) widget.onRunChanged(run); + } catch (error) { + final message = '$error'.trim(); + if (mounted) { + setState( + () => _error = message.isEmpty + ? 'The server did not resume the run.' + : message, + ); + } + } finally { + if (mounted) setState(() => _sending = false); + } + } + + @override + Widget build(BuildContext context) { + if (!canResumeQuotaRun(widget.run)) return const SizedBox.shrink(); + final error = _error; + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + OutlinedButton( + key: resumeQuotaActionKey, + onPressed: _sending ? null : _resume, + child: const Text(resumeQuotaActionLabel), + ), + if (error != null) + Semantics( + liveRegion: true, + child: Text( + error, + key: resumeQuotaErrorKey, + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + ), + ], + ); + } +} diff --git a/app/lib/features/runs/data/runs_repository.dart b/app/lib/features/runs/data/runs_repository.dart index f8e9f259..22705b54 100644 --- a/app/lib/features/runs/data/runs_repository.dart +++ b/app/lib/features/runs/data/runs_repository.dart @@ -45,6 +45,12 @@ class RunsRepository { 'run_detail', ); + /// Resumes a run parked in `waiting_quota` now instead of at its reset. + Future 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. diff --git a/app/lib/features/runs/domain/run_events.dart b/app/lib/features/runs/domain/run_events.dart index f5ff2664..a336a7cf 100644 --- a/app/lib/features/runs/domain/run_events.dart +++ b/app/lib/features/runs/domain/run_events.dart @@ -1,4 +1,5 @@ import '../../../core/api_gateway.dart'; +import 'run_quota.dart'; import 'run_step_evidence.dart'; /// ApiGateway preserves wire envelopes; callers may also supply an extracted @@ -16,7 +17,7 @@ bool isWaitingRunStatus(dynamic status) => _word(status) == 'waiting'; int runLifecycleRank(dynamic status) => switch (_word(status)) { 'queued' => 0, - 'running' || 'waiting' => 1, + 'running' || 'waiting' || runStatusWaitingQuota => 1, 'succeeded' || 'failed' || 'canceled' || 'interrupted' => 2, _ => -1, }; @@ -27,8 +28,19 @@ int stepLifecycleRank(dynamic status) => switch (_word(status)) { _ => -1, }; +/// A run parks in waiting_quota from queued or running and leaves it for +/// queued (a deferred launch) or running (a resumed visit), so a move into or +/// out of it between live states is never stale. +bool _quotaHop(dynamic current, dynamic incoming, int Function(dynamic) rank) => + (isWaitingQuotaStatus(current) || isWaitingQuotaStatus(incoming)) && + rank(current) >= 0 && + rank(current) < 2 && + rank(incoming) >= 0 && + rank(incoming) < 2; + bool _stale(dynamic current, dynamic incoming, int Function(dynamic) rank) { if (_word(incoming).isEmpty) return false; + if (_quotaHop(current, incoming, rank)) return false; final oldRank = rank(current); final newRank = rank(incoming); return oldRank >= 0 && @@ -39,6 +51,7 @@ bool _stale(dynamic current, dynamic incoming, int Function(dynamic) rank) { String _advance(dynamic current, dynamic incoming, int Function(dynamic) rank) { if (_word(incoming).isEmpty || incoming == current) return '${current ?? ''}'; + if (_quotaHop(current, incoming, rank)) return '$incoming'; final oldRank = rank(current); final newRank = rank(incoming); if (oldRank < 0) return '$incoming'; @@ -50,7 +63,12 @@ String _advance(dynamic current, dynamic incoming, int Function(dynamic) rank) { bool executingFor(dynamic status, bool current) => switch (_word(status)) { 'queued' || 'running' => true, - 'waiting' || 'succeeded' || 'failed' || 'canceled' || 'interrupted' => false, + 'waiting' || + runStatusWaitingQuota || + 'succeeded' || + 'failed' || + 'canceled' || + 'interrupted' => false, _ => current, }; @@ -119,9 +137,16 @@ JsonMap _mergeRunFields(JsonMap current, JsonMap frame) { for (final key in ['outcome', 'current_stage', 'created_at', 'finished_at']) { if (!_blank(frame[key])) merged[key] = frame[key]; } - for (final key in ['failure_kind', 'failure_reason']) { + for (final key in ['failure_kind', 'failure_reason', 'failure_class']) { if (frame[key] != null) merged[key] = frame[key]; } + // A status frame for waiting_quota carries the wait; any other status + // clears it. + if (status != runStatusWaitingQuota) { + merged.remove('quota_wait'); + } else if (frame['quota_wait'] is Map) { + merged['quota_wait'] = frame['quota_wait']; + } // Snapshot and terminal frames carry the measured size; others omit it. if (frame['size_bytes'] is num) merged['size_bytes'] = frame['size_bytes']; final oldExport = _positiveInt(current['export_pending_sequence']); @@ -173,6 +198,8 @@ JsonMap? newRunSummaryFromFrame(JsonMap frame) { 'current_stage': frame['current_stage'] ?? '', 'failure_kind': frame['failure_kind'] ?? '', 'failure_reason': frame['failure_reason'] ?? '', + 'failure_class': frame['failure_class'] ?? '', + if (frame['quota_wait'] is Map) 'quota_wait': frame['quota_wait'], 'resource_wait': frame['resource_wait'], 'cancel_requested': frame['cancel_requested'] == true, 'cleanup_unconfirmed': frame['cleanup_unconfirmed'] == true, @@ -245,6 +272,7 @@ bool runDetailNeedsFullSync(JsonMap frame) { final stepStatus = step is Map ? step['status'] : null; return isTerminalRunStatus(frame['status']) || isWaitingRunStatus(frame['status']) || + isWaitingQuotaStatus(frame['status']) || frame['cancel_requested'] == true || frame['cleanup_unconfirmed'] == true || isWaitingRunStatus(stepStatus) || diff --git a/app/lib/features/runs/domain/run_failure_class.dart b/app/lib/features/runs/domain/run_failure_class.dart new file mode 100644 index 00000000..d030119e --- /dev/null +++ b/app/lib/features/runs/domain/run_failure_class.dart @@ -0,0 +1,53 @@ +import '../../../core/api_gateway.dart'; + +/// The operator wording of each server failure class, matching +/// `protocol.FailureClassLabel` in `internal/protocol/run_quota.go`. +const runFailureClassLabels = { + 'quota': 'usage limit', + 'loop_exhausted': 'loop limit reached', + 'timeout': 'timed out', + 'permission_denied': 'permission denied', + 'harness_error': 'harness error', + 'blocked': 'blocked', + 'environment': 'environment problem', + 'canceled': 'canceled', + 'interrupted': 'interrupted', + 'budget': 'budget exhausted', + 'check_failed': 'check failed', + 'other': 'failed', +}; + +/// The wording of [run]'s `failure_class`, or null when it has none. An +/// unknown class from a newer server is shown verbatim, as the server does. +String? runFailureClassLabel(JsonMap run) { + final word = '${run['failure_class'] ?? ''}'.trim().toLowerCase(); + if (word.isEmpty) return null; + return runFailureClassLabels[word] ?? word.replaceAll('_', ' '); +} + +/// The run's whole-run USD budget (`protocol.RunBudget`): absent, or a zero +/// limit, means the run has no cap. +typedef RunBudget = ({double limit, double spent, String source}); + +RunBudget? runBudget(JsonMap run) { + final budget = run['budget']; + if (budget is! Map) return null; + final limit = budget['limit_usd']; + final spent = budget['spent_usd']; + if (limit is! num || limit <= 0) return null; + return ( + limit: limit.toDouble(), + spent: spent is num ? spent.toDouble() : 0, + source: '${budget['source'] ?? ''}'.trim(), + ); +} + +/// `$1.25 of $5.00 budget`, noting a server-wide default cap. +String? runBudgetText(JsonMap run) { + final budget = runBudget(run); + if (budget == null) return null; + final text = + '\$${budget.spent.toStringAsFixed(2)} of ' + '\$${budget.limit.toStringAsFixed(2)} budget'; + return budget.source == 'server' ? '$text (server default)' : text; +} diff --git a/app/lib/features/runs/domain/run_models.dart b/app/lib/features/runs/domain/run_models.dart index a8f43a0e..30ad44ec 100644 --- a/app/lib/features/runs/domain/run_models.dart +++ b/app/lib/features/runs/domain/run_models.dart @@ -1,11 +1,13 @@ import '../../pipelines/pipeline_format.dart'; import '../../../core/api_gateway.dart'; +import 'run_quota.dart'; import 'run_tokens.dart'; const runStates = [ 'queued', 'running', 'waiting', + runStatusWaitingQuota, 'succeeded', 'failed', 'canceled', @@ -86,6 +88,7 @@ String runStateOf(dynamic status) => 'queued' || 'running' || 'waiting' || + runStatusWaitingQuota || 'active' || 'blocked' || 'skipped' => '${status ?? ''}'.trim().toLowerCase(), @@ -208,8 +211,11 @@ RunRowFacts runRowFacts(JsonMap run, DateTime now) { ); } -String runStatusLabel(JsonMap run) { +String runStatusLabel(JsonMap run, {DateTime? now}) { final status = '${run['status'] ?? ''}'; + if (status == runStatusWaitingQuota) { + return waitingQuotaStatusLabel(run, now: now); + } if (!{'queued', 'running', 'waiting'}.contains(status)) { return status.isEmpty ? 'unknown' : status; } diff --git a/app/lib/features/runs/domain/run_outcome_line.dart b/app/lib/features/runs/domain/run_outcome_line.dart index 706b494f..6b717449 100644 --- a/app/lib/features/runs/domain/run_outcome_line.dart +++ b/app/lib/features/runs/domain/run_outcome_line.dart @@ -1,4 +1,5 @@ import '../../../core/api_gateway.dart'; +import 'run_failure_class.dart'; import 'run_models.dart' show runStateOf; /// The longest result preview a succeeded run's row shows; a longer one is @@ -13,16 +14,27 @@ typedef RunOutcomeLine = ({String line, String full, bool failed}); /// The row's outcome line, or null when the run recorded nothing to show. /// /// A failed run shows its failure reason, else its diagnostic's first -/// non-blank line. A succeeded run shows its result preview only when it is +/// non-blank line, after the server's failure class when it recorded one +/// (`Failed · usage limit: `; the catch-all `other` adds nothing). A succeeded run shows its result preview only when it is /// short (at most [runResultPreviewRowLimit] characters on one line). RunOutcomeLine? runOutcomeLine(JsonMap run) { final state = runStateOf(run['status']); if (state == 'failed' && run['executing'] != true) { final reason = '${run['failure_reason'] ?? ''}'.trim(); final diagnostic = '${run['diagnostic'] ?? ''}'.trim(); - final full = reason.isNotEmpty ? reason : diagnostic; - if (full.isEmpty) return null; - return (line: firstLine(full), full: full, failed: true); + final text = reason.isNotEmpty ? reason : diagnostic; + final label = runFailureClassLabel(run); + if (label == null || label == runFailureClassLabels['other']) { + if (text.isEmpty) return null; + return (line: firstLine(text), full: text, failed: true); + } + final prefix = 'Failed · $label'; + if (text.isEmpty) return (line: prefix, full: prefix, failed: true); + return ( + line: '$prefix: ${firstLine(text)}', + full: '$prefix: $text', + failed: true, + ); } if (state == 'succeeded') { final preview = '${run['result_preview'] ?? ''}'.trim(); diff --git a/app/lib/features/runs/domain/run_quota.dart b/app/lib/features/runs/domain/run_quota.dart new file mode 100644 index 00000000..bbd7d664 --- /dev/null +++ b/app/lib/features/runs/domain/run_quota.dart @@ -0,0 +1,75 @@ +import '../../../core/api_gateway.dart'; +import '../../pipelines/pipeline_format.dart' + show formatLocalTimestamp, parseInstant; + +/// The server's status word for a run parked until a provider usage limit +/// resets (`protocol.RunStatusWaitingQuota`). It is not terminal: the server +/// resumes the run on its own after the reset, or on `resume_run`. +const runStatusWaitingQuota = 'waiting_quota'; + +/// The operator's words for [runStatusWaitingQuota]. +const runWaitingQuotaLabel = 'Waiting for usage limit'; + +bool isWaitingQuotaStatus(dynamic status) => + '${status ?? ''}'.trim().toLowerCase() == runStatusWaitingQuota; + +/// A parked run's `quota_wait` (`protocol.RunQuotaWait`). [sequence] is the +/// interrupted visit, 0 when the run was deferred before its first stage. +typedef RunQuotaWait = ({ + DateTime? resetsAt, + DateTime? resumeAt, + int sequence, + String stage, + String account, +}); + +/// The run's quota wait, or null when it carries none. +RunQuotaWait? runQuotaWait(JsonMap run) { + final wait = run['quota_wait']; + if (wait is! Map) return null; + final sequence = wait['sequence']; + return ( + resetsAt: parseInstant('${wait['resets_at'] ?? ''}'), + resumeAt: parseInstant('${wait['resume_at'] ?? ''}'), + sequence: sequence is num ? sequence.toInt() : 0, + stage: '${wait['stage'] ?? ''}'.trim(), + account: '${wait['account'] ?? ''}'.trim(), + ); +} + +/// [instant] in local time: `HH:mm` on [now]'s local day, else `d MMM HH:mm`. +String quotaClockText(DateTime instant, {DateTime? now}) { + final local = instant.toLocal(); + final today = (now ?? DateTime.now()).toLocal(); + if (local.year == today.year && + local.month == today.month && + local.day == today.day) { + String two(int value) => value.toString().padLeft(2, '0'); + return '${two(local.hour)}:${two(local.minute)}'; + } + return formatLocalTimestamp(local.toUtc().toIso8601String()) ?? ''; +} + +/// `resumes 09:01`, or null when the server sent no usable resume time. +String? quotaResumeText(RunQuotaWait? wait, {DateTime? now}) { + final at = wait?.resumeAt ?? wait?.resetsAt; + return at == null ? null : 'resumes ${quotaClockText(at, now: now)}'; +} + +/// The status line of a parked run: `Waiting for usage limit · resumes 09:01`. +String waitingQuotaStatusLabel(JsonMap run, {DateTime? now}) { + final resume = quotaResumeText(runQuotaWait(run), now: now); + return resume == null + ? runWaitingQuotaLabel + : '$runWaitingQuotaLabel · $resume'; +} + +/// The facts under a parked run's notice: the reset time, the account that +/// hit the limit and the interrupted stage, each only when recorded. +String quotaWaitMeta(RunQuotaWait wait, {DateTime? now}) => [ + if (wait.resetsAt case final at?) + 'Limit resets ${quotaClockText(at, now: now)}', + if (quotaResumeText(wait, now: now) case final resume?) 'run $resume', + if (wait.account.isNotEmpty) 'account ${wait.account}', + if (wait.stage.isNotEmpty) 'at ${wait.stage}', +].join(' · '); diff --git a/app/lib/features/runs/ui/run_changes_action.dart b/app/lib/features/runs/ui/run_changes_action.dart index 270b7ceb..36a358ff 100644 --- a/app/lib/features/runs/ui/run_changes_action.dart +++ b/app/lib/features/runs/ui/run_changes_action.dart @@ -19,7 +19,7 @@ List runDetailChangeSteps(JsonMap run) { return const []; } -const _executingStatuses = {'queued', 'running', 'waiting'}; +const _executingStatuses = {'queued', 'running', 'waiting', 'waiting_quota'}; /// Whether the run detail offers the action at all. The opened page is a /// snapshot of the recorded steps, so it is offered only once nothing is diff --git a/app/lib/features/runs/ui/run_detail_actions.dart b/app/lib/features/runs/ui/run_detail_actions.dart index 488eec69..c7c84ff3 100644 --- a/app/lib/features/runs/ui/run_detail_actions.dart +++ b/app/lib/features/runs/ui/run_detail_actions.dart @@ -6,6 +6,7 @@ import '../actions/cancel_run_action.dart'; import '../actions/retry_action.dart'; import '../actions/retry_eligibility.dart'; import 'run_decision_notice.dart'; +import 'run_quota_notice.dart'; /// Native actions on the loaded run, all using the app's one gateway and /// applying only accepted server detail through the same controller callback. @@ -60,6 +61,7 @@ class RunDetailActions extends StatelessWidget { ], ), RunDecisionNotice(run: run, gateway: gateway, onRunChanged: onRunChanged), + RunQuotaNotice(run: run, gateway: gateway, onRunChanged: onRunChanged), ], ); } diff --git a/app/lib/features/runs/ui/run_detail_summary_fields.dart b/app/lib/features/runs/ui/run_detail_summary_fields.dart index 22bb9178..52232b39 100644 --- a/app/lib/features/runs/ui/run_detail_summary_fields.dart +++ b/app/lib/features/runs/ui/run_detail_summary_fields.dart @@ -1,6 +1,7 @@ import '../../../core/api_gateway.dart'; import '../../pipelines/pipeline_format.dart'; import '../domain/run_deletion.dart' show formatByteSize, runSizeBytes; +import '../domain/run_failure_class.dart' show runBudgetText; import '../domain/run_findings.dart' show visitGrantsSummary; import '../domain/run_tokens.dart'; import 'run_detail_visit_facts.dart'; @@ -69,6 +70,7 @@ List detailSummaryRows(JsonMap run, {DateTime? now}) { add('Tokens', tokenUsageDetail(usage)); add('Cost', tokenUsageCost(usage)); } + add('Budget', runBudgetText(run)); final retryOf = _number(run['retry_of'])?.toInt() ?? 0; if (retryOf > 0) add('Retry of', 'run $retryOf'); add('Extra visits', visitGrantsSummary(run)); diff --git a/app/lib/features/runs/ui/run_quota_notice.dart b/app/lib/features/runs/ui/run_quota_notice.dart new file mode 100644 index 00000000..2bdbaa54 --- /dev/null +++ b/app/lib/features/runs/ui/run_quota_notice.dart @@ -0,0 +1,68 @@ +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../actions/resume_quota_action.dart'; +import '../domain/run_quota.dart'; + +/// A run parked until a usage limit resets: when the limit resets and the run +/// resumes, the account that hit it, and "Resume now". The run's Cancel stays +/// with the other run actions. Nothing for any other run. +class RunQuotaNotice extends StatelessWidget { + const RunQuotaNotice({ + super.key, + required this.run, + required this.gateway, + required this.onRunChanged, + this.now, + }); + + final JsonMap run; + final ApiGateway gateway; + final ValueChanged onRunChanged; + + /// The clock, for tests. + final DateTime? now; + + @override + Widget build(BuildContext context) { + if (!isWaitingQuotaStatus(run['status'])) return const SizedBox.shrink(); + final wait = runQuotaWait(run); + final meta = wait == null ? '' : quotaWaitMeta(wait, now: now); + final color = Theme.of(context).colorScheme.tertiary; + return Container( + key: const Key('run-quota-banner'), + width: double.infinity, + padding: const EdgeInsets.only(top: 8, bottom: 4), + child: Row( + children: [ + Icon(Icons.hourglass_bottom, color: color, size: 18), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Semantics( + header: true, + child: const Text( + runWaitingQuotaLabel, + style: TextStyle(fontWeight: FontWeight.w600), + ), + ), + if (meta.isNotEmpty) ...[ + const SizedBox(height: 2), + Text(meta, style: Theme.of(context).textTheme.bodySmall), + ], + ], + ), + ), + const SizedBox(width: 12), + ResumeQuotaRunAction( + run: run, + gateway: gateway, + onRunChanged: onRunChanged, + ), + ], + ), + ); + } +} diff --git a/app/lib/ui/status/run_status_icon.dart b/app/lib/ui/status/run_status_icon.dart index ad91ba06..9fc7bd33 100644 --- a/app/lib/ui/status/run_status_icon.dart +++ b/app/lib/ui/status/run_status_icon.dart @@ -3,7 +3,7 @@ import 'package:flutter/material.dart'; /// The shared status glyph whose tooltip and accessible name say the state. /// /// [state] is the normalised run state (`succeeded`, `failed`, `running`, -/// `waiting`, `queued`, `canceled`, `interrupted`, anything else unknown); +/// `waiting`, `waiting_quota`, `queued`, `canceled`, `interrupted`, anything else unknown); /// [label] is the word a person reads. Colours are the platform's dynamic /// system colours, so the glyph keeps its contrast in light and dark themes. class RunStatusIcon extends StatelessWidget { @@ -45,7 +45,8 @@ Color runStatusColor(String state, [ColorScheme? colorScheme]) { 'failed' => dark ? const Color(0xFFFF453A) : const Color(0xFFFF3B30), 'running' || 'active' => dark ? const Color(0xFF0A84FF) : const Color(0xFF007AFF), - 'waiting' => dark ? const Color(0xFFFFD60A) : const Color(0xFFFFCC00), + 'waiting' || + 'waiting_quota' => dark ? const Color(0xFFFFD60A) : const Color(0xFFFFCC00), 'interrupted' => dark ? const Color(0xFFFF9F0A) : const Color(0xFFFF9500), _ => const Color(0xFF8E8E93), }; @@ -58,6 +59,8 @@ IconData _materialIcon(String state) => switch (state) { 'canceled' => Icons.block, 'interrupted' => Icons.pause_circle_outline, 'waiting' => Icons.person_outline, + // Parked until a usage limit resets: a timer, not a person. + 'waiting_quota' => Icons.hourglass_bottom, 'queued' => Icons.schedule, _ => Icons.help_outline, }; diff --git a/app/test/features/pipelines/pipelines_screen_filter_test.dart b/app/test/features/pipelines/pipelines_screen_filter_test.dart index cab57568..347bc54c 100644 --- a/app/test/features/pipelines/pipelines_screen_filter_test.dart +++ b/app/test/features/pipelines/pipelines_screen_filter_test.dart @@ -29,7 +29,13 @@ void main() { await tester.tap(find.byKey(const Key('pipeline-filter'))); await tester.pumpAndSettle(); - await tester.ensureVisible(find.text('No schedules')); + // The status list (with waiting_quota) pushes scheduling below the + // lazily built part of the page: scroll to it. + await tester.dragUntilVisible( + find.text('No schedules'), + find.byType(ListView).last, + const Offset(0, -200), + ); await tester.pumpAndSettle(); await tester.tap(find.text('No schedules')); await tester.pump(); diff --git a/app/test/features/runs/actions/resume_quota_action_test.dart b/app/test/features/runs/actions/resume_quota_action_test.dart new file mode 100644 index 00000000..f4d83355 --- /dev/null +++ b/app/test/features/runs/actions/resume_quota_action_test.dart @@ -0,0 +1,96 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/attention/domain/attention_models.dart'; +import 'package:pipelines_app/features/runs/actions/cancel_eligibility.dart'; +import 'package:pipelines_app/features/runs/actions/cancel_wording.dart'; +import 'package:pipelines_app/features/runs/actions/resume_quota_action.dart'; +import 'package:pipelines_app/features/runs/domain/run_decisions.dart'; +import 'package:pipelines_app/features/runs/domain/run_models.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_actions.dart'; + +import 'cancel_test_support.dart'; + +JsonMap _parked({bool cancelRequested = false}) => { + 'id': 7, + 'title': 'Nightly build', + 'status': 'waiting_quota', + 'executing': false, + 'cancel_requested': cancelRequested, + 'quota_wait': { + 'resets_at': DateTime(2026, 12, 3, 9).toUtc().toIso8601String(), + 'resume_at': DateTime(2026, 12, 3, 9, 1).toUtc().toIso8601String(), + 'sequence': 2, + 'stage': 'implement', + 'account': 'work', + }, +}; + +Future> _pump( + WidgetTester tester, + FakeCancelGateway gateway, +) async { + final changed = []; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: RunDetailActions( + run: _parked(), + gateway: gateway, + onRunChanged: changed.add, + ), + ), + ), + ); + return changed; +} + +void main() { + test('a parked run is cancellable and resumable, never a decision', () { + final run = _parked(); + expect(canCancelRun(run), isTrue); + expect(canResumeQuotaRun(run), isTrue); + expect(canResumeQuotaRun(_parked(cancelRequested: true)), isFalse); + expect(canCancelRun(_parked(cancelRequested: true)), isFalse); + expect(canResumeQuotaRun({'id': 7, 'status': 'waiting'}), isFalse); + expect(attentionKindForRun(run), isNull); + expect(orderAttention([run]), isEmpty); + expect(pendingDecision(run), isNull); + }); + + testWidgets('Resume now sends resume_run and applies the reply', ( + tester, + ) async { + final gateway = FakeCancelGateway( + (type, fields) async => { + 'type': 'run', + 'run_detail': {'id': 7, 'status': 'running', 'executing': true}, + }, + ); + final changed = await _pump(tester, gateway); + expect(find.text('Waiting for usage limit'), findsOneWidget); + expect(find.textContaining('account work'), findsOneWidget); + expect(find.byKey(cancelActionKey), findsOneWidget); + await tester.tap(find.byKey(resumeQuotaActionKey)); + await tester.pumpAndSettle(); + expect(gateway.calls.single.type, 'resume_run'); + expect(gateway.calls.single.fields, {'run_id': 7}); + expect(changed.single['status'], 'running'); + }); + + testWidgets('a refused resume shows the server message', (tester) async { + final gateway = FakeCancelGateway( + (type, fields) async => + throw Exception('run 7 is not waiting for a usage limit'), + ); + final changed = await _pump(tester, gateway); + await tester.tap(find.byKey(resumeQuotaActionKey)); + await tester.pumpAndSettle(); + expect(find.byKey(resumeQuotaErrorKey), findsOneWidget); + expect( + find.textContaining('not waiting for a usage limit'), + findsOneWidget, + ); + expect(changed, isEmpty); + }); +} diff --git a/app/test/features/runs/domain/run_events_quota_test.dart b/app/test/features/runs/domain/run_events_quota_test.dart new file mode 100644 index 00000000..e401fc75 --- /dev/null +++ b/app/test/features/runs/domain/run_events_quota_test.dart @@ -0,0 +1,108 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/runs/domain/run_events.dart'; + +void main() { + const wait = { + 'resets_at': '2026-12-03T09:00:00Z', + 'resume_at': '2026-12-03T09:01:00Z', + 'sequence': 2, + 'stage': 'implement', + 'account': 'work', + }; + final running = { + 'id': 4, + 'pipeline_id': 1, + 'name': 'build', + 'status': 'running', + 'executing': true, + }; + + test('a running run parks with its wait and resumes without it', () { + final parked = foldRunEvent( + [running], + {'run_id': 4, 'status': 'waiting_quota', 'quota_wait': wait}, + ).runs.single; + expect(parked['status'], 'waiting_quota'); + expect(parked['executing'], isFalse); + expect(parked['quota_wait'], wait); + // A frame without a status keeps the wait. + final same = foldRunEvent( + [parked], + {'run_id': 4, 'current_stage': 'implement'}, + ).runs.single; + expect(same['quota_wait'], wait); + final resumed = foldRunEvent( + [parked], + {'run_id': 4, 'status': 'running'}, + ).runs.single; + expect(resumed['status'], 'running'); + expect(resumed['executing'], isTrue); + expect(resumed.containsKey('quota_wait'), isFalse); + }); + + test('a deferred run goes back to queued when resumed', () { + final deferred = { + ...running, + 'status': 'waiting_quota', + 'executing': false, + }; + final queued = foldRunEvent( + [deferred], + {'run_id': 4, 'status': 'queued'}, + ).runs.single; + expect(queued['status'], 'queued'); + expect(queued['executing'], isTrue); + final parkedAgain = foldRunEvent( + [queued], + {'run_id': 4, 'status': 'waiting_quota', 'quota_wait': wait}, + ).runs.single; + expect(parkedAgain['status'], 'waiting_quota'); + }); + + test('a parked run can be canceled and records the failure class', () { + final parked = {...running, 'status': 'waiting_quota', 'quota_wait': wait}; + final canceled = foldRunEvent( + [parked], + {'run_id': 4, 'status': 'canceled', 'failure_class': 'canceled'}, + ).runs.single; + expect(canceled['status'], 'canceled'); + expect(canceled['failure_class'], 'canceled'); + expect(canceled.containsKey('quota_wait'), isFalse); + // Terminal stays terminal. + final stale = foldRunEvent( + [canceled], + {'run_id': 4, 'status': 'waiting_quota'}, + ).runs.single; + expect(stale['status'], 'canceled'); + }); + + test('the detail folds the same fields and re-reads on parking', () { + final detail = foldRunEventDetail( + {...running, 'steps': []}, + { + 'run_id': 4, + 'status': 'failed', + 'failure_class': 'quota', + 'failure_reason': 'usage limit', + }, + )!; + expect(detail['failure_class'], 'quota'); + expect( + runDetailNeedsFullSync({'run_id': 4, 'status': 'waiting_quota'}), + isTrue, + ); + }); + + test('a new row from a parked frame keeps its wait', () { + final row = newRunSummaryFromFrame({ + 'run_id': 9, + 'pipeline_id': 1, + 'name': 'build', + 'status': 'waiting_quota', + 'quota_wait': wait, + })!; + expect(row['executing'], isFalse); + expect(row['quota_wait'], wait); + expect(row['failure_class'], ''); + }); +} diff --git a/app/test/features/runs/domain/run_quota_test.dart b/app/test/features/runs/domain/run_quota_test.dart new file mode 100644 index 00000000..ae1b9a9f --- /dev/null +++ b/app/test/features/runs/domain/run_quota_test.dart @@ -0,0 +1,130 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/pipelines/pipeline_format.dart' + show runStateLabel; +import 'package:pipelines_app/features/runs/domain/run_failure_class.dart'; +import 'package:pipelines_app/features/runs/domain/run_models.dart'; +import 'package:pipelines_app/features/runs/domain/run_outcome_line.dart'; +import 'package:pipelines_app/features/runs/domain/run_quota.dart'; + +String _local(int hour, int minute) => + DateTime(2026, 12, 3, hour, minute).toUtc().toIso8601String(); + +void main() { + final now = DateTime(2026, 12, 3, 8); + final parked = { + 'id': 4, + 'status': 'waiting_quota', + 'quota_wait': { + 'resets_at': _local(9, 0), + 'resume_at': _local(9, 1), + 'sequence': 3, + 'stage': 'implement', + 'account': 'work', + }, + }; + + test('quota_wait parses and reads in local time', () { + final wait = runQuotaWait(parked)!; + expect(wait.sequence, 3); + expect(wait.stage, 'implement'); + expect(wait.account, 'work'); + expect(quotaResumeText(wait, now: now), 'resumes 09:01'); + expect( + quotaWaitMeta(wait, now: now), + 'Limit resets 09:00 · run resumes 09:01 · account work · at implement', + ); + expect(runQuotaWait({'status': 'waiting_quota'}), isNull); + }); + + test('a resume on another day carries its date', () { + final later = DateTime(2026, 12, 4, 9, 1); + expect(quotaClockText(later, now: now), '4 Dec 09:01'); + }); + + test('waiting_quota is its own state with its own words', () { + expect(runStateOf('waiting_quota'), 'waiting_quota'); + expect(runStates, contains('waiting_quota')); + expect(runStateLabel('waiting_quota'), 'Waiting for usage limit'); + expect( + runStatusLabel(parked, now: now), + 'Waiting for usage limit · resumes 09:01', + ); + expect( + runStatusLabel({'status': 'waiting_quota'}), + 'Waiting for usage limit', + ); + final filtered = filterRuns( + [ + parked, + {'id': 5, 'status': 'waiting'}, + ], + statuses: {'waiting_quota'}, + ); + expect(filtered.map((run) => run['id']), [4]); + }); + + test('failure classes use the server wording', () { + expect(runFailureClassLabel({'failure_class': 'quota'}), 'usage limit'); + expect( + runFailureClassLabel({'failure_class': 'loop_exhausted'}), + 'loop limit reached', + ); + expect( + runFailureClassLabel({'failure_class': 'budget'}), + 'budget exhausted', + ); + expect(runFailureClassLabel({'failure_class': 'new_kind'}), 'new kind'); + expect(runFailureClassLabel({}), isNull); + expect(runFailureClassLabels.length, 12); + }); + + test('the outcome line leads with the failure class', () { + final line = runOutcomeLine({ + 'status': 'failed', + 'failure_class': 'quota', + 'failure_reason': 'Claude usage limit\nreset at 9', + })!; + expect(line.line, 'Failed · usage limit: Claude usage limit'); + expect(line.full, 'Failed · usage limit: Claude usage limit\nreset at 9'); + expect(line.failed, isTrue); + expect( + runOutcomeLine({'status': 'failed', 'failure_class': 'timeout'})?.line, + 'Failed · timed out', + ); + // The catch-all class adds nothing to the reason. + expect( + runOutcomeLine({ + 'status': 'failed', + 'failure_class': 'other', + 'failure_reason': 'exit 2', + })?.line, + 'exit 2', + ); + expect( + runOutcomeLine({'status': 'failed', 'failure_class': 'other'}), + isNull, + ); + }); + + test('a capped run shows its budget', () { + expect( + runBudgetText({ + 'budget': {'limit_usd': 5, 'spent_usd': 1.25, 'source': 'run'}, + }), + r'$1.25 of $5.00 budget', + ); + expect( + runBudgetText({ + 'budget': {'limit_usd': 2, 'spent_usd': 0, 'source': 'server'}, + }), + r'$0.00 of $2.00 budget (server default)', + ); + expect( + runBudgetText({ + 'budget': {'limit_usd': 0}, + }), + isNull, + ); + expect(runBudgetText({}), isNull); + }); +} diff --git a/app/test/features/runs/ui/runs_sheets_test.dart b/app/test/features/runs/ui/runs_sheets_test.dart index 50a67cf0..e9910cd1 100644 --- a/app/test/features/runs/ui/runs_sheets_test.dart +++ b/app/test/features/runs/ui/runs_sheets_test.dart @@ -120,8 +120,9 @@ void main() { await tester.tap(find.byKey(const ValueKey('runs.filter'))); await tester.pumpAndSettle(); - // Seven statuses may be combined: those keep their checkboxes. - expect(find.byType(CheckboxListTile), findsNWidgets(7)); + // Eight statuses (with waiting_quota) may be combined: those keep their + // checkboxes. + expect(find.byType(CheckboxListTile), findsNWidgets(8)); final anyTime = find.widgetWithText(ListTile, 'Any time'); expect(anyTime, findsOneWidget); expect( diff --git a/docs/cli.md b/docs/cli.md index 3f0fcf40..24f08313 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -331,6 +331,8 @@ Submitting activates included schedules, so review them before publishing. | Rename a run | `title ID "TITLE" --json` | | Decide a waiting human stage | `decide ID [STAGE] --option KEY [--feedback TEXT] --json` | | Cancel | `cancel ID --json` | +| Resume a run parked for a usage limit | `resume ID --yes --json` | +| Default whole-run budget | `run-budget [USD\|off] --json` | | Connection and phone settings | `connection --json`, `ping --json` | | Server/ntfy status popup | `status --json` | | Usage statistics/charts | `stats --json` | @@ -350,7 +352,7 @@ printf '%s' '{"type":"get_pipeline","pipeline_id":1,"version":1}' | pipelines rp Existing protocol commands: `ping`, `list_pipelines` (optional `include_archived`), `get_pipeline`, `archive_pipeline`, `unarchive_pipeline`, `list_templates`, `validate`, `submit`, `run_pipeline`, `list_runs`, `get_run`, -`cancel_run`, `retry_run`, `decide_run`, `set_run_title`, `get_run_evidence`, +`cancel_run`, `retry_run`, `decide_run`, `resume_run`, `set_run_title`, `get_run_evidence`, `get_run_settings`, `set_run_settings`, `get_status`, `search`. `search` takes a `search` request object (`query`, with an optional `kind` and `limit`) and returns a `search_results` response whose ranked `results` each carry a stable `target` the client can open plus the typed payload @@ -1185,6 +1187,75 @@ bound is stored as a valid, credential-redacted preview envelope that preserves available stage limits and failure/format diagnostics and names the retained session instead of slicing to malformed JSON. +### Whole-run budgets + +A run can also carry a whole-run USD cap: `pipelines run ... --budget 5` (and +`retry ... --budget 5`; a retry otherwise keeps its source run's own budget), else +the server default set with `pipelines run-budget 5` (`run-budget off` removes it; +`run-budget` alone shows it). Every model stage's reported cost counts towards it. +At 80% the operator gets one `budget_warning` notification; at 100% the running +visit stops, the error edge is not followed and the run fails with failure class +`budget`. The run records `budget: {limit_usd, source: run|server, spent_usd, +warned}`; `inspect` prints it. Stage `budget_usd`/`budget_tokens` still cap each +stage on their own. Protocol: `run_pipeline`/`retry_run` take `budget_usd`; +`get_run_settings` and `set_run_settings` (`run_settings: {default_budget_usd}`) +reply `run_settings`. + +### Usage limits: `waiting_quota` + +A Claude stage refused for a subscription usage limit (the 5-hour or weekly +window) does not fail its run: + +1. The server records the account's limit and tries the same Claude account + auto-switch chats use (only when the stage's Claude home sets its own + `CLAUDE_CONFIG_DIR` and its auto-switch setting is on, see Claude account + switching). On a switch the same stage visit runs again at once on the new + account. +2. Otherwise the run is parked with status `waiting_quota`. The run (and its + `run_event` frames) carry `quota_wait: {resets_at, resume_at, sequence, stage, + account}`; the server resumes the interrupted visit at `resume_at` (the reset + plus one minute), also after a server restart. A parked run holds no executor + and no workspace reservation; if another run holds its workspace at resume + time it tries again a minute later. +3. The visit that runs again does not count against the stage's `max_visits` and + its `input.md` carries a `# Previous attempt` note saying it was interrupted by + the limit and that partial edits may be in the worktree. + +`pipelines resume ` (protocol `resume_run`) resumes a parked run now; +`pipelines cancel ` cancels it (failure class `canceled`). `pipelines wait` +keeps waiting through `waiting_quota`; `run --wait`/`retry --wait` return with the +parked run and a line saying when it resumes. An exhausted paid balance (an API +key's credit, OpenCode's quota error) has no reset of its own and still fails the +run with failure class `quota`; only that case says to top up the account. + +While an account is known to be limited, a new `run` or `retry` whose pipeline has +Claude stages is not launched into it. The request's `quota_policy` decides: +`defer` (the default, and the CLI's choice at an interactive prompt) creates the run +parked in `waiting_quota` with `sequence: 0`, starting at the reset; `refuse` (the +CLI's choice under `--json`/`--yes`) rejects it naming the reset time; `now` +starts it anyway. The CLI flags are `--defer` and `--now`. + +### Failure classes and error loops + +A run that did not succeed carries `failure_class`, written by the runner and +shown by `inspect`, `runs`, `wait`, `run --wait`, the app's failure line and +`stats` (`failure_classes` counts): `quota`, `loop_exhausted`, `timeout`, +`permission_denied`, `harness_error`, `blocked` (a stage routed to `#failure` on +its own outcome), `environment`, `canceled`, `interrupted`, `budget`, +`check_failed` (verification target or delivery gate) and `other`. Runs recorded +before the class existed read as `blocked`, `other`, `canceled` or `interrupted` +from their status. + +A Claude stage that answers `blocked` (or `error`) after the permission rules +refused one of its tool uses (`permission_denials` in Claude Code's result, or a +refused `tool_result`) fails with `permission_denied` naming the tool and path or +command, instead of being reported as the model's own block. Harness failures are +classified before an `error -> ` loop is followed: deterministic ones +(authentication, invalid arguments or model, a configuration the harness refuses, +a permission denial, the same empty readback twice) go to `#failure`; transient +ones (network, 5xx, overloaded, timeouts) wait 15 s, 1 min, then 4 min before the +next visit. + ### Result-first views Home shows retained result previews and completed visits alongside each run and diff --git a/internal/author/skill/SKILL.md b/internal/author/skill/SKILL.md index e17bc50d..e89eb337 100644 --- a/internal/author/skill/SKILL.md +++ b/internal/author/skill/SKILL.md @@ -31,7 +31,9 @@ interrupted, and 1 for a client error (unknown id, connection, `--timeout`). Do not poll with repeated `pipelines runs` calls, and do not tell the user a run is done, or will be reported, without a wait covering it. `wait` keeps blocking while a run is `waiting` on a human stage and prints how to answer it -(`pipelines decide --option KEY`, the user's choice only). +(`pipelines decide --option KEY`, the user's choice only), and through +`waiting_quota` (a usage limit; it resumes itself). Read `failure_class` +first (`references/debugging.md`). A run started from a repository's main checkout runs in its own worktree (`-runs/...`, branch `pipelines/run-...`); a failed run keeps that tree and diff --git a/internal/author/skill/references/control.md b/internal/author/skill/references/control.md index 9f41ffdc..51314886 100644 --- a/internal/author/skill/references/control.md +++ b/internal/author/skill/references/control.md @@ -59,6 +59,15 @@ transient environment or tooling problem, keeping `blocked -> #failure` for a criterion that genuinely cannot be met; that self-loop needs `limits` on the implementer, e.g. `{"max_visits":5,"on":["blocked_retryable"]}`. +Error edges are runner-policed too. A stage error that would fail the same way +again goes to `#failure` instead of following `error -> `: a +deterministic harness failure (authentication, an invalid argument or model, a +configuration the harness refuses), a tool permission denial, a spent run budget, +or the same empty-readback failure twice in a row. A transient one (network, +5xx/overloaded, timeouts) follows the self-loop after a backoff of 15 s, then 1 min, +then 4 min. A provider usage limit never follows the error edge: the run switches +Claude accounts or parks in `waiting_quota` (`references/debugging.md`). + Visit count, limit decision and original target are retained in `inspect --json`. Turn memory is run-local: there is no cross-run memory or hidden replay, and retries start fresh except for the completed prefix, the findings ledger and the diff --git a/internal/author/skill/references/debugging.md b/internal/author/skill/references/debugging.md index f682c1d0..1fb27d0d 100644 --- a/internal/author/skill/references/debugging.md +++ b/internal/author/skill/references/debugging.md @@ -10,6 +10,37 @@ 4. Verify the repair with a focused regression; run broader checks once relevant inputs settle. Do not raise retry/time budgets to hide a reproducible defect. +Read the run's `failure_class` first (in `inspect`, `runs`, `wait` and the app's +failure line; `stats` counts them): + +| class | meaning and next action | +|---|---| +| `quota` | provider usage/balance refused; a Claude window parks instead (below), so this means an exhausted paid balance or a failed park | +| `loop_exhausted` | a stage's visit limit or the 30-step cap; fix the cause the loop kept hitting | +| `timeout` | a stage attempt ran past its `timeout`; check whether work landed before raising it | +| `permission_denied` | the stage's tool use was refused (named in the diagnostic) and it gave up; widen `tools`/write paths or change the task | +| `harness_error` | the harness failed (transport, readback, cleanup); a deterministic one was not looped | +| `blocked` | a stage deliberately routed to `#failure` (its own outcome); read its handoff | +| `environment` | harness missing or signed out, workspace/env/delivery access problems | +| `budget` | the run's `--budget`/default run budget (or a stage budget) was spent | +| `check_failed` | a verification target or delivery gate check failed | +| `canceled`, `interrupted`, `other` | operator cancel, server stop, anything else | + +A Claude stage refused for a usage limit is never failed and never retried into +the limit. The server first switches the Claude home to another saved account +with usage left (when that home's auto-switch is on) and runs the visit again; +otherwise the run is parked in `waiting_quota` with `quota_wait.resets_at`/ +`resume_at` and resumes the same visit a minute after the reset, also after a +restart. The visit that runs again is told in `# Previous attempt` that it was +interrupted and that partial edits may be in the worktree. Do not retry or cancel a +parked run to "unstick" it: `pipelines wait ID` waits through it, +`pipelines resume ID --yes` resumes it now (only when the limit is known to be +lifted) and `pipelines cancel ID --yes` stops it. While an account is known to be +limited, `run`/`retry` under `--json`/`--yes` are refused with the reset time; +pass `--defer` to queue the run for the reset or `--now` only when you know the +limit is gone. A run's `--budget USD` (or the server's `pipelines run-budget`) +warns at 80% and stops at 100% with class `budget`. + `pipelines retry ID --yes --json` resumes the failed stage; `--stage KEY [--visit N]` picks a recorded stage, `--input-file FILE|-` merges a bounded JSON correction (shown to the stage as `# Operator correction`), `--version N` a published version of the diff --git a/internal/author/skill/references/format.md b/internal/author/skill/references/format.md index a957bac8..642ff1f9 100644 --- a/internal/author/skill/references/format.md +++ b/internal/author/skill/references/format.md @@ -173,6 +173,9 @@ edges are allowed. - `budget_usd`, `budget_tokens`: positive caps on reported usage, shared across attempts and visits of this stage; totals include cache reads and writes. Set only when the user asks or a measured visit exists (`references/practices.md`). + A whole-run cap is not a definition setting: it is the run's `--budget USD` or + the server default (`pipelines run-budget`), and every stage's cost counts + towards it (80% warning, stop with failure class `budget` at 100%). - `delivery=true`: the landing stage's gate (below), on any harness, or on a check stage. - `allow_workspace_changes=true`: lets a stage with `shell` but no `edit` leave file changes diff --git a/internal/author/skill/references/operations.md b/internal/author/skill/references/operations.md index 64d5e981..19a63cf2 100644 --- a/internal/author/skill/references/operations.md +++ b/internal/author/skill/references/operations.md @@ -92,7 +92,7 @@ Use the authoritative `CLI_PREFIX` from the prompt: without changing its input or steps. The stored prompt is unchanged, and listing/renaming never calls a model. - `CLI_PREFIX inspect RUN_ID`: compact summary — a header (status, outcome, - duration, diagnostic), one line per step (stage, status, outcome, duration, + duration, `failure_class`, diagnostic, run budget), one line per step (stage, status, outcome, duration, first diagnostic line), how to answer a `waiting` run and the final `# handoff` (bounded). `--step N` prints one step in full without its transcript (add `--transcripts` for it), `--transcripts` alone appends every transcript, and @@ -111,13 +111,19 @@ Use the authoritative `CLI_PREFIX` from the prompt: complete tool history. - `CLI_PREFIX decide RUN_ID [STAGE] --option KEY [--feedback TEXT] [--json]`: answer a run `waiting` on a `type=human` stage (`references/format.md`). +- A run in `waiting_quota` is parked for a provider usage limit and resumes on its + own after `quota_wait.resume_at`; `CLI_PREFIX resume RUN_ID --yes` resumes it now, + `cancel` stops it (`references/debugging.md`). `run`/`retry` take `--budget USD` + (whole-run cap) and `--now`/`--defer` for a known usage limit; + `CLI_PREFIX run-budget [USD|off]` shows or sets the server default run budget. - Without a terminal on stdin/stdout (an agent's shell, a pipe, CI) `run` behaves as `--json` and never opens the full-screen view, `tui` refuses, and every confirmation fails at once naming `--yes` instead of prompting: pass `run NAME "TASK" --json --yes` and `retry RUN_ID --yes --json`. - `CLI_PREFIX wait RUN_ID ...`: one line per run as it finishes (a failed run's stage and first diagnostic line); while a run waits on a human it prints - `waiting at STAGE — answer with: pipelines decide ID --option KEY` once (stderr + `waiting at STAGE — answer with: pipelines decide ID --option KEY` once and + waits through `waiting_quota` (the run resumes on its own) (stderr under `--json`). Exit status: 0 every run succeeded, 2 a run failed, was canceled or interrupted, 1 a client error (unknown id, connection, `--timeout` reached; the run is untouched). `run --wait` and `retry --wait` also exit 2 diff --git a/internal/claude/refusal.go b/internal/claude/refusal.go index caa1684d..005fb941 100644 --- a/internal/claude/refusal.go +++ b/internal/claude/refusal.go @@ -224,3 +224,16 @@ func (c *Chat) noteRejectedLocked(email string, until time.Time) { c.rejectedUntil[email] = until } } + +// IsUsageLimitText reports whether text is Claude Code's usage-limit refusal. +func IsUsageLimitText(text string) bool { return usageLimitText.MatchString(text) } + +// UsageLimitResetIn reads the reset time a usage-limit refusal's text names +// (as of at); ok is false when the text is not a usage-limit refusal or names +// no reset. Pipeline stages use it when no rate_limit_event said. +func UsageLimitResetIn(text string, at time.Time) (time.Time, bool) { + if !usageLimitText.MatchString(text) { + return time.Time{}, false + } + return usageLimitReset(text, at) +} diff --git a/internal/cli/app.go b/internal/cli/app.go index 1e20afea..e9433a48 100644 --- a/internal/cli/app.go +++ b/internal/cli/app.go @@ -62,6 +62,43 @@ type options struct { extraVisits int timeout, waitTimeout time.Duration stageModels stageModelFlags + // quotaNow / quotaDefer choose what run and retry do about a known usage + // limit; budgetUSD caps the whole run. + quotaNow, quotaDefer bool + budgetUSD float64 +} + +// quotaPolicy is the run/retry request's protocol.QuotaPolicy: --now starts +// anyway, --defer queues the run for the reset, and otherwise a person at a +// prompt gets the deferral while --json/--yes automation is refused, so an +// agent never burns a retry into a known limit by accident. +func (o *options) quotaPolicy() (string, error) { + switch { + case o.quotaNow && o.quotaDefer: + return "", fmt.Errorf("--now and --defer are exclusive") + case o.quotaNow: + return protocol.QuotaNow, nil + case o.quotaDefer: + return protocol.QuotaDefer, nil + case o.json || o.yes: + return protocol.QuotaRefuse, nil + } + return protocol.QuotaDefer, nil +} + +// quotaFlags registers --now, --defer and --budget for run and retry. +func quotaFlags(f *flag.FlagSet, o *options) { + f.BoolVar(&o.quotaNow, "now", false, "Start even though the Claude account is known to be out of usage until its reset") + f.BoolVar(&o.quotaDefer, "defer", false, "When the Claude account is known to be out of usage, queue the run to start at the reset (default at a prompt; --json/--yes refuse instead)") + f.Float64Var(&o.budgetUSD, "budget", 0, "Cap this run's reported model cost in USD (warns at 80%, stops at 100%; default: the server's run budget)") +} + +// quotaHint adds the CLI flags to a refusal for a known usage limit. +func quotaHint(err error) error { + if err != nil && strings.Contains(err.Error(), "not starting into a known limit") { + return fmt.Errorf("%w (pass --defer to queue it for the reset, or --now to start anyway)", err) + } + return err } // stageModelFlags collects the repeatable --stage-model STAGE=PROVIDER/MODEL @@ -173,6 +210,7 @@ func (a App) flags(command string) (*flag.FlagSet, *options) { f.Var(o.stageModels, "stage-model", "Override one stage's model; repeatable (STAGE=PROVIDER/MODEL); beats --model") f.BoolVar(&o.wait, "wait", false, "In JSON mode, wait for a terminal run state") f.DurationVar(&o.waitTimeout, "wait-timeout", 0, "Client limit for --wait after the run is admitted (0 waits until terminal); separate from per-request --timeout") + quotaFlags(f, o) case "runs": f.StringVar(&o.name, "pipeline", "", "Filter by exact pipeline name or ID") f.BoolVar(&o.yes, "yes", false, "Confirm `runs rm` without an interactive prompt") @@ -192,10 +230,11 @@ func (a App) flags(command string) (*flag.FlagSet, *options) { f.IntVar(&o.version, "version", 0, "Explicit published version of the same pipeline (default: source version)") f.StringVar(&o.retryInputFile, "input-file", "", "JSON object merged into the selected stage input; '-' reads stdin") f.StringVar(&o.notifyMode, "notify", "auto", "Notifications for this retry: auto, on, or off") + quotaFlags(f, o) case "inspect": f.IntVar(&o.step, "step", 0, "Show one step (its sequence number) in full, without its transcript") f.BoolVar(&o.transcripts, "transcripts", false, "Include stage transcripts (long)") - case "cancel", "draft-delete": + case "cancel", "draft-delete", "resume": f.BoolVar(&o.yes, "yes", false, "Confirm this action without an interactive prompt") case "retention": f.StringVar(&o.db, "db", "", "Existing database path (default: standard data directory)") @@ -607,6 +646,12 @@ func (a App) Run(ctx context.Context, args []string) error { } fmt.Fprintln(a.Out, line) } + if u.WaitingQuota > 0 { + fmt.Fprintf(a.Out, "%d run(s) waiting for a usage limit to reset\n", u.WaitingQuota) + } + if line := failureClassLine(u.FailureClasses); line != "" { + fmt.Fprintln(a.Out, "Why runs did not succeed: "+line) + } fmt.Fprint(a.Out, "\nPipeline\tRuns\tSucceeded\tFailed\tActive\n") for _, p := range u.Pipelines { fmt.Fprintf(a.Out, "%s\t%d\t%d\t%d\t%d\n", p.Name, p.Total, p.Succeeded, p.Failed, p.Active) @@ -845,7 +890,14 @@ func (a App) Run(ctx context.Context, args []string) error { } case "runs": for _, run := range r.Runs { - fmt.Fprintf(a.Out, "%d\t%s\t%s\tv%d\t%s\n", run.ID, run.Label(), run.Name, run.Version, run.Status) + status := run.Status + if run.FailureClass != "" && run.Status != protocol.RunStatusCanceled { + status += " (" + protocol.FailureClassLabel(run.FailureClass) + ")" + } + if run.QuotaWait != nil { + status += " (resumes " + localClock(run.QuotaWait.ResumeAt) + ")" + } + fmt.Fprintf(a.Out, "%d\t%s\t%s\tv%d\t%s\n", run.ID, run.Label(), run.Name, run.Version, status) } case "ping": fmt.Fprintln(a.Out, "Connected ·", r.Time) @@ -1038,7 +1090,11 @@ func (a App) Run(ctx context.Context, args []string) error { if o.retryVisit < 0 { return fmt.Errorf("--visit must be positive") } - message := protocol.Message{Type: typeName, RunID: id, RequestKey: key, RetryMode: o.retryMode, RetryStage: o.retryStage, RetryVisit: o.retryVisit, RetryVersion: o.version, RetryInput: retryInput, NotifyMode: o.notifyMode} + policy, err := o.quotaPolicy() + if err != nil { + return err + } + message := protocol.Message{Type: typeName, RunID: id, RequestKey: key, RetryMode: o.retryMode, RetryStage: o.retryStage, RetryVisit: o.retryVisit, RetryVersion: o.version, RetryInput: retryInput, NotifyMode: o.notifyMode, QuotaPolicy: policy, BudgetUSD: o.budgetUSD} if o.extraVisits != 0 { if o.extraVisits < 1 || o.extraVisits > 5 { return fmt.Errorf("--extra-visits must be from 1 to 5") @@ -1052,7 +1108,10 @@ func (a App) Run(ctx context.Context, args []string) error { } r, err := call(message) if err != nil { - return err + return quotaHint(err) + } + if r.RunDetail != nil && r.RunDetail.Status == protocol.RunStatusWaitingQuota { + a.notice(quotaWaitLine(r.RunDetail)) } return a.finishRun(ctx, r, o, call) } @@ -1069,6 +1128,62 @@ func (a App) Run(ctx context.Context, args []string) error { return a.inspect(r.RunDetail, o) } return a.output(r.RunDetail) + case "resume": + value, err := one() + if err != nil { + return err + } + id, err := strconv.ParseInt(value, 10, 64) + if err != nil || id <= 0 { + return fmt.Errorf("run ID must be positive") + } + if err := a.confirmAction(fmt.Sprintf("Resume run #%d now, before its usage limit is known to have reset?", id), o.yes); err != nil { + return err + } + r, err := call(protocol.Message{Type: protocol.ResumeRun, RunID: id}) + if err != nil { + return err + } + if r.RunDetail == nil { + return fmt.Errorf("server did not return run detail") + } + if o.json { + return a.output(r.RunDetail) + } + _, err = fmt.Fprintf(a.Out, "Resumed run #%d: %s\n", r.RunDetail.ID, r.RunDetail.Status) + return err + case "run-budget": + if len(pos) > 1 { + return fmt.Errorf("run-budget takes at most one value: USD or off") + } + request := protocol.Message{Type: protocol.GetRunSettings} + if len(pos) == 1 { + value := strings.TrimSpace(strings.TrimPrefix(pos[0], "$")) + limit := 0.0 + if value != "off" && value != "0" { + limit, err = strconv.ParseFloat(value, 64) + if err != nil || limit <= 0 { + return fmt.Errorf("run-budget takes a positive USD amount or off") + } + } + request = protocol.Message{Type: protocol.SetRunSettings, RunSettings: &protocol.RunSettings{DefaultBudgetUSD: limit}} + } + r, err := call(request) + if err != nil { + return err + } + if r.RunSettings == nil { + return fmt.Errorf("server did not return run settings; update pipelines-server") + } + if o.json { + return a.output(r.RunSettings) + } + if r.RunSettings.DefaultBudgetUSD <= 0 { + _, err = fmt.Fprintln(a.Out, "Default run budget: off (runs are capped only by their own --budget and their stages' budget_usd)") + } else { + _, err = fmt.Fprintf(a.Out, "Default run budget: $%.2f per run (warns at 80%%, stops at 100%%)\n", r.RunSettings.DefaultBudgetUSD) + } + return err case "decide": if len(pos) < 1 || len(pos) > 2 { return fmt.Errorf("decide requires a run ID and an optional stage key") @@ -1403,7 +1518,15 @@ func (a App) run(ctx context.Context, pos []string, o *options, call callFunc, r if o.wait || o.key != "" || o.version > 0 { return fmt.Errorf("--wait, --request-key and --version require --json") } - _, err := tea.NewProgram(tui.NewRun(ctx, o.url, tui.RunOptions{Pipeline: o.name, Prompt: o.prompt, Title: o.title, Workspace: workspace, Yes: o.yes, AllowTools: o.allow, WritePaths: paths, Model: o.model, StageModels: o.stageModels, NotifyMode: o.notifyMode, OutputFormat: o.outputFormat}), tea.WithContext(ctx), tea.WithAltScreen()).Run() + policy, err := o.quotaPolicy() + if err != nil { + return err + } + _, err = tea.NewProgram(tui.NewRun(ctx, o.url, tui.RunOptions{Pipeline: o.name, Prompt: o.prompt, Title: o.title, Workspace: workspace, Yes: o.yes, AllowTools: o.allow, WritePaths: paths, Model: o.model, StageModels: o.stageModels, NotifyMode: o.notifyMode, OutputFormat: o.outputFormat, QuotaPolicy: policy, BudgetUSD: o.budgetUSD}), tea.WithContext(ctx), tea.WithAltScreen()).Run() + return err + } + policy, err := o.quotaPolicy() + if err != nil { return err } if o.name == "" || strings.TrimSpace(o.prompt) == "" { @@ -1425,9 +1548,12 @@ func (a App) run(ctx context.Context, pos []string, o *options, call callFunc, r if key == "" { key = fmt.Sprintf("cli-%d-%d", os.Getpid(), time.Now().UnixNano()) } - r, err := call(protocol.Message{Type: protocol.RunPipeline, PipelineID: p.ID, Version: version, RequestKey: key, Workspace: workspace, Title: o.title, Input: map[string]any{"prompt": o.prompt}, AllowTools: o.allow, WritePaths: paths, Model: o.model, StageModels: o.stageModels, NotifyMode: o.notifyMode, OutputFormat: o.outputFormat}) + r, err := call(protocol.Message{Type: protocol.RunPipeline, PipelineID: p.ID, Version: version, RequestKey: key, Workspace: workspace, Title: o.title, Input: map[string]any{"prompt": o.prompt}, AllowTools: o.allow, WritePaths: paths, Model: o.model, StageModels: o.stageModels, NotifyMode: o.notifyMode, OutputFormat: o.outputFormat, QuotaPolicy: policy, BudgetUSD: o.budgetUSD}) if err != nil { - return err + return quotaHint(err) + } + if r.RunDetail != nil && r.RunDetail.Status == protocol.RunStatusWaitingQuota { + a.notice(quotaWaitLine(r.RunDetail)) } return a.finishRun(ctx, r, o, call) } @@ -1494,6 +1620,9 @@ func (a App) finishRun(ctx context.Context, r protocol.Message, o *options, call if hint := waitingHint(r.RunDetail); hint != "" { message += "; " + hint } + if line := quotaWaitLine(r.RunDetail); line != "" { + message += "; " + line + } return &StatusError{Code: WaitRunsUnsuccessful, Message: message} } return nil @@ -1540,6 +1669,10 @@ func (a App) wait(ctx context.Context, pos []string, o *options, call callFunc) announced := map[int64]string{} onActive := func(r protocol.Message) { hint := waitingHint(r.RunDetail) + if hint == "" { + // A run parked for a usage limit resumes on its own; say when. + hint = quotaWaitLine(r.RunDetail) + } if hint == "" || announced[r.RunDetail.ID] == hint { return } @@ -1658,7 +1791,7 @@ func runInProgress(status string) bool { // runInProgress plus a run parked on a human decision (waiting), which has not // finished either. func runUnfinished(status string) bool { - return runInProgress(status) || status == protocol.RunStatusWaiting + return runInProgress(status) || status == protocol.RunStatusWaiting || status == protocol.RunStatusWaitingQuota } // runIDs extracts the ids of the runs still active when a wait limit passed. @@ -1695,6 +1828,9 @@ func waitLine(d *protocol.RunDetail) string { if outcome := strings.TrimSpace(d.Outcome); outcome != "" { line += " (" + outcome + ")" } + if d.FailureClass != "" && d.Status != protocol.RunStatusCanceled { + line += " [" + d.FailureClass + "]" + } if stage := strings.TrimSpace(d.CurrentStage); stage != "" { line += " · " + stage } diff --git a/internal/cli/commands.go b/internal/cli/commands.go index d28ffb96..8caf7cbd 100644 --- a/internal/cli/commands.go +++ b/internal/cli/commands.go @@ -21,13 +21,15 @@ var usage = map[string]string{ "import": "import [FILE.zip] [--all] [--on-conflict ask|keep|both|import] [--yes] [--json]", "templates": "templates [--json]", "template": "template [--source | --json]", - "run": "run [name|id] [prompt] [--yes] [--title TITLE] [--model PROVIDER/MODEL] [--stage-model STAGE=PROVIDER/MODEL ...] [--json [--wait [--wait-timeout DURATION]]]", + "run": "run [name|id] [prompt] [--yes] [--title TITLE] [--model PROVIDER/MODEL] [--stage-model STAGE=PROVIDER/MODEL ...] [--budget USD] [--now | --defer] [--json [--wait [--wait-timeout DURATION]]]", "runs": "runs [--pipeline NAME] [--json] | runs rm [run-id ...] [--yes] [--json]", "inspect": "inspect [--step N] [--transcripts] [--json]", "wait": "wait [run-id ...] [--timeout DURATION] [--json]", "cancel": "cancel [--json]", + "resume": "resume [--yes] [--json]", + "run-budget": "run-budget [USD|off] [--json]", "decide": "decide [stage] --option KEY [--feedback TEXT] [--json]", - "retry": "retry [--yes] [--mode resume|restart] [--stage KEY [--visit N]] [--extra-visits N [--stage KEY]] [--version N] [--input-file FILE|-] [--json [--wait [--wait-timeout DURATION]]]", + "retry": "retry [--yes] [--mode resume|restart] [--stage KEY [--visit N]] [--extra-visits N [--stage KEY]] [--version N] [--input-file FILE|-] [--budget USD] [--now | --defer] [--json [--wait [--wait-timeout DURATION]]]", "title": "title \"\" [--json]", "debug": "debug <run-id> [--json | --no-open]", "chat-adopt": "chat-adopt <session-id> [--harness opencode|claude|codex] [--title TEXT] [--json]", @@ -63,6 +65,8 @@ var notes = map[string]string{ "title": "Rename a run's operator-facing title after the fact without touching its input, steps or execution. The title is collapsed to a single bounded line and recorded as explicitly set. `pipelines runs` and `pipelines inspect` then show it.", "inspect": "Print a compact summary of a run: status, outcome and duration, one line per step (stage, status, outcome, duration, first diagnostic line), how to answer a run waiting on a person and the bounded final handoff. --step N prints that step in full (output, diagnostic, file changes, artifacts) without its transcript; --transcripts adds transcripts (to every step, or to --step N); --json prints the complete run record (or just --step N), including transcripts.", "wait": "Block until each named run reaches a terminal status - succeeded, failed, canceled or interrupted, and also through a run waiting on a person - then print one line per run with its id, status and outcome, its stage, how long it took and, for an unsuccessful run, the failing stage and the first line of its diagnostic. While a run waits on a person it prints once how to answer: waiting at STAGE — answer with: pipelines decide ID --option KEY (on stderr under --json). Several ids wait together in one command. Exit status: 0 when every run succeeded; 2 when any run failed, was canceled or interrupted (every run is still reported); 1 for a client-side failure: an unknown run id, a connection that could not be established, or --timeout expiring while a run is still active. A timeout says so plainly, never cancels, retries or otherwise touches a run, and is never reported as its outcome. Read-only: it needs no workspace, is not refused by the workspace guard and writes nothing. --json prints the final run envelope instead of the line (one envelope for one id, an array for several).", + "resume": "Resume a run parked in waiting_quota now instead of at its usage-limit reset: the interrupted stage visit runs again (told it was interrupted and that partial edits may be in the worktree), or a run deferred before its first stage starts. The server resumes parked runs on its own a minute after the reset, also after a restart; use this only when you know the limit is lifted (for example you switched Claude accounts). Cancel a parked run with pipelines cancel.", + "run-budget": "Show or set the server's default whole-run budget in USD (off removes it). A run without its own --budget is capped at this amount of reported model cost: the operator is notified at 80% and the run stops with failure class budget at 100%. Stage budget_usd/budget_tokens in a definition still cap each stage.", "decide": "Choose an option for a run waiting on a human stage. The run must be `waiting`; the option must be one of that stage's non-error edges. The stage is inferred from the run's current stage unless named. The choice and optional --feedback are recorded as the step's evidence (visible in inspect and the TUI) and the run resumes along the chosen edge. An unknown option is refused with the valid list; a repeated decision for an already-decided visit does not double-apply. Works across a server restart because the wait is persisted.", "debug": "Open a fresh configured harness conversation to investigate a run using inspect/show/runs CLI queries. --harness opencode|pi|nvim chooses another configured harness or read-only nvim packet. Does not resume implementation or retry. --json returns the prompt without launching anything.", "rpc": "Accepts a JSON protocol envelope; '-' reads stdin. Every TUI server operation is available here too. Mutating commands are not dry runs. The omni-search command is `search` (fields query, optional kind and limit) and answers with ranked `search_results`.", diff --git a/internal/cli/inspect.go b/internal/cli/inspect.go index 67d14620..b5ea58f1 100644 --- a/internal/cli/inspect.go +++ b/internal/cli/inspect.go @@ -37,9 +37,15 @@ func inspectSummary(d *protocol.RunDetail) string { if d.RetryOf > 0 { fmt.Fprintf(&b, "retry of run %d (%s)\n", d.RetryOf, d.RetryMode) } + if d.FailureClass != "" { + b.WriteString("failure class: " + d.FailureClass + " (" + protocol.FailureClassLabel(d.FailureClass) + ")\n") + } if line := firstLine(d.Diagnostic); line != "" { b.WriteString("diagnostic: " + line + "\n") } + if budget := d.Budget; budget != nil { + fmt.Fprintf(&b, "budget: $%.2f of $%.2f (%s)\n", budget.SpentUSD, budget.LimitUSD, budget.Source) + } if len(d.Steps) > 0 { b.WriteString("\nsteps:\n") } @@ -62,6 +68,9 @@ func inspectSummary(d *protocol.RunDetail) string { } b.WriteString("\nextra visits: " + strings.Join(parts, ", ") + "\n") } + if next := quotaWaitLine(d); next != "" { + b.WriteString("\n" + next + "\n") + } if handoff := finalHandoff(d); handoff != "" { b.WriteString("\nhandoff:\n" + indent(handoff) + "\n") } else if preview := strings.TrimSpace(d.ResultPreview); preview != "" { @@ -227,6 +236,14 @@ func failureDetail(d *protocol.RunDetail) (stage, diagnostic string) { // failureNote names the failing stage and its first diagnostic line. func failureNote(d *protocol.RunDetail) string { + note := failureNoteText(d) + if d.FailureClass != "" && d.FailureClass != protocol.FailureCanceled && note != "" { + return "[" + d.FailureClass + "] " + note + } + return note +} + +func failureNoteText(d *protocol.RunDetail) string { stage, diagnostic := failureDetail(d) switch { case stage != "" && diagnostic != "": diff --git a/internal/cli/run_budget_cli_test.go b/internal/cli/run_budget_cli_test.go new file mode 100644 index 00000000..f48991f7 --- /dev/null +++ b/internal/cli/run_budget_cli_test.go @@ -0,0 +1,51 @@ +package cli_test + +import ( + "context" + "encoding/json" + "strconv" + "strings" + "testing" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +func TestCLIRunBudgetAndResume(t *testing.T) { + run, store, _ := setup(t) + if out, err := run("run-budget"); err != nil || !strings.Contains(out, "off") { + t.Fatal(out, err) + } + if _, err := run("run-budget", "-3"); err == nil { + t.Fatal("a negative default budget was accepted") + } + out, err := run("run-budget", "12.5", "--json") + if err != nil { + t.Fatal(err) + } + var settings protocol.RunSettings + if err := json.Unmarshal([]byte(out), &settings); err != nil || settings.DefaultBudgetUSD != 12.5 { + t.Fatal(out, err) + } + if _, err := store.Submit(context.Background(), "human-budget", cliHumanSource); err != nil { + t.Fatal(err) + } + // A run's own --budget beats the default and is recorded on the run. + out, err = run("run", "human-budget", "ship it", "--json", "--yes", "--budget", "3") + if err != nil { + t.Fatal(err) + } + var started protocol.Message + if err := json.Unmarshal([]byte(out), &started); err != nil || started.RunDetail == nil { + t.Fatal(out, err) + } + if b := started.RunDetail.Budget; b == nil || b.LimitUSD != 3 || b.Source != "run" { + t.Fatalf("run budget %+v", b) + } + // Only a run parked for a usage limit can be resumed. + if _, err := run("resume", strconv.FormatInt(started.RunDetail.ID, 10), "--yes"); err == nil || !strings.Contains(err.Error(), "not waiting for a usage limit") { + t.Fatal("resume of a run that is not parked:", err) + } + if _, err := run("cancel", strconv.FormatInt(started.RunDetail.ID, 10), "--yes"); err != nil { + t.Fatal(err) + } +} diff --git a/internal/cli/run_quota.go b/internal/cli/run_quota.go new file mode 100644 index 00000000..234102cf --- /dev/null +++ b/internal/cli/run_quota.go @@ -0,0 +1,52 @@ +package cli + +import ( + "fmt" + "strings" + "time" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// localClock renders an RFC 3339 instant as local wall-clock time ("15:04", +// with the date when it is not today). +func localClock(value string) string { + at, err := time.Parse(time.RFC3339, value) + if err != nil { + return value + } + at = at.Local() + if y, m, d := at.Date(); y == time.Now().Year() && m == time.Now().Month() && d == time.Now().Day() { + return at.Format("15:04") + } + return at.Format("15:04 on 2 Jan") +} + +// quotaWaitLine tells a reader (or agent) what a run parked for a usage +// limit does next and how to act on it; "" for any other run. +func quotaWaitLine(d *protocol.RunDetail) string { + if d == nil || d.Status != protocol.RunStatusWaitingQuota || d.QuotaWait == nil { + return "" + } + w := d.QuotaWait + what := "starts" + if w.Sequence > 0 { + what = "resumes stage " + w.Stage + } + account := "" + if w.Account != "" { + account = " of " + w.Account + } + return fmt.Sprintf("run %d is waiting for the Claude usage limit%s to reset at %s; it %s automatically at %s — resume now: pipelines resume %d; cancel: pipelines cancel %d; wait: pipelines wait %d", d.ID, account, localClock(w.ResetsAt), what, localClock(w.ResumeAt), d.ID, d.ID, d.ID) +} + +// failureClassLine summarizes failure class counts in protocol order. +func failureClassLine(counts map[string]int) string { + var parts []string + for _, class := range protocol.FailureClasses { + if n := counts[class]; n > 0 { + parts = append(parts, fmt.Sprintf("%d %s", n, protocol.FailureClassLabel(class))) + } + } + return strings.Join(parts, " · ") +} diff --git a/internal/cli/run_quota_test.go b/internal/cli/run_quota_test.go new file mode 100644 index 00000000..395dae32 --- /dev/null +++ b/internal/cli/run_quota_test.go @@ -0,0 +1,59 @@ +package cli + +import ( + "errors" + "strings" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +func TestQuotaPolicyRefusesAutomationUnlessAsked(t *testing.T) { + for _, tc := range []struct { + o options + want string + }{ + {options{}, protocol.QuotaDefer}, + {options{json: true}, protocol.QuotaRefuse}, + {options{yes: true}, protocol.QuotaRefuse}, + {options{json: true, quotaDefer: true}, protocol.QuotaDefer}, + {options{yes: true, quotaNow: true}, protocol.QuotaNow}, + } { + if got, err := tc.o.quotaPolicy(); err != nil || got != tc.want { + t.Errorf("%+v: %q %v, want %q", tc.o, got, err, tc.want) + } + } + both := options{quotaNow: true, quotaDefer: true} + if _, err := both.quotaPolicy(); err == nil { + t.Fatal("--now with --defer was accepted") + } + refusal := quotaHint(errors.New("the Claude usage limit of a@b resets at 09:00 on 4 Dec; not starting into a known limit: ...")) + if !strings.Contains(refusal.Error(), "--defer") || !strings.Contains(refusal.Error(), "--now") { + t.Fatal(refusal) + } +} + +func TestQuotaWaitLineAndFailureClassWording(t *testing.T) { + reset := time.Now().Add(time.Hour).UTC() + parked := &protocol.RunDetail{RunSummary: protocol.RunSummary{ID: 7, Status: protocol.RunStatusWaitingQuota, QuotaWait: &protocol.RunQuotaWait{ResetsAt: reset.Format(time.RFC3339), ResumeAt: reset.Add(time.Minute).Format(time.RFC3339), Sequence: 3, Stage: "implement", Account: "a@example.com"}}} + line := quotaWaitLine(parked) + for _, want := range []string{"run 7", "a@example.com", "resumes stage implement", reset.Local().Format("15:04"), "pipelines resume 7", "pipelines cancel 7"} { + if !strings.Contains(line, want) { + t.Fatalf("%q lacks %q", line, want) + } + } + if !strings.Contains(inspectSummary(parked), "pipelines resume 7") { + t.Fatal("inspect does not say how to resume a parked run") + } + failed := &protocol.RunDetail{RunSummary: protocol.RunSummary{ID: 8, Status: "failed", FailureClass: protocol.FailurePermissionDenied, Diagnostic: "tool permission denied: Bash(git push)"}} + if note := failureNote(failed); !strings.HasPrefix(note, "[permission_denied]") { + t.Fatal(note) + } + if summary := inspectSummary(failed); !strings.Contains(summary, "failure class: permission_denied (permission denied)") { + t.Fatal(summary) + } + if line := failureClassLine(map[string]int{protocol.FailureQuota: 25, protocol.FailureBlocked: 3}); line != "25 usage limit · 3 blocked" { + t.Fatal(line) + } +} diff --git a/internal/pipeline/run_notifications.go b/internal/pipeline/run_notifications.go index 0b3201aa..fcb68c61 100644 --- a/internal/pipeline/run_notifications.go +++ b/internal/pipeline/run_notifications.go @@ -42,6 +42,9 @@ FROM pipeline_runs r JOIN pipelines p ON p.id=r.pipeline_id case "waiting": title = "Run needs your decision" body = "waiting for a human decision" + case protocol.RunStatusWaitingQuota: + title = "Run paused for a usage limit" + body = "waiting for the usage limit to reset" case "failed", "interrupted", "succeeded": if status == "failed" && failureKind == "expected" && mode != "on" { settings, err := readNotificationSettings(ctx, tx) diff --git a/internal/pipeline/run_quota.go b/internal/pipeline/run_quota.go new file mode 100644 index 00000000..b0e63bf9 --- /dev/null +++ b/internal/pipeline/run_quota.go @@ -0,0 +1,266 @@ +package pipeline + +import ( + "context" + "database/sql" + "fmt" + "strings" + "time" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// Usage-limit parking, failure classes and run budgets (see protocol +// run_quota.go). A parked run keeps everything it needs to continue in its +// own row, so it survives a restart without a goroutine: the reset and resume +// times, the interrupted visit (0 for a run deferred before its first stage), +// and for a deferred run its admitted launch request. + +func (s *Store) initRunQuota() error { + for _, column := range []string{"failure_class", "quota_resets_at", "quota_resume_at", "quota_stage", "quota_account", "deferred_json", "budget_source"} { + if err := s.addColumnIfMissing("pipeline_runs", column, "TEXT NOT NULL DEFAULT ''"); err != nil { + return err + } + } + for _, column := range []string{"quota_sequence", "budget_warned"} { + if err := s.addColumnIfMissing("pipeline_runs", column, "INTEGER NOT NULL DEFAULT 0"); err != nil { + return err + } + } + if err := s.addColumnIfMissing("pipeline_runs", "budget_usd", "REAL NOT NULL DEFAULT 0"); err != nil { + return err + } + // quota_limits remembers, per Claude account, until when a stage was + // refused for usage, so a new run or retry is not launched into it. + _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS quota_limits (account TEXT PRIMARY KEY, resets_at TEXT NOT NULL)`) + return err +} + +// defaultFailureClass is the class of a run that stopped without the runner +// naming one: a cancel, an interruption, a deliberate #failure route +// (blocked) or anything else. +func defaultFailureClass(status, failureKind string) string { + switch status { + case protocol.RunStatusCanceled: + return protocol.FailureCanceled + case "interrupted": + return protocol.FailureInterrupted + case "failed": + if failureKind == "expected" { + return protocol.FailureBlocked + } + return protocol.FailureOther + } + return "" +} + +// failureClassCounts counts finished unsuccessful runs by failure class. +func failureClassCounts(ctx context.Context, tx *sql.Tx) (map[string]int, error) { + rows, err := tx.QueryContext(ctx, `SELECT status,failure_kind,failure_class,COUNT(*) FROM pipeline_runs WHERE status IN ('failed','canceled','interrupted') GROUP BY status,failure_kind,failure_class`) + if err != nil { + return nil, err + } + defer rows.Close() + counts := map[string]int{} + for rows.Next() { + var status, kind, class string + var n int + if err := rows.Scan(&status, &kind, &class, &n); err != nil { + return nil, err + } + if class == "" { + class = defaultFailureClass(status, kind) + } + counts[class] += n + } + if err := rows.Err(); err != nil { + return nil, err + } + if len(counts) == 0 { + return nil, nil + } + return counts, nil +} + +// SetRunFailureClass records the runner's classification of an unfinished +// run just before it is finished; FinishRun keeps it for a failure and +// clears it for a success. +func (s *Store) SetRunFailureClass(ctx context.Context, id int64, class string) error { + _, err := s.db.ExecContext(ctx, `UPDATE pipeline_runs SET failure_class=? WHERE id=? AND finished_at IS NULL`, class, id) + return err +} + +func quotaTime(t time.Time) string { + if t.IsZero() { + return "" + } + return t.UTC().Format(time.RFC3339) +} + +// ParkRunForQuota parks an executing run in waiting_quota. sequence is the +// interrupted visit (its step is already finished as failed) or 0 for a run +// deferred before its first stage, whose launch request is deferred. +func (s *Store) ParkRunForQuota(ctx context.Context, id int64, sequence int, stageKey, account string, resetsAt, resumeAt time.Time, diagnostic, deferred string) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + if err := affected(tx.ExecContext(ctx, `UPDATE pipeline_runs SET status=?,quota_resets_at=?,quota_resume_at=?,quota_sequence=?,quota_stage=?,quota_account=?,deferred_json=?,diagnostic=?,current_stage=CASE WHEN ?<>'' THEN ? ELSE current_stage END +WHERE id=? AND status IN ('queued','running') AND cancel_requested=0 AND cleanup_unconfirmed=0 +AND NOT EXISTS(SELECT 1 FROM run_steps WHERE run_id=pipeline_runs.id AND agent_active=1)`, + protocol.RunStatusWaitingQuota, quotaTime(resetsAt), quotaTime(resumeAt), sequence, stageKey, account, deferred, diagnostic, stageKey, stageKey, id)); err != nil { + return fmt.Errorf("%w: %v", ErrInvalidRunTransition, err) + } + if err := enqueueRunTransitionNotification(ctx, tx, id); err != nil { + return err + } + return tx.Commit() +} + +// QuotaParking is a parked run's resume record. +type QuotaParking struct { + RunID int64 + Sequence int + Stage string + Account string + ResetsAt time.Time + ResumeAt time.Time + Deferred string +} + +func scanQuotaParking(row interface{ Scan(...any) error }) (QuotaParking, error) { + var p QuotaParking + var resets, resume string + if err := row.Scan(&p.RunID, &p.Sequence, &p.Stage, &p.Account, &resets, &resume, &p.Deferred); err != nil { + return p, err + } + p.ResetsAt, _ = time.Parse(time.RFC3339, resets) + p.ResumeAt, _ = time.Parse(time.RFC3339, resume) + return p, nil +} + +// QuotaParkedRuns lists every run parked in waiting_quota. +func (s *Store) QuotaParkedRuns(ctx context.Context) ([]QuotaParking, error) { + rows, err := s.db.QueryContext(ctx, `SELECT id,quota_sequence,quota_stage,quota_account,quota_resets_at,quota_resume_at,deferred_json FROM pipeline_runs WHERE status=? AND cancel_requested=0 ORDER BY id`, protocol.RunStatusWaitingQuota) + if err != nil { + return nil, err + } + defer rows.Close() + var parked []QuotaParking + for rows.Next() { + p, err := scanQuotaParking(rows) + if err != nil { + return nil, err + } + parked = append(parked, p) + } + return parked, rows.Err() +} + +// UnparkQuotaRun moves a parked run back to running and returns its resume +// record. It fails with ErrInvalidRunTransition when the run is not parked +// (already resumed, canceled or deleted), so a resume happens at most once. +func (s *Store) UnparkQuotaRun(ctx context.Context, id int64) (QuotaParking, error) { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return QuotaParking{}, err + } + defer tx.Rollback() + p, err := scanQuotaParking(tx.QueryRowContext(ctx, `SELECT id,quota_sequence,quota_stage,quota_account,quota_resets_at,quota_resume_at,deferred_json FROM pipeline_runs WHERE id=? AND status=? AND cancel_requested=0`, id, protocol.RunStatusWaitingQuota)) + if err == sql.ErrNoRows { + return QuotaParking{}, fmt.Errorf("%w: run %d is not waiting for a usage limit", ErrInvalidRunTransition, id) + } + if err != nil { + return QuotaParking{}, err + } + status := protocol.RunStatusRunning + if p.Sequence == 0 { + status = protocol.RunStatusQueued + } + if err := affected(tx.ExecContext(ctx, `UPDATE pipeline_runs SET status=?,quota_resets_at='',quota_resume_at='',quota_sequence=0,quota_stage='',deferred_json='',diagnostic='' WHERE id=? AND status=?`, status, id, protocol.RunStatusWaitingQuota)); err != nil { + return QuotaParking{}, err + } + return p, tx.Commit() +} + +// RecordQuotaLimit remembers that account is out of usage until resetsAt. +func (s *Store) RecordQuotaLimit(ctx context.Context, account string, resetsAt time.Time) error { + if strings.TrimSpace(account) == "" || resetsAt.IsZero() { + return nil + } + _, err := s.db.ExecContext(ctx, `INSERT INTO quota_limits(account,resets_at) VALUES(?,?) +ON CONFLICT(account) DO UPDATE SET resets_at=CASE WHEN excluded.resets_at>resets_at THEN excluded.resets_at ELSE resets_at END`, account, quotaTime(resetsAt)) + return err +} + +// QuotaLimit reports until when account is known to be out of usage; ok is +// false when no limit is known or it has already reset. +func (s *Store) QuotaLimit(ctx context.Context, account string, now time.Time) (time.Time, bool, error) { + var value string + err := s.db.QueryRowContext(ctx, `SELECT resets_at FROM quota_limits WHERE account=?`, account).Scan(&value) + if err == sql.ErrNoRows { + return time.Time{}, false, nil + } + if err != nil { + return time.Time{}, false, err + } + at, err := time.Parse(time.RFC3339, value) + if err != nil || !at.After(now) { + return time.Time{}, false, nil + } + return at, true, nil +} + +// AnyQuotaLimit reports whether any account is known to be limited past now, +// so admission resolves a run's account only when it can matter. +func (s *Store) AnyQuotaLimit(ctx context.Context, now time.Time) (bool, error) { + var any bool + err := s.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM quota_limits WHERE resets_at>?)`, quotaTime(now)).Scan(&any) + return any, err +} + +// SetRunBudget records a run's whole-run USD cap and where it came from. +func (s *Store) SetRunBudget(ctx context.Context, id int64, limitUSD float64, source string) error { + _, err := s.db.ExecContext(ctx, `UPDATE pipeline_runs SET budget_usd=?,budget_source=? WHERE id=?`, limitUSD, source, id) + return err +} + +// MarkRunBudgetWarned records the 80% warning once; it reports whether this +// call was the first. +func (s *Store) MarkRunBudgetWarned(ctx context.Context, id int64) (bool, error) { + res, err := s.db.ExecContext(ctx, `UPDATE pipeline_runs SET budget_warned=1 WHERE id=? AND budget_warned=0`, id) + if err != nil { + return false, err + } + n, err := res.RowsAffected() + return n == 1, err +} + +// runDefaultBudgetSetting is the server_settings key of the default run cap. +const runDefaultBudgetSetting = "run.default_budget_usd" + +// RunSettings reads the server-wide run defaults. +func (s *Store) RunSettings(ctx context.Context) (protocol.RunSettings, error) { + var settings protocol.RunSettings + value, found, err := s.ServerSetting(ctx, runDefaultBudgetSetting) + if err != nil || !found { + return settings, err + } + _, _ = fmt.Sscanf(value, "%g", &settings.DefaultBudgetUSD) + if settings.DefaultBudgetUSD < 0 { + settings.DefaultBudgetUSD = 0 + } + return settings, nil +} + +// SetRunSettings records the server-wide run defaults. +func (s *Store) SetRunSettings(ctx context.Context, settings protocol.RunSettings) (protocol.RunSettings, error) { + if settings.DefaultBudgetUSD < 0 || settings.DefaultBudgetUSD != settings.DefaultBudgetUSD || settings.DefaultBudgetUSD > 1e6 { + return protocol.RunSettings{}, fmt.Errorf("default_budget_usd must be 0 (no cap) or a positive USD amount") + } + if err := s.SetServerSetting(ctx, runDefaultBudgetSetting, fmt.Sprintf("%g", settings.DefaultBudgetUSD)); err != nil { + return protocol.RunSettings{}, err + } + return s.RunSettings(ctx) +} diff --git a/internal/pipeline/run_usage.go b/internal/pipeline/run_usage.go index 4050e433..2be825f2 100644 --- a/internal/pipeline/run_usage.go +++ b/internal/pipeline/run_usage.go @@ -46,6 +46,9 @@ WHERE u.run_id IN (`+strings.TrimSuffix(strings.Repeat("?,", len(args)), ",")+`) u.SplitKnown = u.TokensKnownStages > 0 && u.SplitUnknownStages == 0 u.CacheKnown = u.TokensKnownStages > 0 && u.CacheKnownStages == u.TokensKnownStages byID[id].Usage = &u + if byID[id].Budget != nil { + byID[id].Budget.SpentUSD = u.CostUSD + } } err = rows.Err() rows.Close() diff --git a/internal/pipeline/runs.go b/internal/pipeline/runs.go index 2a49d217..d1982e6f 100644 --- a/internal/pipeline/runs.go +++ b/internal/pipeline/runs.go @@ -27,14 +27,27 @@ CASE WHEN r.status='waiting' THEN COALESCE((SELECT sequence FROM session_export_ EXISTS(SELECT 1 FROM run_schedule_origin WHERE run_id=r.id), COALESCE((SELECT schedule_id FROM run_schedule_origin WHERE run_id=r.id),0), COALESCE((SELECT name FROM run_schedule_origin WHERE run_id=r.id),''), -MAX(r.size_bytes,0) +MAX(r.size_bytes,0), +r.failure_class,r.quota_resets_at,r.quota_resume_at,r.quota_sequence,r.quota_stage,r.quota_account,r.budget_usd,r.budget_source,r.budget_warned ` + runFrom + ` JOIN pipeline_versions v ON v.pipeline_id=r.pipeline_id AND v.version=r.version` func scanRun(row interface{ Scan(...any) error }, r *protocol.RunSummary) error { var output, stageModels string - if err := row.Scan(&r.ID, &r.PipelineID, &r.Name, &r.Version, &r.ContentHash, &r.Status, &r.Outcome, &r.CurrentStage, &r.CreatedAt, &r.FinishedAt, &r.Diagnostic, &r.FailureKind, &r.FailureReason, &output, &r.CompletedSteps, &r.Workspace, &r.Title, &r.Model, &stageModels, &r.NotifyMode, &r.CancelRequested, &r.CleanupUnconfirmed, &r.OutputFormat, &r.ExportPendingSequence, &r.Scheduled, &r.ScheduleID, &r.ScheduleName, &r.SizeBytes); err != nil { + var quota protocol.RunQuotaWait + var budget protocol.RunBudget + if err := row.Scan(&r.ID, &r.PipelineID, &r.Name, &r.Version, &r.ContentHash, &r.Status, &r.Outcome, &r.CurrentStage, &r.CreatedAt, &r.FinishedAt, &r.Diagnostic, &r.FailureKind, &r.FailureReason, &output, &r.CompletedSteps, &r.Workspace, &r.Title, &r.Model, &stageModels, &r.NotifyMode, &r.CancelRequested, &r.CleanupUnconfirmed, &r.OutputFormat, &r.ExportPendingSequence, &r.Scheduled, &r.ScheduleID, &r.ScheduleName, &r.SizeBytes, &r.FailureClass, "a.ResetsAt, "a.ResumeAt, "a.Sequence, "a.Stage, "a.Account, &budget.LimitUSD, &budget.Source, &budget.Warned); err != nil { return err } + if r.Status == protocol.RunStatusWaitingQuota { + r.QuotaWait = "a + } + if budget.LimitUSD > 0 { + r.Budget = &budget + } + if r.FailureClass == "" { + // Rows that predate the column still say why they stopped. + r.FailureClass = defaultFailureClass(r.Status, r.FailureKind) + } if stageModels != "" && stageModels != "{}" { if err := json.Unmarshal([]byte(stageModels), &r.StageModels); err != nil { return err @@ -316,6 +329,9 @@ strftime('%Y-%m-%dT%H:%M:%SZ',started_at),COALESCE(strftime('%Y-%m-%dT%H:%M:%SZ' // The run total is one pass over the steps already loaded above: it adds no // query and no transcript parse. r.Usage = protocol.TotalUsage(r.Steps) + if r.Budget != nil && r.Usage != nil { + r.Budget.SpentUSD = r.Usage.CostUSD + } r.Warnings = protocol.RunWarnings(r.Steps) if r.Environment != nil { for _, warning := range r.Environment.Warnings { diff --git a/internal/pipeline/runs_mutate.go b/internal/pipeline/runs_mutate.go index 9461d437..0119ce19 100644 --- a/internal/pipeline/runs_mutate.go +++ b/internal/pipeline/runs_mutate.go @@ -386,8 +386,9 @@ func (s *Store) CancelWaiting(ctx context.Context, id int64) error { } defer tx.Rollback() res, err := tx.ExecContext(ctx, `UPDATE pipeline_runs SET status='canceled',cancel_requested=1, -diagnostic=CASE WHEN EXISTS(SELECT 1 FROM session_export_gates g WHERE g.run_id=pipeline_runs.id) THEN 'Canceled while awaiting session export; computed visit retained' ELSE 'Canceled while waiting for a decision' END, -finished_at=CURRENT_TIMESTAMP WHERE id=? AND (status=? OR (status IN ('failed','interrupted') AND EXISTS(SELECT 1 FROM session_export_gates g WHERE g.run_id=pipeline_runs.id)))`, id, protocol.RunStatusWaiting) +diagnostic=CASE WHEN EXISTS(SELECT 1 FROM session_export_gates g WHERE g.run_id=pipeline_runs.id) THEN 'Canceled while awaiting session export; computed visit retained' WHEN status=? THEN 'Canceled while waiting for the usage limit to reset' ELSE 'Canceled while waiting for a decision' END, +failure_class='canceled',quota_resets_at='',quota_resume_at='',deferred_json='', +finished_at=CURRENT_TIMESTAMP WHERE id=? AND (status IN (?,?) OR (status IN ('failed','interrupted') AND EXISTS(SELECT 1 FROM session_export_gates g WHERE g.run_id=pipeline_runs.id)))`, protocol.RunStatusWaitingQuota, id, protocol.RunStatusWaiting, protocol.RunStatusWaitingQuota) if err != nil { return err } @@ -408,7 +409,7 @@ finished_at=CURRENT_TIMESTAMP WHERE id=? AND (status=? OR (status IN ('failed',' func (s *Store) Cancel(ctx context.Context, id int64) error { return affected(s.db.ExecContext(ctx, `UPDATE pipeline_runs SET cancel_requested=1, diagnostic=CASE WHEN cleanup_unconfirmed=1 THEN diagnostic ELSE 'Stop requested; waiting for execution and cleanup to stop' END -WHERE id=? AND (status IN ('queued','running','waiting') OR (status IN ('failed','interrupted') AND EXISTS(SELECT 1 FROM session_export_gates g WHERE g.run_id=pipeline_runs.id)))`, id)) +WHERE id=? AND (status IN ('queued','running','waiting','waiting_quota') OR (status IN ('failed','interrupted') AND EXISTS(SELECT 1 FROM session_export_gates g WHERE g.run_id=pipeline_runs.id)))`, id)) } func (s *Store) FinishRun(ctx context.Context, id int64, status, outcome, diagnostic string, output map[string]any) error { @@ -422,14 +423,19 @@ func (s *Store) FinishRun(ctx context.Context, id int64, status, outcome, diagno } defer tx.Rollback() failureKind, failureReason := classifyRunFailure(ctx, tx, id, status, diagnostic) + // A class the runner recorded for this run (SetRunFailureClass) wins over + // the derived default; a success carries none. + derivedClass := defaultFailureClass(status, failureKind) if err := affected(tx.ExecContext(ctx, `UPDATE pipeline_runs SET status=CASE WHEN cancel_requested=1 THEN 'canceled' ELSE ? END, outcome=CASE WHEN cancel_requested=1 THEN '' ELSE ? END, diagnostic=CASE WHEN cancel_requested=1 THEN 'Canceled by operator; execution stopped' ELSE ? END, failure_kind=CASE WHEN cancel_requested=1 THEN '' ELSE ? END, failure_reason=CASE WHEN cancel_requested=1 THEN '' ELSE ? END, + failure_class=CASE WHEN cancel_requested=1 THEN 'canceled' WHEN ?='' THEN '' WHEN failure_class<>'' THEN failure_class ELSE ? END, + quota_resets_at='',quota_resume_at='',deferred_json='', output_json=?,finished_at=CURRENT_TIMESTAMP WHERE id=? AND status IN ('queued','running') AND cleanup_unconfirmed=0 - AND NOT EXISTS(SELECT 1 FROM run_steps WHERE run_id=pipeline_runs.id AND agent_active=1)`, status, outcome, diagnostic, failureKind, failureReason, string(data), id)); err != nil { + AND NOT EXISTS(SELECT 1 FROM run_steps WHERE run_id=pipeline_runs.id AND agent_active=1)`, status, outcome, diagnostic, failureKind, failureReason, derivedClass, derivedClass, string(data), id)); err != nil { return err } if err := enqueueRunTransitionNotification(ctx, tx, id); err != nil { diff --git a/internal/pipeline/runs_schema.go b/internal/pipeline/runs_schema.go index 9766bc96..189fdc1b 100644 --- a/internal/pipeline/runs_schema.go +++ b/internal/pipeline/runs_schema.go @@ -85,6 +85,9 @@ CREATE TABLE IF NOT EXISTS retry_checkpoints ( return err } } + if err := s.initRunQuota(); err != nil { + return err + } if err := s.dropResourceSchema(); err != nil { return err } @@ -245,11 +248,11 @@ func (s *Store) RecoverRunsKeeping(ctx context.Context, keep map[int64]bool, rea if _, err := tx.ExecContext(ctx, "UPDATE run_steps SET diagnostic=? WHERE run_id=? AND status='interrupted' AND sequence=(SELECT MAX(sequence) FROM run_steps WHERE run_id=?)", "Server restarted; "+reason, id, id); err != nil { return err } - if _, err := tx.ExecContext(ctx, "UPDATE pipeline_runs SET status='interrupted',diagnostic=?,failure_kind='unexpected',failure_reason=?,finished_at=CURRENT_TIMESTAMP WHERE id=? AND status IN ('queued','running') AND cancel_requested=0 AND cleanup_unconfirmed=0", "Server restarted; "+reason+"; run was not resumed", "Server restarted; "+reason+"; run was not resumed", id); err != nil { + if _, err := tx.ExecContext(ctx, "UPDATE pipeline_runs SET status='interrupted',diagnostic=?,failure_kind='unexpected',failure_reason=?,failure_class='interrupted',finished_at=CURRENT_TIMESTAMP WHERE id=? AND status IN ('queued','running') AND cancel_requested=0 AND cleanup_unconfirmed=0", "Server restarted; "+reason+"; run was not resumed", "Server restarted; "+reason+"; run was not resumed", id); err != nil { return err } } - if _, err := tx.ExecContext(ctx, "UPDATE pipeline_runs SET status=CASE WHEN cancel_requested=1 THEN 'canceled' ELSE 'interrupted' END,diagnostic='Server stopped; owned sessions stopped; run was not resumed',failure_kind=CASE WHEN cancel_requested=1 THEN '' ELSE 'unexpected' END,failure_reason=CASE WHEN cancel_requested=1 THEN '' ELSE 'Server stopped; owned sessions stopped; run was not resumed' END,finished_at=CURRENT_TIMESTAMP WHERE status IN ('queued','running') AND status<>? AND cleanup_unconfirmed=0"+runFilter, append([]any{protocol.RunStatusWaiting}, keptArgs...)...); err != nil { + if _, err := tx.ExecContext(ctx, "UPDATE pipeline_runs SET status=CASE WHEN cancel_requested=1 THEN 'canceled' ELSE 'interrupted' END,diagnostic='Server stopped; owned sessions stopped; run was not resumed',failure_kind=CASE WHEN cancel_requested=1 THEN '' ELSE 'unexpected' END,failure_reason=CASE WHEN cancel_requested=1 THEN '' ELSE 'Server stopped; owned sessions stopped; run was not resumed' END,failure_class=CASE WHEN cancel_requested=1 THEN 'canceled' ELSE 'interrupted' END,finished_at=CURRENT_TIMESTAMP WHERE status IN ('queued','running') AND status<>? AND cleanup_unconfirmed=0"+runFilter, append([]any{protocol.RunStatusWaiting}, keptArgs...)...); err != nil { return err } // An export checkpoint is a paused handoff, not an interrupted model call. diff --git a/internal/pipeline/stats.go b/internal/pipeline/stats.go index 4931e7e1..5d4ec816 100644 --- a/internal/pipeline/stats.go +++ b/internal/pipeline/stats.go @@ -61,6 +61,12 @@ func (s *Store) UsageStats(ctx context.Context) (*protocol.UsageStats, error) { return nil, err } stats.Usage = usage + if stats.FailureClasses, err = failureClassCounts(ctx, tx); err != nil { + return nil, err + } + if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM pipeline_runs WHERE status=?`, protocol.RunStatusWaitingQuota).Scan(&stats.WaitingQuota); err != nil { + return nil, err + } return stats, tx.Commit() } diff --git a/internal/protocol/message.go b/internal/protocol/message.go index 3e726239..25c105bf 100644 --- a/internal/protocol/message.go +++ b/internal/protocol/message.go @@ -214,6 +214,14 @@ type Message struct { RetryVisit int `json:"retry_visit,omitempty"` RetryVersion int `json:"retry_version,omitempty"` RetryInput map[string]any `json:"retry_input,omitempty"` + // QuotaPolicy says what a run/retry does when the Claude account its + // stages use is known to be out of usage: defer (default), refuse or now. + QuotaPolicy string `json:"quota_policy,omitempty"` + // BudgetUSD caps the whole run's reported model cost (0 = the server + // default, if any). + BudgetUSD float64 `json:"budget_usd,omitempty"` + // RunSettings is the get/set_run_settings body and reply. + RunSettings *RunSettings `json:"run_settings,omitempty"` // RetryExtraVisits (1-5) grants extra visits to a resumed loop: to // RetryExtraStage when set, otherwise to the stage(s) that exhausted their // visits. The resume continues the exhausted loop instead of failing again. diff --git a/internal/protocol/run_quota.go b/internal/protocol/run_quota.go new file mode 100644 index 00000000..b06686b1 --- /dev/null +++ b/internal/protocol/run_quota.go @@ -0,0 +1,113 @@ +package protocol + +// Usage-limit parking, failure classes and run budgets. +// +// A run whose stage is refused for a provider usage limit is not failed: it +// is parked in RunStatusWaitingQuota with the reset time and resumes the same +// stage visit automatically a minute after the reset (or when the operator +// sends ResumeRun). A run or retry admitted while the same Claude account is +// known to be limited is deferred the same way before its first stage. + +const ( + // RunStatusWaitingQuota parks a run until a provider usage limit resets. + // It is not terminal: FinishedAt stays empty and no goroutine holds it. + RunStatusWaitingQuota = "waiting_quota" + // ResumeRun resumes a run parked in waiting_quota now; the reply is Run. + ResumeRun = "resume_run" + // GetRunSettings / SetRunSettings read and change the server-wide run + // defaults; both reply RunSettingsReply carrying RunSettings. + GetRunSettings = "get_run_settings" + SetRunSettings = "set_run_settings" + RunSettingsReply = "run_settings" +) + +// Quota policies a run/retry request may carry for a known usage limit of the +// account its Claude stages would use. +const ( + // QuotaDefer (also the empty default) admits the run parked in + // waiting_quota until the limit resets. + QuotaDefer = "defer" + // QuotaRefuse rejects the request with the reset time instead. + QuotaRefuse = "refuse" + // QuotaNow starts the run immediately anyway. + QuotaNow = "now" +) + +// Failure classes the runner records on a run that did not succeed. The +// value is empty for a run that succeeded, is running or is parked. +const ( + FailureQuota = "quota" + FailureLoopExhausted = "loop_exhausted" + FailureTimeout = "timeout" + FailurePermissionDenied = "permission_denied" + FailureHarnessError = "harness_error" + FailureBlocked = "blocked" + FailureEnvironment = "environment" + FailureCanceled = "canceled" + FailureInterrupted = "interrupted" + FailureBudget = "budget" + FailureCheckFailed = "check_failed" + FailureOther = "other" +) + +// FailureClasses lists every failure class in display order. +var FailureClasses = []string{FailureQuota, FailureLoopExhausted, FailureTimeout, FailurePermissionDenied, FailureHarnessError, FailureBlocked, FailureEnvironment, FailureCanceled, FailureInterrupted, FailureBudget, FailureCheckFailed, FailureOther} + +// FailureClassLabel is the short operator-facing wording of a class. +func FailureClassLabel(class string) string { + switch class { + case FailureQuota: + return "usage limit" + case FailureLoopExhausted: + return "loop limit reached" + case FailureTimeout: + return "timed out" + case FailurePermissionDenied: + return "permission denied" + case FailureHarnessError: + return "harness error" + case FailureBlocked: + return "blocked" + case FailureEnvironment: + return "environment problem" + case FailureCanceled: + return "canceled" + case FailureInterrupted: + return "interrupted" + case FailureBudget: + return "budget exhausted" + case FailureCheckFailed: + return "check failed" + case FailureOther: + return "failed" + } + return class +} + +// RunQuotaWait describes a run parked in waiting_quota. ResetsAt is when the +// limit resets (RFC 3339, UTC) and ResumeAt when the server resumes the run. +// Sequence is the interrupted visit (0 when the run is deferred before its +// first stage). Account names the Claude home/account that hit the limit, +// when known. +type RunQuotaWait struct { + ResetsAt string `json:"resets_at"` + ResumeAt string `json:"resume_at"` + Sequence int `json:"sequence,omitempty"` + Stage string `json:"stage,omitempty"` + Account string `json:"account,omitempty"` +} + +// RunBudget is a run's whole-run USD cap and what it spent so far. LimitUSD +// is 0 when the run has no cap. Warned is set once the 80% warning was sent. +type RunBudget struct { + LimitUSD float64 `json:"limit_usd"` + Source string `json:"source,omitempty"` + SpentUSD float64 `json:"spent_usd"` + Warned bool `json:"warned,omitempty"` +} + +// RunSettings are the server-wide run defaults. DefaultBudgetUSD caps every +// run that names no budget of its own (0 = no default cap). +type RunSettings struct { + DefaultBudgetUSD float64 `json:"default_budget_usd"` +} diff --git a/internal/protocol/runevents.go b/internal/protocol/runevents.go index 9689e3e1..864da49e 100644 --- a/internal/protocol/runevents.go +++ b/internal/protocol/runevents.go @@ -60,6 +60,9 @@ type RunEventFrame struct { FinishedAt string `json:"finished_at,omitempty"` FailureKind string `json:"failure_kind,omitempty"` FailureReason string `json:"failure_reason,omitempty"` + FailureClass string `json:"failure_class,omitempty"` + // QuotaWait is present on a frame that parks the run in waiting_quota. + QuotaWait *RunQuotaWait `json:"quota_wait,omitempty"` // Artifacts is the number of files recorded for the referenced step, so a // client can surface artifact capture without reading the step. Artifacts int `json:"artifacts,omitempty"` diff --git a/internal/protocol/runs.go b/internal/protocol/runs.go index 36f69cfc..f83253bd 100644 --- a/internal/protocol/runs.go +++ b/internal/protocol/runs.go @@ -189,8 +189,15 @@ type RunSummary struct { Diagnostic string `json:"diagnostic"` FailureKind string `json:"failure_kind,omitempty"` FailureReason string `json:"failure_reason,omitempty"` - ResultPreview string `json:"result_preview,omitempty"` - CompletedSteps int `json:"completed_steps"` + // FailureClass is the runner's classification of a run that did not + // succeed (see FailureClasses); empty otherwise and for historical rows. + FailureClass string `json:"failure_class,omitempty"` + // QuotaWait is set while Status is waiting_quota. + QuotaWait *RunQuotaWait `json:"quota_wait,omitempty"` + // Budget is the run's whole-run USD cap; absent when the run has none. + Budget *RunBudget `json:"budget,omitempty"` + ResultPreview string `json:"result_preview,omitempty"` + CompletedSteps int `json:"completed_steps"` // Model and StageModels are the launch-time overrides this run records so it // stays reproducible: Model covers every model stage and StageModels overrides // individual stages by key. They are empty for a run that used the pinned diff --git a/internal/protocol/stats.go b/internal/protocol/stats.go index 2d4a576c..8e2ae2fe 100644 --- a/internal/protocol/stats.go +++ b/internal/protocol/stats.go @@ -52,4 +52,10 @@ type UsageStats struct { // Usage is the history-wide sum of the per-run reported usage. It is absent // for a database with no recorded model usage (including a pre-upgrade one). Usage *UsageTotals `json:"usage,omitempty"` + // FailureClasses counts the runs that did not succeed by failure class + // (canceled and interrupted included); rows that predate the class are + // counted as blocked or other, as their runs read. + FailureClasses map[string]int `json:"failure_classes,omitempty"` + // WaitingQuota counts the runs parked for a usage limit now. + WaitingQuota int `json:"waiting_quota,omitempty"` } diff --git a/internal/server/run_budget.go b/internal/server/run_budget.go new file mode 100644 index 00000000..caafcbad --- /dev/null +++ b/internal/server/run_budget.go @@ -0,0 +1,115 @@ +package server + +import ( + "context" + "fmt" + "log" + "math" + "regexp" + "time" + + "git.a-wan.net/alan/pipelines/internal/pipeline" + "git.a-wan.net/alan/pipelines/internal/protocol" + "git.a-wan.net/alan/pipelines/internal/stage" +) + +// Run budgets and the error-loop policy. +// +// A run's whole-run USD cap is the run's own budget_usd, else the server +// default (run settings). Every model stage's budget also counts towards it: +// at 80% the operator is warned once, at 100% the visit stops and the run +// fails with failure class budget. The definition's per-stage budget_usd and +// budget_tokens still cap each stage on their own. + +// budgetWarnRatio is the share of the run cap that sends the warning. +const budgetWarnRatio = 0.8 + +// errorLoopBackoff is the wait before the next visit of a stage whose +// transient harness failure routed back to itself: 15 s, 1 min, then 4 min +// for every further consecutive one. Tests shorten it. +var errorLoopBackoff = []time.Duration{15 * time.Second, time.Minute, 4 * time.Minute} + +// sleepOrDone waits delay; false when ctx ends first. +func sleepOrDone(ctx context.Context, delay time.Duration) bool { + if delay <= 0 { + return ctx.Err() == nil + } + timer := time.NewTimer(delay) + defer timer.Stop() + select { + case <-ctx.Done(): + return false + case <-timer.C: + return true + } +} + +var harnessSignatureDigits = regexp.MustCompile(`[0-9]+`) + +// harnessSignature is a failure's text with its numbers (ids, times, +// counts) removed, so the same failure on two visits compares equal. +func harnessSignature(err error) string { + if err == nil { + return "" + } + text := harnessSignatureDigits.ReplaceAllString(err.Error(), "#") + if len(text) > 400 { + text = text[:400] + } + return text +} + +// resolveRunBudget is the cap a new run gets: its own request, else the +// server default. It returns the source recorded with it. +func (r *runner) resolveRunBudget(request protocol.Message) (float64, string, error) { + if request.BudgetUSD < 0 || math.IsNaN(request.BudgetUSD) || math.IsInf(request.BudgetUSD, 0) { + return 0, "", fmt.Errorf("budget_usd must be a positive USD amount") + } + if request.BudgetUSD > 0 { + return request.BudgetUSD, "run", nil + } + ctx, cancel := context.WithTimeout(r.ctx, 5*time.Second) + defer cancel() + settings, err := r.store.RunSettings(ctx) + if err != nil || settings.DefaultBudgetUSD <= 0 { + return 0, "", err + } + return settings.DefaultBudgetUSD, "server", nil +} + +// runBudget loads a run's cap and what it already spent (a resumed run). +func (r *runner) runBudget(ctx context.Context, id int64) *stage.RunBudget { + read, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second) + defer cancel() + detail, err := r.store.GetRun(read, id) + if err != nil || detail == nil || detail.Budget == nil { + return nil + } + spent := 0.0 + if detail.Usage != nil { + spent = detail.Usage.CostUSD + } + return stage.NewRunBudget(detail.Budget.LimitUSD, spent) +} + +// checkRunBudget sends the one 80% warning of a run's cap. +func (r *runner) checkRunBudget(id int64, name string, budget *stage.RunBudget) { + if !budget.Enabled() || budget.Spent() < budget.Limit()*budgetWarnRatio { + return + } + save, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + first, err := r.store.MarkRunBudgetWarned(save, id) + if err != nil || !first { + if err != nil { + log.Printf("run %d: record the budget warning: %v", id, err) + } + return + } + body := fmt.Sprintf("Run #%d · %s · spent $%.2f of its $%.2f budget; it stops at the cap", id, name, budget.Spent(), budget.Limit()) + if err := r.store.EnqueueRunNotification(save, pipeline.RunNotification{RunID: id, Sequence: 0, Event: "budget_warning", Channel: "system", Title: "Run budget 80% used", Body: body, Click: runAttentionClick(id)}); err != nil { + log.Printf("run %d: queue the budget warning: %v", id, err) + return + } + r.deliverRunNotificationBatch(time.Now(), 1) +} diff --git a/internal/server/run_quota.go b/internal/server/run_quota.go new file mode 100644 index 00000000..828157c2 --- /dev/null +++ b/internal/server/run_quota.go @@ -0,0 +1,411 @@ +package server + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log" + "os" + "strings" + "sync" + "time" + + "git.a-wan.net/alan/pipelines/internal/claude" + "git.a-wan.net/alan/pipelines/internal/claudeaccounts" + "git.a-wan.net/alan/pipelines/internal/pipeline" + "git.a-wan.net/alan/pipelines/internal/protocol" + "git.a-wan.net/alan/pipelines/internal/stage" + "git.a-wan.net/alan/pipelines/internal/turn" + "git.a-wan.net/alan/pipelines/internal/workenv" +) + +// Usage limits park runs instead of failing them. +// +// When a stage is refused for a provider usage limit the runner first tries +// the Claude account auto-switch chats use (the home's own setting decides); +// on a switch the same visit runs again at once on the new account. Otherwise +// the run is parked in waiting_quota with the reset time and resumes the same +// visit a minute after the reset (quotaResumeMargin). The parked state lives +// in the run row, so start-up re-arms the timers. Either way the visit that +// runs again is told, in a "# Previous attempt" note, that the limit +// interrupted it and partial edits may be in the worktree. +// +// A run or retry admitted while the account its Claude stages use is known +// to be out of usage is deferred the same way before its first stage (or +// refused, or started anyway: protocol.QuotaPolicy). + +const ( + // quotaResumeMargin is how long after the reset a parked run resumes. + quotaResumeMargin = time.Minute + // quotaFallbackHold is the wait when a refusal named no reset time. + quotaFallbackHold = time.Hour + // quotaBusyRetry is the wait before trying again when the run's + // workspace is held by another run at resume time. + quotaBusyRetry = time.Minute +) + +// quotaState is the runner's usage-limit collaborators and timers. +type quotaState struct { + mu sync.Mutex + timers map[int64]*time.Timer + // switchAccount signs workspace's Claude home in to another saved + // account with usage left (the chats' auto-switch); nil means no switch + // is possible. It reports the accounts switched from and to. + switchAccount func(ctx context.Context, workspace string, resetsAt time.Time) (from, to string, err error) + // account names the Claude account a run in workspace uses; nil uses + // claudeAccountKey. + account func(ctx context.Context, workspace string) string + // now is the clock; nil is time.Now. + now func() time.Time +} + +func (r *runner) quotaNow() time.Time { + if r.quota.now != nil { + return r.quota.now() + } + return time.Now() +} + +// quotaAccount names the account a run in workspace uses for its Claude +// stages: its Claude home and the account signed in there. +func (r *runner) quotaAccount(ctx context.Context, workspace string) string { + if r.quota.account != nil { + return r.quota.account(ctx, workspace) + } + resolver := r.dirEnv + if resolver == nil { + resolver = workenv.Default + } + return claudeAccountKey(ctx, resolver, workspace) +} + +// claudeAccountKey is "<home>|<email>": the CLAUDE_CONFIG_DIR a process in +// workspace runs with ("default" for the user's own ~/.claude) and the +// account signed in there when its files say. +func claudeAccountKey(ctx context.Context, resolver *workenv.Resolver, workspace string) string { + home, err := claude.AccountConfigDir(ctx, resolver, workspace, os.Environ()) + if err != nil { + return "default|" + } + email, _, _, ok := claudeaccounts.Store{ConfigDir: home}.Identity() + if !ok { + email = "" + } + return home + "|" + strings.ToLower(strings.TrimSpace(email)) +} + +// quotaAccountLabel is the operator-facing name of an account key. +func quotaAccountLabel(account string) string { + home, email, _ := strings.Cut(account, "|") + switch { + case email != "": + return email + case home == "default" || home == "": + return "the server's Claude account" + } + return "the Claude account of " + home +} + +// usesClaudeHarness reports whether any model stage of graph runs on the +// Claude harness (the only one whose usage windows reset on their own). +func usesClaudeHarness(graph protocol.Graph) bool { + for _, s := range graph.Stages { + if stage.EffectiveType(s.Type) == stage.ModelType && s.Configs["harness"] == stage.ClaudeBackend { + return true + } + } + return false +} + +// quotaAdmission is what start does about a known usage limit. +type quotaAdmission struct { + account string + resetsAt time.Time +} + +// knownQuotaLimit reports a known, unexpired usage limit of the account the +// graph's Claude stages would use in workspace. +func (r *runner) knownQuotaLimit(graph protocol.Graph, workspace string) (quotaAdmission, bool) { + if !usesClaudeHarness(graph) { + return quotaAdmission{}, false + } + ctx, cancel := context.WithTimeout(r.ctx, 10*time.Second) + defer cancel() + if any, err := r.store.AnyQuotaLimit(ctx, r.quotaNow()); err != nil || !any { + return quotaAdmission{}, false + } + account := r.quotaAccount(ctx, workspace) + resetsAt, ok, err := r.store.QuotaLimit(ctx, account, r.quotaNow()) + if err != nil || !ok { + return quotaAdmission{}, false + } + return quotaAdmission{account: account, resetsAt: resetsAt}, true +} + +// quotaRefusal is the error a refuse policy answers with. +func quotaRefusal(limit quotaAdmission) error { + return fmt.Errorf("the Claude usage limit of %s resets at %s; not starting into a known limit: queue the run to start at the reset (quota_policy=defer) or start it now anyway (quota_policy=now)", quotaAccountLabel(limit.account), limit.resetsAt.Local().Format("15:04 on 2 Jan")) +} + +// deferredLaunch is the admitted request of a run deferred before its first +// stage, persisted so the start survives a restart. +type deferredLaunch struct { + Request protocol.Message `json:"request"` + RetrySource int64 `json:"retry_source,omitempty"` +} + +// deferLaunch parks a just-created run before its first stage. Callers hold +// r.mu; the run is not in r.active. +func (r *runner) deferLaunch(id int64, workspace string, request protocol.Message, limit quotaAdmission) error { + data, err := json.Marshal(deferredLaunch{Request: request, RetrySource: request.RetrySource}) + if err != nil { + return err + } + resumeAt := limit.resetsAt.Add(quotaResumeMargin) + diagnostic := fmt.Sprintf("Deferred: the Claude usage limit of %s resets at %s; the run starts at %s", quotaAccountLabel(limit.account), limit.resetsAt.Local().Format("15:04 on 2 Jan"), resumeAt.Local().Format("15:04")) + save, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := r.store.ParkRunForQuota(save, id, 0, "", quotaAccountLabel(limit.account), limit.resetsAt, resumeAt, diagnostic, string(data)); err != nil { + return err + } + r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: workspace, Status: protocol.RunStatusWaitingQuota, QuotaWait: quotaWaitFrame(0, "", limit.account, limit.resetsAt, resumeAt)}, false) + r.armQuotaResume(id, resumeAt) + return nil +} + +func quotaWaitFrame(sequence int, stageKey, account string, resetsAt, resumeAt time.Time) *protocol.RunQuotaWait { + return &protocol.RunQuotaWait{ResetsAt: resetsAt.UTC().Format(time.RFC3339), ResumeAt: resumeAt.UTC().Format(time.RFC3339), Sequence: sequence, Stage: stageKey, Account: quotaAccountLabel(account)} +} + +// quotaDecision is what the loop does about a visit refused for usage. +type quotaDecision struct { + // rerun: the home switched accounts; run the visit again now. + rerun bool + // park: wait for the reset. + park bool + account string + resetsAt time.Time + note string +} + +// decideQuota handles a visit refused for a usage limit: it records the +// account's limit, then switches accounts or parks. An exhausted paid +// balance (no reset of its own) still fails the run. +func (r *runner) decideQuota(ctx context.Context, workspace string, err error) quotaDecision { + if !stage.SubscriptionQuota(err) { + return quotaDecision{} + } + now := r.quotaNow() + resetsAt, known := stage.QuotaResetsAt(err) + if !known || !resetsAt.After(now) { + resetsAt = now.Add(quotaFallbackHold) + } + lookup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second) + defer cancel() + account := r.quotaAccount(lookup, workspace) + if recordErr := r.store.RecordQuotaLimit(lookup, account, resetsAt); recordErr != nil { + log.Printf("record usage limit of %s: %v", quotaAccountLabel(account), recordErr) + } + if r.quota.switchAccount != nil { + switchCtx, switchCancel := context.WithTimeout(context.WithoutCancel(ctx), time.Minute) + from, to, switchErr := r.quota.switchAccount(switchCtx, workspace, resetsAt) + switchCancel() + if switchErr == nil && to != "" { + if from == "" { + from = "the previous account" + } + return quotaDecision{rerun: true, account: account, resetsAt: resetsAt, note: fmt.Sprintf("The Claude usage limit of %s interrupted this visit; Pipelines switched the Claude home to %s and runs the visit again.", from, to)} + } + if switchErr != nil && !errors.Is(switchErr, claude.ErrAutoSwitchOff) && !errors.Is(switchErr, claude.ErrNoAccountLeft) && !errors.Is(switchErr, claude.ErrNoConfigDir) && !errors.Is(switchErr, errNotClaudeChat) { + log.Printf("run workspace %s: Claude account auto-switch: %v", workspace, switchErr) + } + } + return quotaDecision{park: true, account: account, resetsAt: resetsAt, note: fmt.Sprintf("The Claude usage limit of %s interrupted this visit; the run waited for the limit to reset at %s and resumed the visit.", quotaAccountLabel(account), resetsAt.Local().Format("15:04 on 2 Jan"))} +} + +// quotaPreviousAttempt is the note the visit that runs again receives. +func quotaPreviousAttempt(stageKey, note string) string { + return turn.RenderPreviousAttempt(turn.PreviousAttempt{Attempt: 2, Stage: stageKey, Interruption: note}) +} + +// parkForQuota parks the run after its interrupted visit was recorded. +func (r *runner) parkForQuota(id int64, workspace string, sequence int, stageKey string, completed int, decision quotaDecision) { + resumeAt := decision.resetsAt.Add(quotaResumeMargin) + diagnostic := fmt.Sprintf("Waiting for the Claude usage limit of %s to reset at %s; stage %s resumes at %s", quotaAccountLabel(decision.account), decision.resetsAt.Local().Format("15:04 on 2 Jan"), stageKey, resumeAt.Local().Format("15:04")) + r.mu.Lock() + save, cancel := context.WithTimeout(context.Background(), 10*time.Second) + err := r.store.ParkRunForQuota(save, id, sequence, stageKey, quotaAccountLabel(decision.account), decision.resetsAt, resumeAt, diagnostic, "") + cancel() + if err != nil { + r.mu.Unlock() + log.Printf("run %d: park for the usage limit: %v; finishing it failed", id, err) + r.finishRunStateClass(id, "", workspace, "failed", "error", diagnostic, completed, sequence, stageKey, nil, protocol.FailureQuota) + return + } + r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: workspace, Status: protocol.RunStatusWaitingQuota, CurrentStage: stageKey, CompletedSteps: completed, QuotaWait: quotaWaitFrame(sequence, stageKey, decision.account, decision.resetsAt, resumeAt)}, false) + // Like a human wait, a parked run holds no goroutine and no workspace + // reservation; the resume checks the workspace is free again. + delete(r.active, id) + r.mu.Unlock() + r.deliverRunNotificationBatch(time.Now(), 1) + r.armQuotaResume(id, resumeAt) +} + +// armQuotaResume (re)schedules a parked run's resume. +func (r *runner) armQuotaResume(id int64, at time.Time) { + delay := max(at.Sub(r.quotaNow()), 0) + r.quota.mu.Lock() + defer r.quota.mu.Unlock() + if r.quota.timers == nil { + r.quota.timers = map[int64]*time.Timer{} + } + if old := r.quota.timers[id]; old != nil { + old.Stop() + } + r.quota.timers[id] = time.AfterFunc(delay, func() { + r.quota.mu.Lock() + delete(r.quota.timers, id) + r.quota.mu.Unlock() + if r.ctx.Err() != nil { + return + } + if _, err := r.resumeQuota(id); err != nil { + if errors.Is(err, errQuotaWorkspaceBusy) { + r.armQuotaResume(id, r.quotaNow().Add(quotaBusyRetry)) + return + } + if !errors.Is(err, pipeline.ErrInvalidRunTransition) { + log.Printf("run %d: resume after the usage limit: %v", id, err) + } + } + }) +} + +// disarmQuotaResume drops a parked run's timer (canceled or deleted). +func (r *runner) disarmQuotaResume(id int64) { + r.quota.mu.Lock() + defer r.quota.mu.Unlock() + if timer := r.quota.timers[id]; timer != nil { + timer.Stop() + delete(r.quota.timers, id) + } +} + +// stopQuotaTimers stops every pending resume (server shutdown). +func (r *runner) stopQuotaTimers() { + r.quota.mu.Lock() + defer r.quota.mu.Unlock() + for id, timer := range r.quota.timers { + timer.Stop() + delete(r.quota.timers, id) + } +} + +// armParkedRuns re-arms the resume of every run a previous process parked. +func (r *runner) armParkedRuns() { + ctx, cancel := context.WithTimeout(r.ctx, 10*time.Second) + defer cancel() + parked, err := r.store.QuotaParkedRuns(ctx) + if err != nil { + log.Printf("list runs waiting for a usage limit: %v", err) + return + } + for _, p := range parked { + resumeAt := p.ResumeAt + if resumeAt.IsZero() { + resumeAt = r.quotaNow() + } + r.armQuotaResume(p.RunID, resumeAt) + } +} + +var errQuotaWorkspaceBusy = errors.New("the run's workspace is held by another run") + +// resumeQuota resumes a parked run now: the interrupted visit runs again, or +// a deferred run starts. Both the timer and the operator's "resume now" use +// it; the store's transition makes it happen at most once. +func (r *runner) resumeQuota(id int64) (*protocol.RunDetail, error) { + if id <= 0 { + return nil, fmt.Errorf("resume requires a positive run ID") + } + r.mu.Lock() + ctx, cancel := context.WithTimeout(r.ctx, 10*time.Second) + detail, err := r.store.GetRun(ctx, id) + if err != nil { + cancel() + r.mu.Unlock() + return nil, err + } + if detail.Status != protocol.RunStatusWaitingQuota { + cancel() + r.mu.Unlock() + return nil, fmt.Errorf("%w: run %d is not waiting for a usage limit (it is %s)", pipeline.ErrInvalidRunTransition, id, detail.Status) + } + if _, busy := r.active[id]; busy { + cancel() + r.mu.Unlock() + return nil, fmt.Errorf("run %d is still settling; try again in a moment", id) + } + if err := r.checkWorkspaceFree(detail.Workspace); err != nil { + cancel() + r.mu.Unlock() + return nil, fmt.Errorf("%w: %v", errQuotaWorkspaceBusy, err) + } + parking, err := r.store.UnparkQuotaRun(ctx, id) + cancel() + if err != nil { + r.mu.Unlock() + return nil, err + } + r.disarmQuotaResume(id) + r.rememberRunIdentity(id, identityOfRunSummary(detail.RunSummary)) + workspace := detail.Workspace + if parking.Sequence == 0 { + var launch deferredLaunch + if err := json.Unmarshal([]byte(parking.Deferred), &launch); err != nil { + r.mu.Unlock() + r.finishRunStateClass(id, detail.Name, workspace, "failed", "error", "deferred launch request is unreadable: "+err.Error(), 0, 0, "", nil, protocol.FailureOther) + return r.getRun(id) + } + request := launch.Request + request.RetrySource = launch.RetrySource + d, err := r.store.Get(r.ctx, detail.PipelineID, detail.Version) + if err != nil { + r.mu.Unlock() + r.finishRunStateClass(id, detail.Name, workspace, "failed", "error", err.Error(), 0, 0, "", nil, protocol.FailureOther) + return r.getRun(id) + } + r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: workspace, Status: protocol.RunStatusQueued}, false) + r.launch(id, workspace, func(ctx context.Context) { + r.run(ctx, id, d, workspace, request) + }) + r.mu.Unlock() + return r.getRun(id) + } + var interrupted *protocol.RunStep + for i := range detail.Steps { + if detail.Steps[i].Sequence == parking.Sequence { + interrupted = &detail.Steps[i] + } + } + if interrupted == nil { + r.mu.Unlock() + r.finishRunStateClass(id, detail.Name, workspace, "failed", "error", fmt.Sprintf("the visit interrupted by the usage limit (#%d) is missing", parking.Sequence), completedSteps(detail.Steps), parking.Sequence, parking.Stage, nil, protocol.FailureQuota) + return r.getRun(id) + } + step := *interrupted + r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: workspace, Status: protocol.RunStatusRunning, CurrentStage: step.Stage, CompletedSteps: completedSteps(detail.Steps)}, false) + note := fmt.Sprintf("The Claude usage limit of %s interrupted this visit; the run waited for the limit to reset at %s and resumed the visit.", parking.Account, parking.ResetsAt.Local().Format("15:04 on 2 Jan")) + r.launch(id, workspace, func(ctx context.Context) { + state := rebuildRunState(detail, protocol.RunStep{Target: step.Stage, Output: step.Input}) + // The interrupted visit does not count against the stage's limits. + if state.visits[step.Stage] > 0 { + state.visits[step.Stage]-- + } + state.previousAttempt = quotaPreviousAttempt(step.Stage, note) + r.runLoop(ctx, id, detail.Graph, detail.Name, workspace, protocol.Message{WritePaths: detail.WritePaths, AllowTools: detail.AllowTools, Model: detail.Model, StageModels: detail.StageModels}, state) + }) + r.mu.Unlock() + return r.getRun(id) +} diff --git a/internal/server/run_quota_test.go b/internal/server/run_quota_test.go new file mode 100644 index 00000000..61e5efe3 --- /dev/null +++ b/internal/server/run_quota_test.go @@ -0,0 +1,406 @@ +package server + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/pipeline" + "git.a-wan.net/alan/pipelines/internal/protocol" + "git.a-wan.net/alan/pipelines/internal/stage" +) + +// quotaSource is a two-stage Claude pipeline whose stages loop on error, so a +// test sees the runner (not the definition) decide what a failure does. +const quotaSource = "# stage work\n\n```prompt\nDo the work.\n```\n\n```tools\nread\n```\n\n```edges\nsuccess -> review\nerror -> work\n```\n\n```limits\n{\"max_visits\":3,\"on\":[\"error\"]}\n```\n\n```configs\nharness=claude\nprovider=anthropic\nmodel=claude-haiku-5-5\nretries=0\n```\n\n" + + "# stage review\n\n```prompt\nReview the work.\n```\n\n```tools\nread\n```\n\n```edges\nsuccess -> #success\nblocked -> #failure\nerror -> work\n```\n\n```configs\nharness=claude\nprovider=anthropic\nmodel=claude-haiku-5-5\nretries=0\n```\n\n" + +// quotaRunner submits quotaSource and returns a runner whose Claude account +// is fixed (no real Claude home is read) and whose clock the test controls. +func quotaRunner(t *testing.T) (context.Context, *runner, *pipeline.Store, int64, *atomic.Int64) { + t.Helper() + ctx, cancel := context.WithCancel(context.Background()) + r, store, id := submitRunner(t, ctx, quotaSource) + t.Cleanup(func() { + cancel() + r.wg.Wait() + r.stopQuotaTimers() + store.Close() + }) + clock := &atomic.Int64{} + clock.Store(time.Now().UnixNano()) + r.quota.now = func() time.Time { return time.Unix(0, clock.Load()) } + r.quota.account = func(context.Context, string) string { return "/homes/a|a@example.com" } + return ctx, r, store, id, clock +} + +func quotaLimited(resetsAt time.Time) error { + return fmt.Errorf("model stage work: HARNESS TRANSPORT: %w: %w", stage.ErrHarnessTransport, &stage.QuotaError{Subscription: true, ResetsAt: resetsAt}) +} + +func runStatus(t *testing.T, store *pipeline.Store, id int64) *protocol.RunDetail { + t.Helper() + detail, err := store.GetRun(context.Background(), id) + if err != nil { + t.Fatal(err) + } + return detail +} + +func TestUsageLimitParksTheRunAndResumesTheSameVisit(t *testing.T) { + ctx, r, store, pipelineID, clock := quotaRunner(t) + reset := time.Unix(0, clock.Load()).Add(time.Hour).Truncate(time.Second) + var calls atomic.Int32 + var resumedInput atomic.Value + r.execute = func(ctx context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) { + if def.Key == "work" && calls.Add(1) == 1 { + return stage.Result{}, quotaLimited(reset) + } + if def.Key == "work" { + data, _ := os.ReadFile(def.Turn.Input) + resumedInput.Store(string(data)) + } + return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil + } + run := startRun(t, r, pipelineID, "quota-park") + parked := runStatus(t, store, run.ID) + if parked.Status != protocol.RunStatusWaitingQuota || parked.FinishedAt != "" || parked.QuotaWait == nil { + t.Fatalf("the run was not parked: %+v", parked.RunSummary) + } + wait := parked.QuotaWait + if wait.Sequence != 1 || wait.Stage != "work" || wait.ResetsAt != reset.UTC().Format(time.RFC3339) || wait.ResumeAt != reset.Add(time.Minute).UTC().Format(time.RFC3339) || wait.Account != "a@example.com" { + t.Fatalf("parking record %+v", wait) + } + if len(parked.Steps) != 1 || parked.Steps[0].Status != "failed" || parked.Steps[0].Target != "work" || strings.Contains(parked.Steps[0].Diagnostic, "top up") { + t.Fatalf("interrupted visit %+v", parked.Steps) + } + if parked.FailureClass != "" { + t.Fatalf("a parked run has no failure class: %q", parked.FailureClass) + } + r.quota.mu.Lock() + armed := r.quota.timers[run.ID] != nil + r.quota.mu.Unlock() + if !armed { + t.Fatal("no resume was scheduled") + } + // The account's limit is remembered for later admissions. + if at, ok, err := store.QuotaLimit(ctx, "/homes/a|a@example.com", time.Unix(0, clock.Load())); err != nil || !ok || !at.Equal(reset) { + t.Fatal("limit not recorded", at, ok, err) + } + // Resume now (the operator's action; the timer calls the same path). + if _, err := r.resumeQuota(run.ID); err != nil { + t.Fatal(err) + } + r.wg.Wait() + done := runStatus(t, store, run.ID) + if done.Status != "succeeded" || len(done.Steps) != 3 || done.QuotaWait != nil { + t.Fatalf("the resumed run did not finish: %+v %+v", done.RunSummary, done.Steps) + } + if done.Steps[1].Stage != "work" || done.Steps[1].Control == nil || done.Steps[1].Control.Visit != 1 { + t.Fatalf("the interrupted visit counted against the stage: %+v", done.Steps[1].Control) + } + input, _ := resumedInput.Load().(string) + if !strings.Contains(input, "# Previous attempt") || !strings.Contains(input, "interrupted") || !strings.Contains(input, "Partial edits") { + t.Fatalf("the resumed visit was not told about the interruption:\n%s", input) + } + if _, err := r.resumeQuota(run.ID); !errors.Is(err, pipeline.ErrInvalidRunTransition) { + t.Fatal("a second resume must be refused", err) + } +} + +func TestUsageLimitSwitchesAccountAndRerunsAtOnce(t *testing.T) { + _, r, store, pipelineID, clock := quotaRunner(t) + var calls atomic.Int32 + var switched atomic.Int32 + r.quota.switchAccount = func(_ context.Context, workspace string, _ time.Time) (string, string, error) { + switched.Add(1) + return "a@example.com", "b@example.com", nil + } + r.execute = func(ctx context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) { + if def.Key == "work" && calls.Add(1) == 1 { + return stage.Result{}, quotaLimited(time.Unix(0, clock.Load()).Add(time.Hour)) + } + return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil + } + run := startRun(t, r, pipelineID, "quota-switch") + done := runStatus(t, store, run.ID) + if done.Status != "succeeded" || len(done.Steps) != 3 || switched.Load() != 1 { + t.Fatalf("switch did not rerun the visit: %+v %+v", done.RunSummary, done.Steps) + } + if !strings.Contains(done.Steps[0].Diagnostic, "switched Claude account") || done.Steps[0].Target != "work" { + t.Fatalf("interrupted visit %+v", done.Steps[0]) + } +} + +func TestParkedRunSurvivesRestartAndCanBeCanceled(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "quota.db") + store, err := pipeline.Open(path) + if err != nil { + t.Fatal(err) + } + ctx, shutdown := context.WithCancel(context.Background()) + if _, err := store.Submit(ctx, "quota", quotaSource); err != nil { + t.Fatal(err) + } + items, _ := store.List(ctx) + r, err := newRunner(ctx, store) + if err != nil { + t.Fatal(err) + } + r.quota.account = func(context.Context, string) string { return "default|" } + reset := time.Now().Add(time.Hour) + r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) { + return stage.Result{}, quotaLimited(reset) + } + parkedA := startRun(t, r, items[0].ID, "parked-a") + parkedB := startRun(t, r, items[0].ID, "parked-b") + shutdown() + r.wg.Wait() + r.stopQuotaTimers() + store.Close() + + store, err = pipeline.Open(path) + if err != nil { + t.Fatal(err) + } + defer store.Close() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + r, err = newRunner(ctx, store) + if err != nil { + t.Fatal(err) + } + defer func() { r.wg.Wait(); r.stopQuotaTimers() }() + for _, id := range []int64{parkedA.ID, parkedB.ID} { + if status := runStatus(t, store, id).Status; status != protocol.RunStatusWaitingQuota { + t.Fatalf("run %d did not stay parked across the restart: %s", id, status) + } + } + // Cancel B while it waits: no goroutine holds it. + if err := r.cancel(parkedB.ID); err != nil { + t.Fatal(err) + } + canceled := runStatus(t, store, parkedB.ID) + if canceled.Status != protocol.RunStatusCanceled || canceled.FailureClass != protocol.FailureCanceled || canceled.FinishedAt == "" { + t.Fatalf("cancel of a parked run: %+v", canceled.RunSummary) + } + // The restarted server's clock is past A's resume time: it resumes. + r.quota.now = func() time.Time { return reset.Add(2 * time.Minute) } + r.quota.account = func(context.Context, string) string { return "default|" } + var mu sync.Mutex + var visits []string + r.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) { + mu.Lock() + visits = append(visits, def.Key) + mu.Unlock() + return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil + } + r.armParkedRuns() + deadline := time.Now().Add(10 * time.Second) + for runStatus(t, store, parkedA.ID).Status != "succeeded" { + if time.Now().After(deadline) { + t.Fatalf("the parked run was not resumed after the restart: %+v", runStatus(t, store, parkedA.ID).RunSummary) + } + time.Sleep(20 * time.Millisecond) + } + r.wg.Wait() + mu.Lock() + defer mu.Unlock() + if strings.Join(visits, ",") != "work,review" { + t.Fatalf("resumed visits %v", visits) + } + if status := runStatus(t, store, parkedB.ID).Status; status != protocol.RunStatusCanceled { + t.Fatalf("the canceled run came back: %s", status) + } +} + +func TestKnownUsageLimitDefersOrRefusesNewRunsAndRetries(t *testing.T) { + ctx, r, store, pipelineID, clock := quotaRunner(t) + reset := time.Unix(0, clock.Load()).Add(30 * time.Minute) + if err := store.RecordQuotaLimit(ctx, "/homes/a|a@example.com", reset); err != nil { + t.Fatal(err) + } + var calls atomic.Int32 + r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) { + calls.Add(1) + return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil + } + workspace := t.TempDir() + request := func(key, policy string) protocol.Message { + return protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: key, Workspace: workspace, Input: map[string]any{"prompt": "task"}, QuotaPolicy: policy} + } + if _, err := r.start(request("refused", protocol.QuotaRefuse)); err == nil || !strings.Contains(err.Error(), "resets at") { + t.Fatal("refuse policy did not refuse", err) + } + deferred, err := r.start(request("deferred", "")) + if err != nil { + t.Fatal(err) + } + r.wg.Wait() + if deferred.Status != protocol.RunStatusWaitingQuota || deferred.QuotaWait == nil || deferred.QuotaWait.Sequence != 0 || calls.Load() != 0 { + t.Fatalf("the run was not deferred: %+v", deferred.RunSummary) + } + // A replay of the same request returns the deferred run, not a new one. + if replay, err := r.start(request("deferred", "")); err != nil || replay.ID != deferred.ID { + t.Fatal("replay", replay, err) + } + // The deferred run starts (here: resume now) and runs from its entry. + if _, err := r.resumeQuota(deferred.ID); err != nil { + t.Fatal(err) + } + r.wg.Wait() + if done := runStatus(t, store, deferred.ID); done.Status != "succeeded" || calls.Load() != 2 { + t.Fatalf("the deferred run did not run: %+v", done.RunSummary) + } + // quota_policy=now starts at once anyway. + now, err := r.start(request("now", protocol.QuotaNow)) + if err != nil { + t.Fatal(err) + } + r.wg.Wait() + if done := runStatus(t, store, now.ID); done.Status != "succeeded" { + t.Fatalf("quota_policy=now did not start: %+v", done.RunSummary) + } + // A retry is deferred the same way. + r.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) { + if def.Key == "review" { + return stage.Result{Outcome: "blocked", Output: stage.Values{"summary": "no"}}, nil + } + return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil + } + failed, err := r.start(request("to-retry", protocol.QuotaNow)) + if err != nil { + t.Fatal(err) + } + r.wg.Wait() + if detail := runStatus(t, store, failed.ID); detail.Status != "failed" || detail.FailureClass != protocol.FailureBlocked { + t.Fatalf("blocked run: %+v", detail.RunSummary) + } + retried, err := r.retry(protocol.Message{RunID: failed.ID, RequestKey: "retry-1"}) + if err != nil { + t.Fatal(err) + } + if retried.Status != protocol.RunStatusWaitingQuota { + t.Fatalf("the retry was not deferred: %+v", retried.RunSummary) + } + if _, err := r.retry(protocol.Message{RunID: failed.ID, RequestKey: "retry-2", QuotaPolicy: protocol.QuotaRefuse}); err == nil { + t.Fatal("a refuse-policy retry into a known limit was admitted") + } + stats, err := store.UsageStats(ctx) + if err != nil { + t.Fatal(err) + } + if stats.WaitingQuota != 1 || stats.FailureClasses[protocol.FailureBlocked] != 1 { + t.Fatalf("stats: waiting_quota %d, classes %v", stats.WaitingQuota, stats.FailureClasses) + } +} + +func TestFailureClassesAndErrorLoopPolicy(t *testing.T) { + saved := errorLoopBackoff + errorLoopBackoff = []time.Duration{5 * time.Millisecond, 10 * time.Millisecond} + t.Cleanup(func() { errorLoopBackoff = saved }) + for _, tc := range []struct { + name string + errs []error + status string + class string + visits int + reason string + }{ + {name: "deterministic", errs: []error{fmt.Errorf("%w: invalid argument --tools", stage.ErrHarnessTransport)}, status: "failed", class: protocol.FailureHarnessError, visits: 1, reason: "repeats on every attempt"}, + {name: "repeated-readback", errs: []error{fmt.Errorf("%w: final assistant readback contained no assistant message", stage.ErrHarnessTransport), fmt.Errorf("%w: final assistant readback contained no assistant message", stage.ErrHarnessTransport)}, status: "failed", class: protocol.FailureHarnessError, visits: 2, reason: "same harness failure repeated"}, + {name: "transient", errs: []error{fmt.Errorf("%w: connection reset", stage.ErrHarnessTransport), fmt.Errorf("%w: 503 overloaded", stage.ErrHarnessTransport)}, status: "succeeded", visits: 3}, + {name: "permission", errs: []error{fmt.Errorf("model stage work: %w", &stage.PermissionDeniedError{Denials: []string{"Bash(git push)"}})}, status: "failed", class: protocol.FailurePermissionDenied, visits: 1, reason: "Bash(git push)"}, + {name: "loop", errs: []error{errors.New("a"), errors.New("b"), errors.New("c")}, status: "failed", class: protocol.FailureLoopExhausted, visits: 3}, + {name: "timeout", errs: []error{fmt.Errorf("x: %w", context.DeadlineExceeded), fmt.Errorf("x: %w", context.DeadlineExceeded), fmt.Errorf("x: %w", context.DeadlineExceeded)}, status: "failed", class: protocol.FailureLoopExhausted, visits: 3}, + } { + t.Run(tc.name, func(t *testing.T) { + _, r, store, pipelineID, _ := quotaRunner(t) + var calls atomic.Int32 + r.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) { + if def.Key == "work" { + if n := int(calls.Add(1)); n <= len(tc.errs) { + return stage.Result{}, tc.errs[n-1] + } + } + return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil + } + run := startRun(t, r, pipelineID, "class-"+tc.name) + detail := runStatus(t, store, run.ID) + if detail.Status != tc.status || detail.FailureClass != tc.class { + t.Fatalf("status %s class %q, want %s %q (%s)", detail.Status, detail.FailureClass, tc.status, tc.class, detail.Diagnostic) + } + if got := int(calls.Load()); got != tc.visits { + t.Fatalf("%d visits of work, want %d", got, tc.visits) + } + if tc.reason != "" && !strings.Contains(detail.Diagnostic, tc.reason) { + t.Fatalf("diagnostic %q does not say %q", detail.Diagnostic, tc.reason) + } + }) + } +} + +func TestRunBudgetWarnsAndStops(t *testing.T) { + ctx, r, store, pipelineID, _ := quotaRunner(t) + r.execute = func(ctx context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) { + cost := 0.85 + if def.Key == "review" { + cost = 0.30 + } + if err := stage.BudgetFrom(ctx).ObserveCost("session-"+def.Key, cost); err != nil { + return stage.Result{}, err + } + return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil + } + run, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "budget", Workspace: t.TempDir(), Input: map[string]any{"prompt": "task"}, BudgetUSD: 1}) + if err != nil { + t.Fatal(err) + } + r.wg.Wait() + detail := runStatus(t, store, run.ID) + if detail.Status != "failed" || detail.FailureClass != protocol.FailureBudget || len(detail.Steps) != 2 { + t.Fatalf("budget stop: %+v %+v", detail.RunSummary, detail.Steps) + } + // review's error edge leads back to work; a spent run budget does not. + if detail.Steps[1].Target != protocol.FailureEnd { + t.Fatalf("budget stop followed the error edge: %+v", detail.Steps[1]) + } + if detail.Budget == nil || detail.Budget.LimitUSD != 1 || detail.Budget.Source != "run" || !detail.Budget.Warned { + t.Fatalf("budget record %+v", detail.Budget) + } + notes, err := store.RunNotifications(ctx, run.ID) + if err != nil { + t.Fatal(err) + } + warned := false + for _, n := range notes { + warned = warned || n.Event == "budget_warning" + } + if !warned { + t.Fatalf("no 80%% warning was queued: %+v", notes) + } +} + +func TestServerDefaultRunBudget(t *testing.T) { + ctx, r, store, pipelineID, _ := quotaRunner(t) + if _, err := store.SetRunSettings(ctx, protocol.RunSettings{DefaultBudgetUSD: -1}); err == nil { + t.Fatal("a negative default was accepted") + } + if _, err := store.SetRunSettings(ctx, protocol.RunSettings{DefaultBudgetUSD: 5}); err != nil { + t.Fatal(err) + } + r.execute = successExecute + run := startRun(t, r, pipelineID, "default-budget") + detail := runStatus(t, store, run.ID) + if detail.Budget == nil || detail.Budget.LimitUSD != 5 || detail.Budget.Source != "server" || detail.FailureClass != "" { + t.Fatalf("default budget %+v class %q", detail.Budget, detail.FailureClass) + } +} diff --git a/internal/server/runevents.go b/internal/server/runevents.go index bd4e4e3c..1475102a 100644 --- a/internal/server/runevents.go +++ b/internal/server/runevents.go @@ -537,6 +537,14 @@ func mergeRunEventFrame(into, in *protocol.RunEventFrame) { if in.Status != "" { into.Status = in.Status into.ExportPendingSequence = in.ExportPendingSequence + // A status change carries its own usage-limit wait (or clears it). + into.QuotaWait = in.QuotaWait + } + if in.FailureClass != "" { + into.FailureClass = in.FailureClass + } + if in.FailureKind != "" { + into.FailureKind, into.FailureReason = in.FailureKind, in.FailureReason } if in.Outcome != "" { into.Outcome = in.Outcome @@ -617,6 +625,8 @@ func handleRunEvents(request protocol.Message, events *runEventHub, runs *runner FinishedAt: summary.FinishedAt, FailureKind: summary.FailureKind, FailureReason: summary.FailureReason, + FailureClass: summary.FailureClass, + QuotaWait: summary.QuotaWait, CancelRequested: summary.CancelRequested, CleanupUnconfirmed: summary.CleanupUnconfirmed, ExportPendingSequence: summary.ExportPendingSequence, diff --git a/internal/server/runner.go b/internal/server/runner.go index 4ddf322b..a52e7569 100644 --- a/internal/server/runner.go +++ b/internal/server/runner.go @@ -101,6 +101,8 @@ type runner struct { // holds the runs start-up recovery kept for reattachRuns to continue. detach bool reattach []reattachPlan + // quota parks runs refused for a usage limit (run_quota.go). + quota quotaState } func newRunner(ctx context.Context, s *pipeline.Store) (*runner, error) { @@ -288,6 +290,32 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc } } } + budgetUSD, budgetSource, err := r.resolveRunBudget(request) + if err != nil { + return nil, err + } + // A known usage limit of the account the Claude stages would use: defer + // the start to the reset, refuse, or start anyway (protocol.QuotaPolicy). + // An idempotent replay returns its run as it is. + var quotaLimit quotaAdmission + quotaDeferred := false + switch request.QuotaPolicy { + case "", protocol.QuotaDefer, protocol.QuotaRefuse, protocol.QuotaNow: + default: + return nil, fmt.Errorf("quota_policy must be defer, refuse or now") + } + if request.QuotaPolicy != protocol.QuotaNow { + if limit, limited := r.knownQuotaLimit(d.Graph, workspace); limited { + if replay, err := r.store.RunByKey(r.ctx, request.RequestKey); err != nil { + return nil, err + } else if replay == 0 { + if request.QuotaPolicy == protocol.QuotaRefuse { + return nil, quotaRefusal(limit) + } + quotaLimit, quotaDeferred = limit, true + } + } + } // Decide admission and idempotency under the lock, but generate the title // only for a request that will actually start a run: a rejected or replayed // request must not pay for a bounded model generation, and a live one must @@ -415,6 +443,11 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc r.rememberRunIdentity(id, identityOfRunSummary(detail.RunSummary)) } if created { + if budgetUSD > 0 { + if err := r.store.SetRunBudget(r.ctx, id, budgetUSD, budgetSource); err != nil { + return nil, err + } + } if request.RetrySource > 0 && request.RetryMode != "restart" { checkpoint, checkpointErr := r.retrySourceCheckpointSelected(request.RetrySource, d, request.RetryStage, request.RetryVisit, request.RetryInput, request.RetryExtraVisits) if checkpointErr != nil { @@ -433,9 +466,24 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc Status: protocol.RunStatusQueued, CreatedAt: time.Now().UTC().Format(time.RFC3339), }, false) - r.launch(id, workspace, func(ctx context.Context) { - r.run(ctx, id, d, workspace, request) - }) + deferred := false + if quotaDeferred { + if err := r.deferLaunch(id, workspace, request, quotaLimit); err != nil { + log.Printf("run %d: defer to the usage-limit reset: %v; starting now", id, err) + } else { + deferred = true + } + } + if !deferred { + r.launch(id, workspace, func(ctx context.Context) { + r.run(ctx, id, d, workspace, request) + }) + } + if budgetUSD > 0 || deferred { + if reread, err := r.store.GetRun(r.ctx, id); err == nil && reread != nil { + detail = reread + } + } } if detail != nil { _, detail.Executing = r.active[id] @@ -511,7 +559,7 @@ func (r *runner) settleLaunchOnce(id int64, generation *byte) (bool, error) { } r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: detail.Workspace, Status: protocol.RunStatusCanceled, CancelRequested: true, CurrentStage: detail.CurrentStage, FinishedAt: time.Now().UTC().Format(time.RFC3339)}, true) } - if detail.FinishedAt != "" || detail.Status == protocol.RunStatusWaiting { + if detail.FinishedAt != "" || detail.Status == protocol.RunStatusWaiting || detail.Status == protocol.RunStatusWaitingQuota { delete(r.active, id) } // A landed (or change-free) successful run's own worktree is no longer @@ -1070,7 +1118,12 @@ func (r *runner) retry(request protocol.Message) (*protocol.RunDetail, error) { if notifyMode == "" { notifyMode, _ = r.store.RunNotifyMode(r.ctx, original.ID) } - return r.start(protocol.Message{PipelineID: original.PipelineID, Version: version, RequestKey: request.RequestKey, RetryMode: mode, RetrySource: original.ID, RetryStage: request.RetryStage, RetryVisit: request.RetryVisit, RetryInput: request.RetryInput, RetryExtraVisits: request.RetryExtraVisits, RetryExtraStage: request.RetryExtraStage, Workspace: original.Workspace, Input: original.Input, AllowTools: original.AllowTools, WritePaths: original.WritePaths, Model: original.Model, StageModels: original.StageModels, NotifyMode: notifyMode, OutputFormat: original.OutputFormat}, original.ID) + // A retry keeps the source run's own budget unless it names one. + budgetUSD := request.BudgetUSD + if budgetUSD == 0 && original.Budget != nil && original.Budget.Source == "run" { + budgetUSD = original.Budget.LimitUSD + } + return r.start(protocol.Message{PipelineID: original.PipelineID, Version: version, RequestKey: request.RequestKey, RetryMode: mode, RetrySource: original.ID, RetryStage: request.RetryStage, RetryVisit: request.RetryVisit, RetryInput: request.RetryInput, RetryExtraVisits: request.RetryExtraVisits, RetryExtraStage: request.RetryExtraStage, Workspace: original.Workspace, Input: original.Input, AllowTools: original.AllowTools, WritePaths: original.WritePaths, Model: original.Model, StageModels: original.StageModels, NotifyMode: notifyMode, OutputFormat: original.OutputFormat, QuotaPolicy: request.QuotaPolicy, BudgetUSD: budgetUSD}, original.ID) } func (r *runner) cancel(id int64) error { @@ -1083,10 +1136,12 @@ func (r *runner) cancel(id int64) error { if ok { entry.cancel() } else { - // Only a parked human run is known to have no live executor. + // Only a parked run (a human decision or a usage limit) is known to + // have no live executor. if err := r.store.CancelWaiting(r.ctx, id); err != nil { return err } + r.disarmQuotaResume(id) } r.forgetAttention(id) if r.events != nil { @@ -1102,6 +1157,7 @@ func (r *runner) cancel(id int64) error { FinishedAt: detail.FinishedAt, CancelRequested: detail.CancelRequested, CleanupUnconfirmed: detail.CleanupUnconfirmed, + FailureClass: detail.FailureClass, }, !ok) } } @@ -1399,6 +1455,14 @@ type runState struct { // adopt names the visit to re-adopt from a previous server process instead // of starting it; it is consumed by the loop's first iteration. adopt *adoptedVisit + // failureClass is the class the run finishes with if it fails now: the + // latest visit's failure (protocol.Failure*), "" to let the store derive. + failureClass string + // errorLoops counts each stage's consecutive transient error self-loops + // (the backoff step); lastHarness is its latest repeatable harness + // failure, so the same one twice in a row stops the loop. + errorLoops map[string]int + lastHarness map[string]string // findings is the run's findings ledger; grants are extra visits per stage // (loop_state.go). sessions is each stage's latest harness session, which // a resume_session stage continues on its next visit. @@ -1826,6 +1890,19 @@ func (r *runner) emitRun(frame protocol.RunEventFrame, terminal bool) { } func (r *runner) finishRunState(id int64, name, workspace, status, outcome, diagnostic string, completed, sequence int, currentStage string, input stage.Values) { + r.finishRunStateClass(id, name, workspace, status, outcome, diagnostic, completed, sequence, currentStage, input, "") +} + +// finishRunStateClass finishes a run recording the runner's failure class +// (empty lets the store derive one; a success records none). +func (r *runner) finishRunStateClass(id int64, name, workspace, status, outcome, diagnostic string, completed, sequence int, currentStage string, input stage.Values, class string) { + if class != "" && status != "succeeded" { + save, cancel := context.WithTimeout(context.Background(), 10*time.Second) + if err := r.store.SetRunFailureClass(save, id, class); err != nil { + log.Printf("run %d: record failure class: %v", id, err) + } + cancel() + } // The deliverable and the size walk touch files only: they run without r.mu, // so listings and details do not stall behind a large run finishing. The // run stays in r.active (its workspace reserved) until the launch teardown. @@ -1869,6 +1946,7 @@ func (r *runner) finishRunState(id int64, name, workspace, status, outcome, diag FinishedAt: detail.FinishedAt, FailureKind: detail.FailureKind, FailureReason: detail.FailureReason, + FailureClass: detail.FailureClass, SizeBytes: size, }, true) r.kickSizes() @@ -2020,7 +2098,7 @@ func (r *runner) finishStage(id int64, name, workspace string, selected protocol func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, name, workspace string, request protocol.Message, state *runState) { finish := func(status, outcome, diagnostic string) { - r.finishRunState(id, name, workspace, status, outcome, diagnostic, state.completed, state.nextSequence-1, state.key, state.input) + r.finishRunStateClass(id, name, workspace, status, outcome, diagnostic, state.completed, state.nextSequence-1, state.key, state.input, state.failureClass) } // canceled settles an operator cancel. A server shutdown is not a cancel: // the run is left exactly as persisted for the next process to continue. @@ -2058,11 +2136,17 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na } effectiveModels = resolved } + runBudget := r.runBudget(ctx, id) for sequence := state.nextSequence; sequence <= state.stepLimit(graph); sequence++ { if ctx.Err() != nil { canceled() return } + if budgetErr := runBudget.Check(); budgetErr != nil { + state.failureClass = protocol.FailureBudget + finish("failed", "error", budgetErr.Error()) + return + } key := state.key var def stage.Definition var selected protocol.Stage @@ -2106,6 +2190,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na } return } + state.failureClass = protocol.FailureLoopExhausted if state.visits[key]+1 > hardVisits { finish("failed", "error", "stage visit budget exceeded") return @@ -2362,6 +2447,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na // The budget is shared across every visit to this stage key, so capture // its cumulative usage before the visit and record only this visit's // increment on the step, never the cumulative total again. + budgets[key].SetRun(runBudget) budgetBefore = budgets[key].Snapshot() stageCtx = stage.WithBudget(stageCtx, budgets[key]) } @@ -2545,6 +2631,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na step.Output["salvage"] = result.Output } } + checkFailed := false if err == nil && result.Outcome == "success" { target, targetErr := stage.VerificationTargetFor(def) if targetErr != nil { @@ -2561,6 +2648,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na } } } + checkFailed = err != nil if err != nil { step.Status = "failed" step.Diagnostic = err.Error() @@ -2596,6 +2684,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na var catchUp string catchUp, err = verifyDelivery(gateCtx, workspace, landing, checks, r.deliveryCommitMessage(id)) gateCancel() + checkFailed = err != nil // A failed gate already carries the note in its diagnostic. A step // diagnostic on success renders as a stop, so success is logged. if catchUp != "" { @@ -2615,10 +2704,45 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na step.Transcript = stage.RetainSession(step.Transcript, stageSession) } step.Target = def.Edges[step.Outcome] + var quota quotaDecision if errors.Is(err, opencode.ErrProviderQuota) { - // Another visit would be refused the same way: stop the run on the - // provider's refusal instead of following the error edge again. + // Another visit would be refused the same way: never follow the + // error edge. A usage window that resets switches accounts or + // parks the run (run_quota.go); an empty balance stops it. step.Target = protocol.FailureEnd + if !errors.Is(err, stage.ErrStageCleanup) { + quota = r.decideQuota(ctx, workspace, err) + } + if quota.rerun || quota.park { + step.Target = key + if quota.rerun { + step.Diagnostic += "; switched Claude account, running the visit again" + } else { + step.Diagnostic += fmt.Sprintf("; the run waits for the reset and resumes this stage at %s", quota.resetsAt.Add(quotaResumeMargin).Local().Format("15:04 on 2 Jan")) + } + } + } + harnessKind := stage.HarnessFailureKind(err) + if err != nil && !quota.rerun && !quota.park && step.Target != protocol.FailureEnd { + switch { + case errors.Is(err, stage.ErrPermissionDenied), errors.Is(err, stage.ErrRunBudgetExceeded): + // Another visit is refused the same way. + step.Target = protocol.FailureEnd + case step.Target == key && harnessKind == stage.HarnessDeterministic: + step.Target = protocol.FailureEnd + step.Diagnostic += "; this harness failure repeats on every attempt, so the error loop was not followed" + case step.Target == key && harnessKind == stage.HarnessRepeatable && state.lastHarness[key] == harnessSignature(err): + step.Target = protocol.FailureEnd + step.Diagnostic += "; the same harness failure repeated, so the error loop was not followed" + } + } + if state.lastHarness == nil { + state.lastHarness = map[string]string{} + } + if harnessKind == stage.HarnessRepeatable { + state.lastHarness[key] = harnessSignature(err) + } else { + delete(state.lastHarness, key) } if errors.Is(err, stage.ErrStageCleanup) { // Retain the partial evidence without pretending that the agent stopped. @@ -2643,6 +2767,19 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na step.Target = protocol.FailureEnd parkExhausted = false } + switch { + case step.Control.LimitReached: + state.failureClass = protocol.FailureLoopExhausted + case checkFailed, stage.EffectiveType(def.Type) == stage.CheckType && step.Target == protocol.FailureEnd && !errors.Is(err, opencode.ErrProviderQuota): + // A delivery gate, verification target or check stage failed. + state.failureClass = protocol.FailureCheckFailed + case err != nil: + state.failureClass = stage.FailureClassOf(err) + case step.Target == protocol.FailureEnd: + state.failureClass = protocol.FailureBlocked + default: + state.failureClass = "" + } _, _, _, failedTerminal := terminalFinish(step.Target, step.Stage, step.Outcome, step.Diagnostic) if exportRequired && !completeSessionExport(sessionExport) && !(err != nil && failedTerminal && step.Target != protocol.SuccessEnd) { // Preserve the real computation, files, outcome and target. In @@ -2692,6 +2829,10 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na canceled() return } + if quota.park && !terminal { + r.parkForQuota(id, workspace, sequence, key, state.completed, quota) + return + } // Advance the in-memory UI-surface evidence only after the step is // persisted, so the skip guard agrees with what the store holds. state.recordChanges(step.FileChanges, step.Artifacts) @@ -2708,6 +2849,12 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na if stage.EffectiveType(def.Type) == stage.ModelType { r.recordFindings(id, state, step) } + } else if quota.rerun { + // The visit runs again on the switched account with its own + // input, told that the limit interrupted it; it does not count. + state.input = input + state.visits[key]-- + state.previousAttempt = quotaPreviousAttempt(key, quota.note) } else if step.Status == "failed" && step.Target != "" && step.Target != protocol.FailureEnd && step.Target != protocol.SuccessEnd { // The error edge leads to another stage: tell it what failed. @@ -2754,8 +2901,25 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na } return } + r.checkRunBudget(id, name, runBudget) + if step.Status == "completed" { + delete(state.errorLoops, key) + } else if step.Status == "failed" && step.Target == key && !quota.rerun && (harnessKind == stage.HarnessTransient || harnessKind == stage.HarnessRepeatable) { + // A transient harness failure looping back to its own stage waits + // before the next visit, longer each time (errorLoopBackoff). + if state.errorLoops == nil { + state.errorLoops = map[string]int{} + } + delay := errorLoopBackoff[min(state.errorLoops[key], len(errorLoopBackoff)-1)] + state.errorLoops[key]++ + if !sleepOrDone(ctx, delay) { + canceled() + return + } + } state.key = step.Target } + state.failureClass = protocol.FailureLoopExhausted finish("failed", "error", "total stage budget exceeded") } diff --git a/internal/server/websocket.go b/internal/server/websocket.go index 62511ca9..9d18e76d 100644 --- a/internal/server/websocket.go +++ b/internal/server/websocket.go @@ -14,6 +14,7 @@ import ( "git.a-wan.net/alan/pipelines/examples" "git.a-wan.net/alan/pipelines/internal/buildinfo" + "git.a-wan.net/alan/pipelines/internal/claude" "git.a-wan.net/alan/pipelines/internal/pipeline" "git.a-wan.net/alan/pipelines/internal/protocol" "git.a-wan.net/alan/pipelines/internal/summarise" @@ -554,7 +555,7 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin response.Error = err.Error() } } - } else if runs != nil && (request.Type == protocol.RunPipeline || request.Type == protocol.RetryRun || request.Type == protocol.ListRuns || request.Type == protocol.GetRun || request.Type == protocol.CancelRun || request.Type == protocol.DecideRun || request.Type == protocol.SetRunTitle || request.Type == protocol.GetRunEvidence || request.Type == protocol.RepairSessionExport || request.Type == protocol.DeleteRuns) { + } else if runs != nil && (request.Type == protocol.RunPipeline || request.Type == protocol.RetryRun || request.Type == protocol.ListRuns || request.Type == protocol.GetRun || request.Type == protocol.CancelRun || request.Type == protocol.DecideRun || request.Type == protocol.SetRunTitle || request.Type == protocol.GetRunEvidence || request.Type == protocol.RepairSessionExport || request.Type == protocol.DeleteRuns || request.Type == protocol.ResumeRun || request.Type == protocol.GetRunSettings || request.Type == protocol.SetRunSettings) { var err error switch request.Type { case protocol.DeleteRuns: @@ -598,6 +599,23 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin } else { response.RunDetail, err = runs.getRun(request.RunID) } + case protocol.ResumeRun: + response.Type = protocol.Run + response.RunDetail, err = runs.resumeQuota(request.RunID) + case protocol.GetRunSettings: + response.Type = protocol.RunSettingsReply + var settings protocol.RunSettings + settings, err = stores[0].RunSettings(connCtx) + response.RunSettings = &settings + case protocol.SetRunSettings: + response.Type = protocol.RunSettingsReply + if request.RunSettings == nil { + err = fmt.Errorf("set_run_settings requires run_settings") + } else { + var settings protocol.RunSettings + settings, err = stores[0].SetRunSettings(connCtx, *request.RunSettings) + response.RunSettings = &settings + } case protocol.CancelRun: response.Type = protocol.Run err = runs.cancel(request.RunID) @@ -657,9 +675,24 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin hub.watchUsageRefusals(options.Chat) } if runs != nil { + // A stage refused for a usage limit first tries the Claude account + // auto-switch chats use (the home's own setting decides). + if manager, ok := options.Chat.(*chatManager); ok { + runs.quota.switchAccount = func(ctx context.Context, workspace string, resetsAt time.Time) (string, string, error) { + switcher, ok := manager.harness(claude.Backend).(chatAutoSwitcher) + if !ok { + return "", "", errNotClaudeChat + } + result, err := switcher.AutoSwitchAccount(ctx, claude.UsageRefusal{Directory: workspace, ResetsAt: resetsAt}) + return result.From, result.To, err + } + } // Continue the runs a previous process left in flight, now that the // runner's collaborators are wired and before any request is served. runs.reattachRuns() + // Re-arm the resume of runs parked for a usage limit. + runs.armParkedRuns() + context.AfterFunc(ctx, runs.stopQuotaTimers) } return &runHandler{Handler: guardRequests(mux, options.AccessToken), runner: runs, hub: hub} } diff --git a/internal/stage/budget.go b/internal/stage/budget.go index 9d04b940..68392248 100644 --- a/internal/stage/budget.go +++ b/internal/stage/budget.go @@ -90,6 +90,8 @@ type reportedUsage struct { } type Budget struct { + // run is the whole-run cap this stage budget also counts towards. + run *RunBudget mu sync.Mutex state BudgetSnapshot records map[string]BudgetSnapshot @@ -108,6 +110,22 @@ func (b *Budget) RestoreUsage(used BudgetSnapshot) { used.LimitUSD, used.LimitTokens = b.state.LimitUSD, b.state.LimitTokens b.state = used } + +// SetRun makes the stage budget count its cost towards the whole-run cap. +func (b *Budget) SetRun(run *RunBudget) { b.mu.Lock(); b.run = run; b.mu.Unlock() } + +// watched reports whether a harness must poll usage: a stage limit or a +// whole-run cap is set. +func (b *Budget) watched() bool { + if b == nil { + return false + } + b.mu.Lock() + run := b.run + b.mu.Unlock() + return b.Enabled() || run.Enabled() +} + func (b *Budget) Enabled() bool { return b != nil && (b.state.LimitUSD > 0 || b.state.LimitTokens > 0) } func (b *Budget) Snapshot() BudgetSnapshot { b.mu.Lock(); defer b.mu.Unlock(); return b.state } @@ -154,13 +172,21 @@ func (b *Budget) checkLocked() error { } return nil } -func (b *Budget) Check() error { b.mu.Lock(); defer b.mu.Unlock(); return b.checkLocked() } +func (b *Budget) Check() error { + b.mu.Lock() + defer b.mu.Unlock() + if err := b.checkLocked(); err != nil { + return err + } + return b.run.Check() +} func (b *Budget) observe(key string, usage reportedUsage) error { b.mu.Lock() defer b.mu.Unlock() old := b.records[key] defer func() { b.records[key] = old }() + spentBefore := b.state.UsedUSD if usage.USD != nil { if *usage.USD < 0 || math.IsNaN(*usage.USD) || math.IsInf(*usage.USD, 0) { return fmt.Errorf("%w: invalid cost", ErrBudgetAccounting) @@ -231,7 +257,68 @@ func (b *Budget) observe(key string, usage reportedUsage) error { case b.state.LimitTokens > 0: return fmt.Errorf("%w: complete token usage was not reported", ErrBudgetAccounting) } - return b.checkLocked() + if err := b.checkLocked(); err != nil { + return err + } + return b.run.add(b.state.UsedUSD - spentBefore) +} + +// RunBudget is a run's whole-run USD cap, shared by every stage budget of +// the run. A nil or zero-limit RunBudget only counts. +type RunBudget struct { + mu sync.Mutex + limit float64 + spent float64 +} + +// NewRunBudget starts a run cap of limit USD (0 = none) with spent already +// used by earlier visits. +func NewRunBudget(limit, spent float64) *RunBudget { + return &RunBudget{limit: limit, spent: spent} +} + +func (r *RunBudget) Enabled() bool { return r != nil && r.limit > 0 } + +// Spent and Limit report the cap's state. +func (r *RunBudget) Spent() float64 { + if r == nil { + return 0 + } + r.mu.Lock() + defer r.mu.Unlock() + return r.spent +} + +func (r *RunBudget) Limit() float64 { + if r == nil { + return 0 + } + return r.limit +} + +func (r *RunBudget) add(usd float64) error { + if r == nil { + return nil + } + r.mu.Lock() + if usd > 0 { + r.spent += usd + } + r.mu.Unlock() + return r.Check() +} + +// Check fails with ErrRunBudgetExceeded once the run spent its cap. +func (r *RunBudget) Check() error { + if !r.Enabled() { + return nil + } + r.mu.Lock() + defer r.mu.Unlock() + if r.spent >= r.limit { + return fmt.Errorf("%w: %w: USD %.2f / %.2f", ErrBudgetExceeded, ErrRunBudgetExceeded, r.spent, r.limit) + } + return nil } type budgetContextKey struct{} @@ -239,6 +326,17 @@ type budgetContextKey struct{} func WithBudget(ctx context.Context, budget *Budget) context.Context { return context.WithValue(ctx, budgetContextKey{}, budget) } + +// BudgetFrom is the stage budget a visit runs under (nil when none); an +// in-process executor reports its cost with ObserveCost. +func BudgetFrom(ctx context.Context) *Budget { return budgetFromContext(ctx) } + +// ObserveCost reports a session's cumulative USD cost, as a harness usage +// report does, and fails once the stage or run cap is spent. +func (b *Budget) ObserveCost(session string, usd float64) error { + return b.observe(session, reportedUsage{USD: &usd}) +} + func budgetFromContext(ctx context.Context) *Budget { b, _ := ctx.Value(budgetContextKey{}).(*Budget) return b @@ -254,7 +352,7 @@ type budgetWatch struct { func (c OpenCodeClient) BudgetCapable() bool { return true } func (c OpenCodeClient) watchBudget(ctx context.Context, budget *Budget, id string) (context.Context, *budgetWatch, error) { - if !budget.Enabled() { + if !budget.watched() { return ctx, nil, nil } if err := budget.Check(); err != nil { diff --git a/internal/stage/claude_stage.go b/internal/stage/claude_stage.go index b84a03d1..3645045e 100644 --- a/internal/stage/claude_stage.go +++ b/internal/stage/claude_stage.go @@ -17,7 +17,6 @@ import ( "time" "git.a-wan.net/alan/pipelines/internal/claude" - "git.a-wan.net/alan/pipelines/internal/opencode" "git.a-wan.net/alan/pipelines/internal/workenv" ) @@ -71,6 +70,8 @@ type ClaudeStageClient struct { operatorPlugins []string budget *Budget + // denials are the tool uses the permission rules refused this visit. + denials []string // Session totals across the visit's invocations (the prompt and one // outcome follow-up share a session and report per invocation). usd float64 @@ -217,6 +218,7 @@ func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, pr // again. resume := TakeResumeSession(ctx) c.WorkStarted = false + c.denials = nil c.usd, c.input, c.output, c.reasoning, c.cacheRead, c.cacheW = 0, 0, 0, 0, 0, 0 c.budget = config.Budget if c.budget == nil { @@ -462,8 +464,117 @@ type claudeStreamRecord struct { ResetsAt int64 `json:"resetsAt"` } `json:"rate_limit_info"` Message *struct { - Error string `json:"error"` + Error string `json:"error"` + Content json.RawMessage `json:"content"` } `json:"message"` + // PermissionDenials are the tool uses the permission rules refused + // during the invocation (on the result record). + PermissionDenials []claudePermissionDenial `json:"permission_denials"` +} + +type claudePermissionDenial struct { + ToolName string `json:"tool_name"` + ToolInput map[string]any `json:"tool_input"` +} + +// maxReportedDenials bounds the denials named in a diagnostic. +const maxReportedDenials = 5 + +// describe names a denied tool use for the operator: the tool and the path +// or the start of the command it was refused for (bounded, one line). +func (d claudePermissionDenial) describe() string { + name := sanitizedClaudeName(d.ToolName) + target := "" + for _, key := range []string{"file_path", "path", "notebook_path", "command", "url", "pattern"} { + if value, ok := d.ToolInput[key].(string); ok && strings.TrimSpace(value) != "" { + target = strings.Join(strings.Fields(value), " ") + break + } + } + if target == "" { + return name + } + if len([]rune(target)) > 80 { + target = string([]rune(target)[:80]) + "..." + } + return name + "(" + target + ")" +} + +// PermissionDenials names the tool uses the visit's permission rules refused. +func (c *ClaudeStageClient) PermissionDenials() []string { return c.denials } + +func (c *ClaudeStageClient) noteDenial(description string) { + for _, seen := range c.denials { + if seen == description { + return + } + } + if len(c.denials) < maxReportedDenials { + c.denials = append(c.denials, description) + } +} + +// claudePermissionRefusal matches the tool_result text Claude Code returns for +// a tool use its permission mode refused. +func claudePermissionRefusal(text string) bool { + lower := strings.ToLower(text) + return strings.Contains(lower, "requested permissions to") || (strings.Contains(lower, "permission") && strings.Contains(lower, "denied")) +} + +// toolResultDenials scans a user message's tool results for permission +// refusals of the tool uses named in uses (tool_use id -> description). +func toolResultDenials(content json.RawMessage, uses map[string]string) []string { + var blocks []struct { + Type string `json:"type"` + ToolUseID string `json:"tool_use_id"` + IsError bool `json:"is_error"` + Content json.RawMessage `json:"content"` + } + if json.Unmarshal(content, &blocks) != nil { + return nil + } + var denied []string + for _, block := range blocks { + if block.Type != "tool_result" || !block.IsError { + continue + } + var text string + if json.Unmarshal(block.Content, &text) != nil { + var parts []struct { + Text string `json:"text"` + } + _ = json.Unmarshal(block.Content, &parts) + for _, part := range parts { + text += part.Text + } + } + if claudePermissionRefusal(text) { + name := uses[block.ToolUseID] + if name == "" { + name = "a tool" + } + denied = append(denied, name) + } + } + return denied +} + +// toolUses records the tool_use blocks of an assistant message. +func toolUses(content json.RawMessage, uses map[string]string) { + var blocks []struct { + Type string `json:"type"` + ID string `json:"id"` + Name string `json:"name"` + Input map[string]any `json:"input"` + } + if json.Unmarshal(content, &blocks) != nil { + return + } + for _, block := range blocks { + if block.Type == "tool_use" && block.ID != "" && len(uses) < 4096 { + uses[block.ID] = claudePermissionDenial{ToolName: block.Name, ToolInput: block.Input}.describe() + } + } } // claudeInvocation is what one CLI invocation's stream-json output reported. @@ -472,6 +583,10 @@ type claudeInvocation struct { refusal, limited bool resetsAt int64 authFailed, sessionMismatch, modelMismatch bool + // uses names the invocation's tool_use blocks (id -> description) and + // denials the uses the permission rules refused. + uses map[string]string + denials []string } func (inv *claudeInvocation) observe(record claudeStreamRecord, session, model string) { @@ -486,24 +601,39 @@ func (inv *claudeInvocation) observe(record claudeStreamRecord, session, model s inv.limited = true inv.resetsAt = record.RateLimit.ResetsAt } + case "user": + if record.Message != nil { + inv.denials = append(inv.denials, toolResultDenials(record.Message.Content, inv.uses)...) + } case "assistant": if record.Message != nil { + if inv.uses == nil { + inv.uses = map[string]string{} + } + toolUses(record.Message.Content, inv.uses) switch record.Message.Error { - case "billing_error", "rate_limit": + case "billing_error": inv.refusal = true + case "rate_limit": + inv.refusal, inv.limited = true, true case "authentication_failed": inv.authFailed = true } } switch record.Error { - case "billing_error", "rate_limit": + case "billing_error": inv.refusal = true + case "rate_limit": + inv.refusal, inv.limited = true, true case "authentication_failed": inv.authFailed = true } case "result": copied := record inv.final = &copied + for _, denial := range record.PermissionDenials { + inv.denials = append(inv.denials, denial.describe()) + } } } @@ -770,6 +900,9 @@ func (c *ClaudeStageClient) settle(ctx context.Context, proc *claudeProcess, inv if ctx.Err() != nil { return "", ctx.Err() } + for _, denial := range inv.denials { + c.noteDenial(denial) + } final := inv.final if final != nil { if usageErr := c.observe(final); usageErr != nil { @@ -779,13 +912,21 @@ func (c *ClaudeStageClient) settle(ctx context.Context, proc *claudeProcess, inv switch { case inv.authFailed: return "", fmt.Errorf("%w: %w", ErrHarnessTransport, errClaudeSignedOut) - case inv.refusal || (inv.limited && (final == nil || final.IsError)): - if inv.resetsAt > 0 { - // A usage window, not an empty account: say when it reopens (a - // time only; no provider text is copied). - return "", fmt.Errorf("%w: %w; the Claude usage limit resets at %s", ErrHarnessTransport, opencode.ErrProviderQuota, time.Unix(inv.resetsAt, 0).Format("15:04 on 2 Jan")) + case inv.refusal || (inv.limited && (final == nil || final.IsError)) || (final != nil && final.IsError && claudeUsageLimitText(final.Result)): + if inv.limited || !inv.refusal { + // A subscription usage window, not an empty account: say when it + // reopens (a time only; no provider text is copied). + quota := &QuotaError{Subscription: true} + if inv.resetsAt > 0 { + quota.ResetsAt = time.Unix(inv.resetsAt, 0) + } else if final != nil { + if at, ok := claude.UsageLimitResetIn(final.Result, time.Now()); ok { + quota.ResetsAt = at + } + } + return "", fmt.Errorf("%w: %w", ErrHarnessTransport, quota) } - return "", fmt.Errorf("%w: %w", ErrHarnessTransport, opencode.ErrProviderQuota) + return "", fmt.Errorf("%w: %w", ErrHarnessTransport, &QuotaError{}) case inv.sessionMismatch || inv.modelMismatch: return "", fmt.Errorf("%w: Claude Code did not start the requested session and model", ErrHarnessTransport) case final == nil && proc.adopted: @@ -803,6 +944,12 @@ func (c *ClaudeStageClient) settle(ctx context.Context, proc *claudeProcess, inv return final.Result, nil } +// claudeUsageLimitText reports whether a result's text is Claude Code's +// usage-limit refusal (the text is only matched, never copied). +func claudeUsageLimitText(text string) bool { + return claude.IsUsageLimitText(text) +} + // claudeProcessAlive reports whether pid is a live (not zombie) process whose // command line names the session, so a recorded pid the system reused is never // mistaken for the stage's CLI. diff --git a/internal/stage/claude_stage_test.go b/internal/stage/claude_stage_test.go index 7a32dac2..852cd423 100644 --- a/internal/stage/claude_stage_test.go +++ b/internal/stage/claude_stage_test.go @@ -92,6 +92,18 @@ case "$FAKE_CLAUDE_CASE" in echo '{"type":"result","subtype":"success","is_error":true,"result":"PROVIDER-BODY-SECRET","session_id":"'"$session"'",'"$usage"'}' exit 1 ;; + ratelimit) + init "$session" "$model" + echo '{"type":"assistant","session_id":"'"$session"'","error":"rate_limit","message":{"role":"assistant","error":"rate_limit","content":[{"type":"text","text":"Claude AI usage limit reached|1794409200"}]}}' + echo '{"type":"result","subtype":"success","is_error":true,"result":"Claude AI usage limit reached|1794409200","session_id":"'"$session"'",'"$usage"'}' + exit 1 + ;; + denied) + init "$session" "$model" + echo '{"type":"assistant","session_id":"'"$session"'","message":{"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"Edit","input":{"file_path":"/etc/hosts"}}]}}' + echo '{"type":"user","session_id":"'"$session"'","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","is_error":true,"content":"Claude requested permissions to write to /etc/hosts, but you have not granted it yet."}]}}' + printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"result":"# outcome\nblocked\n","session_id":"'"$session"'","permission_denials":[{"tool_name":"Bash","tool_use_id":"t2","tool_input":{"command":"git push origin main"}}],'"$usage"'}' + ;; auth) init "$session" "$model" echo '{"type":"assistant","session_id":"'"$session"'","error":"authentication_failed","message":{"role":"assistant","content":[{"type":"text","text":"PROVIDER-BODY-SECRET"}]}}' @@ -375,7 +387,15 @@ func TestClaudeStageFailuresAreFixedText(t *testing.T) { "quota": func(err error) bool { return errors.Is(err, opencode.ErrProviderQuota) }, // A usage window names when it reopens. "limited": func(err error) bool { - return errors.Is(err, opencode.ErrProviderQuota) && strings.Contains(err.Error(), "usage limit resets at") + at, ok := QuotaResetsAt(err) + return errors.Is(err, opencode.ErrProviderQuota) && SubscriptionQuota(err) && ok && at.Unix() == 1794409200 && + strings.Contains(err.Error(), "resets at") && !strings.Contains(err.Error(), "top up") + }, + // A subscription refusal named only by the assistant's error and + // the CLI's own text still parks with the reset the text names. + "ratelimit": func(err error) bool { + at, ok := QuotaResetsAt(err) + return errors.Is(err, opencode.ErrProviderQuota) && SubscriptionQuota(err) && ok && at.Unix() == 1794409200 && !strings.Contains(err.Error(), "top up") }, "auth": func(err error) bool { return errors.Is(err, errClaudeSignedOut) }, "maxturns": func(err error) bool { return strings.Contains(err.Error(), "(error_max_turns)") }, diff --git a/internal/stage/failure_class.go b/internal/stage/failure_class.go new file mode 100644 index 00000000..07c23484 --- /dev/null +++ b/internal/stage/failure_class.go @@ -0,0 +1,139 @@ +package stage + +import ( + "context" + "errors" + "fmt" + "strings" + "time" + + "git.a-wan.net/alan/pipelines/internal/opencode" + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// QuotaError is a provider usage-limit refusal. It matches +// opencode.ErrProviderQuota with errors.Is. ResetsAt is when the limit resets +// (zero when the refusal did not say). A subscription window (Claude's 5-hour +// or weekly limit) is not an empty account, so its text never asks the +// operator to top anything up. +type QuotaError struct { + ResetsAt time.Time + Subscription bool +} + +func (e *QuotaError) Error() string { + if !e.Subscription { + return opencode.ErrProviderQuota.Error() + } + if e.ResetsAt.IsZero() { + return "the Claude usage limit was reached; the run continues when it resets" + } + return "the Claude usage limit was reached; it resets at " + e.ResetsAt.Local().Format("15:04 on 2 Jan") +} + +func (e *QuotaError) Unwrap() error { return opencode.ErrProviderQuota } + +// QuotaResetsAt returns the reset time a usage-limit error carries. +func QuotaResetsAt(err error) (time.Time, bool) { + var quota *QuotaError + if errors.As(err, "a) && !quota.ResetsAt.IsZero() { + return quota.ResetsAt, true + } + return time.Time{}, false +} + +// SubscriptionQuota reports whether err is a subscription usage window (one +// that resets on its own), as opposed to an exhausted paid balance. +func SubscriptionQuota(err error) bool { + var quota *QuotaError + return errors.As(err, "a) && quota.Subscription +} + +// ErrPermissionDenied is a stage whose declared tool use was refused by the +// harness's permission rules and that then gave up (answered blocked or +// error) instead of finishing its work. +var ErrPermissionDenied = errors.New("tool permission denied") + +// PermissionDeniedError names the refused tool uses (bounded). +type PermissionDeniedError struct{ Denials []string } + +func (e *PermissionDeniedError) Error() string { + return fmt.Sprintf("%s: %s; widen the stage's tools or run write paths, or change the task", ErrPermissionDenied, strings.Join(e.Denials, ", ")) +} + +func (e *PermissionDeniedError) Unwrap() error { return ErrPermissionDenied } + +// permissionDenier is a client that observed tool permission denials. +type permissionDenier interface{ PermissionDenials() []string } + +// ErrRunBudgetExceeded is the whole-run USD cap; it also matches +// ErrBudgetExceeded. +var ErrRunBudgetExceeded = errors.New("run budget exceeded") + +// Harness failure kinds (HarnessFailureKind). +const ( + HarnessTransient = "transient" + HarnessDeterministic = "deterministic" + // HarnessRepeatable is a harness failure that is deterministic when it + // repeats on the next visit of the same stage (an empty readback). + HarnessRepeatable = "repeatable" +) + +// HarnessFailureKind classifies a stage failure for the runner's error-loop +// policy: transient failures (network, 5xx, overloaded, timeouts) are worth +// another visit after a backoff; deterministic ones (authentication, +// invalid arguments, a configuration the harness refuses) fail the same way +// every time. "" means the error is not a harness failure. +func HarnessFailureKind(err error) string { + if err == nil || errors.Is(err, opencode.ErrProviderQuota) || errors.Is(err, ErrBudgetExceeded) || errors.Is(err, context.Canceled) { + return "" + } + if errors.Is(err, ErrPermissionDenied) || errors.Is(err, errClaudeSignedOut) || errors.Is(err, errClaudeMissing) { + return HarnessDeterministic + } + text := strings.ToLower(err.Error()) + for _, marker := range []string{"authentication", "unauthorized", "invalid api key", "invalid argument", "invalid_request", "unknown option", "unknown model", "model not found", "not supported", "cannot enforce", "needs provider", "did not start the requested session and model"} { + if strings.Contains(text, marker) { + return HarnessDeterministic + } + } + if strings.Contains(text, "readback contained no assistant message") { + return HarnessRepeatable + } + if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, ErrHarnessUnreachable) { + return HarnessTransient + } + for _, marker := range []string{"timeout", "timed out", "connection refused", "connection reset", "broken pipe", "eof", "no such host", "network", "overloaded", "529", "502", "503", "504", "500 internal", "temporarily", "try again"} { + if strings.Contains(text, marker) { + return HarnessTransient + } + } + if harnessTransportFailure(err) { + return HarnessTransient + } + return "" +} + +// FailureClassOf maps a stage error to the run failure class it causes. +func FailureClassOf(err error) string { + var deadline *stageDeadlineError + switch { + case err == nil: + return "" + case errors.Is(err, opencode.ErrProviderQuota): + return protocol.FailureQuota + case errors.Is(err, ErrBudgetExceeded): + return protocol.FailureBudget + case errors.Is(err, ErrPermissionDenied): + return protocol.FailurePermissionDenied + case errors.Is(err, context.Canceled): + return protocol.FailureCanceled + case errors.Is(err, errClaudeSignedOut), errors.Is(err, errClaudeMissing), errors.Is(err, ErrHarnessUnreachable): + return protocol.FailureEnvironment + case errors.As(err, &deadline), errors.Is(err, context.DeadlineExceeded): + return protocol.FailureTimeout + case harnessTransportFailure(err), errors.Is(err, ErrStageCleanup), errors.Is(err, ErrBudgetAccounting): + return protocol.FailureHarnessError + } + return protocol.FailureOther +} diff --git a/internal/stage/failure_class_test.go b/internal/stage/failure_class_test.go new file mode 100644 index 00000000..0a006b52 --- /dev/null +++ b/internal/stage/failure_class_test.go @@ -0,0 +1,84 @@ +package stage + +import ( + "context" + "errors" + "fmt" + "strings" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/opencode" + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +func TestClaudeStagePermissionDenialFailsABlockedVisit(t *testing.T) { + client, _, _ := fakeClaudeClient(t, "denied") + def := modelDefinition() + def.Configs = map[string]string{"harness": ClaudeBackend, "provider": ClaudeProvider, "model": "claude-haiku-5-5", "retries": "0"} + def.Blocks["configs"] = "harness=claude\nprovider=anthropic\nmodel=claude-haiku-5-5\nretries=0" + def.Edges = map[string]string{"success": protocol.SuccessEnd, "blocked": protocol.FailureEnd, "error": protocol.FailureEnd} + _, err := (ModelStage{Client: client}).Run(context.Background(), def, nil) + if !errors.Is(err, ErrPermissionDenied) || FailureClassOf(err) != protocol.FailurePermissionDenied { + t.Fatal(err) + } + for _, want := range []string{"Edit(/etc/hosts)", "Bash(git push origin main)"} { + if !strings.Contains(err.Error(), want) { + t.Fatalf("diagnostic %q does not name %s", err, want) + } + } + if HarnessFailureKind(err) != HarnessDeterministic { + t.Fatal("a permission denial repeats on the next visit") + } +} + +func TestQuotaErrorWording(t *testing.T) { + reset := time.Date(2026, 12, 3, 9, 0, 0, 0, time.UTC) + subscription := fmt.Errorf("%w: %w", ErrHarnessTransport, &QuotaError{Subscription: true, ResetsAt: reset}) + if !errors.Is(subscription, opencode.ErrProviderQuota) || strings.Contains(subscription.Error(), "top up") { + t.Fatal(subscription) + } + if at, ok := QuotaResetsAt(subscription); !ok || !at.Equal(reset) { + t.Fatal(at, ok) + } + balance := &QuotaError{} + if !strings.Contains(balance.Error(), "top up") || SubscriptionQuota(balance) { + t.Fatal("an exhausted paid balance keeps the top-up advice") + } + if FailureClassOf(subscription) != protocol.FailureQuota || HarnessFailureKind(subscription) != "" { + t.Fatal("quota is its own class, never a harness retry") + } +} + +func TestHarnessFailureKinds(t *testing.T) { + for _, tc := range []struct { + err error + kind string + }{ + {fmt.Errorf("%w: connection refused", ErrHarnessUnreachable), HarnessTransient}, + {&openCodeError{status: 503}, HarnessTransient}, + {fmt.Errorf("%w: the provider is overloaded", ErrHarnessTransport), HarnessTransient}, + {fmt.Errorf("x: %w", context.DeadlineExceeded), HarnessTransient}, + {fmt.Errorf("%w: final assistant readback contained no assistant message", ErrHarnessTransport), HarnessRepeatable}, + {fmt.Errorf("%w: %w", ErrHarnessTransport, errClaudeSignedOut), HarnessDeterministic}, + {fmt.Errorf("%w: invalid argument --tools", ErrHarnessTransport), HarnessDeterministic}, + {errors.New("plain stage error"), ""}, + {fmt.Errorf("%w: USD 2 / 1", ErrBudgetExceeded), ""}, + } { + if got := HarnessFailureKind(tc.err); got != tc.kind { + t.Errorf("%v: kind %q, want %q", tc.err, got, tc.kind) + } + } + for err, class := range map[error]string{ + fmt.Errorf("%w: %w", ErrBudgetExceeded, ErrRunBudgetExceeded): protocol.FailureBudget, + &stageDeadlineError{timeout: time.Second}: protocol.FailureTimeout, + fmt.Errorf("%w: x", ErrHarnessTransport): protocol.FailureHarnessError, + fmt.Errorf("%w: x", ErrHarnessUnreachable): protocol.FailureEnvironment, + context.Canceled: protocol.FailureCanceled, + errors.New("anything else"): protocol.FailureOther, + } { + if got := FailureClassOf(err); got != class { + t.Errorf("%v: class %q, want %q", err, got, class) + } + } +} diff --git a/internal/stage/model_run.go b/internal/stage/model_run.go index cd920681..c761703a 100644 --- a/internal/stage/model_run.go +++ b/internal/stage/model_run.go @@ -90,6 +90,13 @@ func (m ModelStage) Run(ctx context.Context, def Definition, input Values) (Resu } cancel() if resultErr == nil { + // A stage that gave up after its tool use was refused failed on + // the permission rules, not on the task: say which use. + if denier, ok := client.(permissionDenier); ok && (result.Outcome == "blocked" || result.Outcome == "error") { + if denials := denier.PermissionDenials(); len(denials) > 0 { + return result, wrapModelStageFailure(def.Key, &PermissionDeniedError{Denials: denials}) + } + } return result, nil } // A malformed final result mutates nothing on an explicit read-only diff --git a/internal/tui/cli_run.go b/internal/tui/cli_run.go index 9468cf80..18de4a62 100644 --- a/internal/tui/cli_run.go +++ b/internal/tui/cli_run.go @@ -19,6 +19,9 @@ type RunOptions struct { Model string StageModels map[string]string NotifyMode string + // QuotaPolicy and BudgetUSD pass the CLI's --now/--defer and --budget. + QuotaPolicy string + BudgetUSD float64 } func NewRun(ctx context.Context, url string, options RunOptions) Model { diff --git a/internal/tui/dashboard.go b/internal/tui/dashboard.go index 7d87f553..8c63d8f4 100644 --- a/internal/tui/dashboard.go +++ b/internal/tui/dashboard.go @@ -107,6 +107,9 @@ func (m Model) homeLines() []string { if r.Status == protocol.RunStatusWaiting { runs = append(runs, "Waiting on a person · stage "+r.CurrentStage) } + if r.Status == protocol.RunStatusWaitingQuota && r.QuotaWait != nil { + runs = append(runs, "Waiting for the usage limit · resumes "+quotaResumeClock(r.QuotaWait.ResumeAt)) + } runs = append(runs, "") } if len(m.runs) > limit { diff --git a/internal/tui/run_detail.go b/internal/tui/run_detail.go index ea143a7e..3c5c9bde 100644 --- a/internal/tui/run_detail.go +++ b/internal/tui/run_detail.go @@ -269,7 +269,7 @@ func runStatus(status string) string { color = themeError case "running", "queued": color = themeAccent - case protocol.RunStatusWaiting: + case protocol.RunStatusWaiting, protocol.RunStatusWaitingQuota: color = themeAccent } return lipgloss.NewStyle().Foreground(color).Render(status) diff --git a/internal/tui/run_progress.go b/internal/tui/run_progress.go index 79d9e61e..ce36acbf 100644 --- a/internal/tui/run_progress.go +++ b/internal/tui/run_progress.go @@ -1,6 +1,8 @@ package tui import ( + "time" + "git.a-wan.net/alan/pipelines/internal/protocol" "github.com/charmbracelet/lipgloss" ) @@ -30,6 +32,9 @@ func (m Model) progress(status string) string { case protocol.RunStatusWaiting: marker = "⏸" color = themeAccent + case protocol.RunStatusWaitingQuota: + marker = "⧗" + color = themeAccent } return lipgloss.NewStyle().Foreground(color).Render(marker + " " + status) } @@ -51,3 +56,12 @@ func (m Model) stepProgressStatus(step protocol.RunStep) string { } return status } + +// quotaResumeClock is a parked run's resume time in local wall-clock time. +func quotaResumeClock(value string) string { + at, err := time.Parse(time.RFC3339, value) + if err != nil { + return value + } + return at.Local().Format("15:04 Mon") +} diff --git a/internal/tui/runs.go b/internal/tui/runs.go index ce018a37..1823ae25 100644 --- a/internal/tui/runs.go +++ b/internal/tui/runs.go @@ -147,7 +147,7 @@ func (m *Model) startSelectedRun() tea.Cmd { m.runCollapsed = nil m.runDetail = nil m.runTop = 0 - request := protocol.Message{Type: protocol.RunPipeline, PipelineID: m.detail.ID, Version: m.detail.Version, RequestKey: fmt.Sprintf("tui-%d", time.Now().UnixNano()), Title: m.cliOptions.Title, Input: initialRunInput(m.runTask), AllowTools: m.runHasMutationTools(), WritePaths: m.runPaths, Workspace: m.runWorkspace, Model: m.cliOptions.Model, StageModels: m.cliOptions.StageModels, NotifyMode: m.cliOptions.NotifyMode, OutputFormat: m.cliOptions.OutputFormat} + request := protocol.Message{Type: protocol.RunPipeline, PipelineID: m.detail.ID, Version: m.detail.Version, RequestKey: fmt.Sprintf("tui-%d", time.Now().UnixNano()), Title: m.cliOptions.Title, Input: initialRunInput(m.runTask), AllowTools: m.runHasMutationTools(), WritePaths: m.runPaths, Workspace: m.runWorkspace, Model: m.cliOptions.Model, StageModels: m.cliOptions.StageModels, NotifyMode: m.cliOptions.NotifyMode, OutputFormat: m.cliOptions.OutputFormat, QuotaPolicy: m.cliOptions.QuotaPolicy, BudgetUSD: m.cliOptions.BudgetUSD} updated, cmd := m.runRequest(request) *m = updated.(Model) return cmd diff --git a/internal/turn/attempt.go b/internal/turn/attempt.go index c6918540..1a0f02c3 100644 --- a/internal/turn/attempt.go +++ b/internal/turn/attempt.go @@ -20,6 +20,10 @@ type PreviousAttempt struct { Diagnostic string // Run is the failed source run for a run retry; 0 for an in-stage retry. Run int64 + // Interruption, when set, says the previous attempt did not fail on its + // own but was stopped from outside (a provider usage limit); it replaces + // the failure wording and the diagnostic. + Interruption string } // RenderPreviousAttempt renders a bounded "# Previous attempt" section that @@ -36,6 +40,13 @@ func RenderPreviousAttempt(p PreviousAttempt) string { if stageName == "" { stageName = "unknown" } + if interruption := strings.TrimSpace(p.Interruption); interruption != "" { + fmt.Fprintf(&b, "This is attempt %d of stage %s. The previous attempt did not fail on its own: it was interrupted.", attempt, capLine(stageName, essentialLineCap)) + b.WriteString(" Partial edits from it may still be in the worktree; check them (for example with git status and git diff) and continue from them instead of redoing work.\n\n") + b.WriteString(capLine(oneLine(interruption), PreviousAttemptCap)) + b.WriteString("\n") + return b.String() + } if p.Run > 0 { fmt.Fprintf(&b, "This is attempt %d. The previous attempt (run %d) failed in stage %s.", attempt, p.Run, capLine(stageName, essentialLineCap)) } else {