Repository navigation
Expand file tree
/
Copy patherrors.py
More file actions
2000 lines (1692 loc) · 86.1 KB
/
Copy patherrors.py
File metadata and controls
2000 lines (1692 loc) · 86.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import json
import os
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal, TypedDict, cast, get_args
if TYPE_CHECKING:
from collections.abc import Callable
from gflow_cli.diagnostics import IncidentRef
__all__ = [
"CHARGED_VALUES",
"CONTENT_SAFETY_REASONS",
"EXIT_CODE_MAP",
"NEXT_ACTION_VALUES",
"RETRYABLE_ERRORS",
"RETRY_ACTIONS",
"Charged",
"NextAction",
"AisandboxAuthError",
"AuthExpiredError",
"AuthLoginTimeoutError",
"AuthMissingError",
"BatchIntegrityError",
"BatchPartialError",
"BrowserEngineUnavailableError",
"ChainManifestError",
"ChainPartialError",
"ConfigurationError",
"ContentPolicyError",
"CreditCapExceededError",
"DataIntegrityError",
"DataMigrationError",
"DataStoreError",
"ExtendUnavailableError",
"FlowAgentUiError",
"FlowApiError",
"FlowAppError",
"FlowAccessUnavailableError",
"FlowAccountChooserError",
"FlowHostMigratedError",
"FrameExtractionError",
"GFlowError",
"IdentityRecheckPendingError",
"MediaAttributionError",
"MediaUploadRejectedError",
"ReferenceNotFoundError",
"MentionIndexUnavailableError",
"ModelModeIncompatibilityError",
"MediaDownloadError",
"NetworkError",
"OwnerEvidence",
"ProblemDetails",
"ProfileAccessError",
"QueueSchemaError",
"RateLimitError",
"RecaptchaError",
"RpcResponseUnavailableError",
"SceneConcatError",
"SecurityError",
"ServerCancelUnavailableError",
"SyncPartialError",
"TaskCancelledError",
"TaskNotFoundError",
"TransportTimeoutError",
"UiModeUnavailableError",
"UiSelectorDriftError",
"UpscaleUnavailableError",
"VideoModelSelectionError",
"VideoAssemblyError",
"WafRejectionError",
"WireFormatError",
"active_exit_code",
"active_exit_code_mode",
"classify_content_safety",
"exit_code_for",
"is_retryable",
"legacy_exit_code_for",
"outcome_members",
"nothing_submitted",
]
#: Whether Flow may have billed the failed operation (#1201).
Charged = Literal["no", "maybe", "yes"]
#: What a caller should do next (#1201). See docs/ERRORS.md for each value's meaning.
NextAction = Literal["retry", "retry_after", "wait", "reauth", "fix_input", "reconcile", "none"]
CHARGED_VALUES: frozenset[str] = frozenset(get_args(Charged))
NEXT_ACTION_VALUES: frozenset[str] = frozenset(get_args(NextAction))
#: The actions that mean "run it again": ``retryable`` is true exactly for these.
RETRY_ACTIONS: frozenset[str] = frozenset({"retry", "retry_after"})
def outcome_members(charged: Charged, next_action: NextAction) -> dict[str, Any]:
"""``charged`` / ``next_action`` / ``retryable`` for an envelope built by hand (#1201)."""
return {
"charged": charged,
"next_action": next_action,
"retryable": next_action in RETRY_ACTIONS,
}
class ProblemDetails(TypedDict, total=False):
"""RFC 9457 Problem Details JSON shape (https://datatracker.ietf.org/doc/html/rfc9457).
gflow extensions: `remediation_hint`, `route`, `incident`, and (#1201) `charged`,
`next_action`, `operation_id`."""
type: str # required
title: str # required
status: int # optional — only the literal HTTP status of the failed call
detail: str # optional
instance: str # optional — `gflow:error:<correlation_id>`
remediation_hint: str # gflow extension
route: str # gflow extension — sanitized route name, NOT full URL
incident: dict[str, str] # gflow extension — remote-safe {id, capture_status} ONLY
charged: Charged # gflow extension (#1201) — always present
next_action: NextAction # gflow extension (#1201) — always present, agrees with retryable
operation_id: str # gflow extension (#1201) — local job / media id, when one exists
retry_after: float # gflow extension (#1201) — seconds, with next_action retry_after
completed_media_ids: list[str] # gflow extension (#1201) — a partial chain's billed links
quoted: int | None # gflow extension — Flow's pre-submit credit quote
max_credits: int # gflow extension — caller's credit ceiling
class GFlowError(Exception):
"""Base class for all gflow domain errors. Library-wide root.
Field shape: RFC 9457 Problem Details. Class-level (`problem_type`,
`title`, `_default_remediation`) define stable identity per class.
Instance-level (`detail`, `status`, `instance`, `remediation_hint`,
`route`) populated per raise.
`instance` is `gflow:error:<correlation_id>` (per-occurrence ID), NOT
the failed route URL — RFC 9457 §3.5 says `instance` identifies the
occurrence, not the endpoint. Route name lives in the `route` extension.
"""
problem_type: str = "about:blank"
title: str = "Error"
_default_remediation: str = ""
#: Set post-raise by the incident capture boundary (diagnostics design).
#: ``to_problem_details()`` exposes only the remote-safe {id, capture_status}
#: projection; the local path/artifacts stay CLI-local (S21).
incident_ref: IncidentRef | None = None
#: Per-instance override of this class's ``RETRYABLE_ERRORS`` membership; ``None``
#: keeps it. It lived on ``FlowAppError`` while that was the only producer, whose
#: comment set the condition for promoting it: "move it up if, and only if, a second
#: class needs it." #799 is the second — a migrated account whose composer is
#: agent-only raises ``FlowAgentUiError``, which is in ``RETRYABLE_ERRORS`` for the
#: labs A/B cohort that flaps, while which composer an account gets does not.
#: ``is_retryable`` reads it by ``getattr``.
#:
#: **Not every subclass accepts it.** Those declaring their own ``__init__``
#: (``RateLimitError``, ``WireFormatError``, ``BatchPartialError``,
#: ``BatchIntegrityError``, ``ChainPartialError``, ``SyncPartialError``) do not
#: forward it and raise ``TypeError`` — deliberately left that way rather than
#: threaded through six constructors no raise site passes it to. The failure is
#: LOUD, which is the property that matters: a silently dropped ``retryable=False``
#: would hand a caller a doomed retry nobody could explain. Add it to a subclass
#: when a raise site there actually needs it; ``test_errors_classification.py`` pins
#: the current split so this note cannot quietly go stale.
retryable: bool | None = None
#: #1201 defaults. Every class in ``EXIT_CODE_MAP`` declares its own (a test
#: enforces it); a raise site overrides them through ``__init__``. ``charged`` is
#: ``no`` only where the class proves nothing was submitted.
charged: Charged = "maybe"
next_action: NextAction = "none"
operation_id: str = ""
def __init__(
self,
detail: str = "",
*,
status: int | None = None,
instance: str | None = None,
route: str = "",
remediation_hint: str | None = None,
retryable: bool | None = None,
charged: Charged | None = None,
next_action: NextAction | None = None,
operation_id: str | None = None,
) -> None:
message = self.title if not detail else f"{self.title}: {detail}"
super().__init__(message)
self.detail = detail
self.status = status
self.instance = instance or ""
self.route = route
self.retryable = retryable
self.remediation_hint = (
remediation_hint if remediation_hint is not None else self._default_remediation
)
if charged is not None:
self.charged = charged
if operation_id is not None:
self.operation_id = operation_id
if next_action is not None:
self.next_action = next_action
# The explicit action decides retryability unless the site also set it.
if retryable is None:
self.retryable = next_action in RETRY_ACTIONS
def resolved_next_action(self) -> NextAction:
"""``next_action``, reconciled with ``is_retryable`` at emit time.
A raise site (or ``client.py``, after construction) may flip ``retryable``
without naming an action; the class default then contradicts the flag. A flip
to retryable reads ``retry``; a flip away reads ``reconcile`` when Flow may
have billed (a post-submit timeout), else ``none``.
"""
retryable = is_retryable(self)
if (self.next_action in RETRY_ACTIONS) == retryable:
return self.next_action
if retryable:
return "retry"
return "none" if self.charged == "no" else "reconcile"
def to_problem_details(self) -> ProblemDetails:
out: ProblemDetails = {
"type": self.problem_type,
"title": self.title,
}
if self.status is not None:
out["status"] = self.status
if self.detail:
out["detail"] = self.detail
if self.instance:
out["instance"] = self.instance
if self.remediation_hint:
out["remediation_hint"] = self.remediation_hint
if self.route:
out["route"] = self.route
if self.incident_ref is not None:
out["incident"] = {
"id": self.incident_ref.id,
"capture_status": self.incident_ref.capture_status,
}
out["charged"] = self.charged
out["next_action"] = self.resolved_next_action()
if self.operation_id:
out["operation_id"] = self.operation_id
return out
class nothing_submitted: # noqa: N801 - used as a lowercase `with` statement
"""Mark every gflow error raised inside as ``charged="no"``: no request has left yet.
Wrap only code that runs before the generation submit. A class default of ``maybe``
would otherwise answer for every pre-submit raise site, telling the caller to
reconcile a charge that cannot exist (#1320). The exception always propagates.
``sent``, when given, reports whether a submit request was seen inside the region
(a stray keystroke can submit); the override is then withheld."""
def __init__(self, sent: Callable[[], bool] | None = None) -> None:
self._sent = sent
def __enter__(self) -> None:
return None
def __exit__(self, _type: object, exc: BaseException | None, _tb: object) -> None:
if isinstance(exc, GFlowError) and not (self._sent is not None and self._sent()):
exc.charged = "no"
class FlowApiError(GFlowError):
"""Parent of all API-related errors. Retained as a named parent class so
`except FlowApiError` continues to catch typed subclasses below.
Constructor accepts BOTH the legacy 3-arg form (Phase 3 callers) AND
the new GFlowError-style kwargs.
Legacy form: ``FlowApiError(status: int, body: str, *, route: str = "")``
The ``body`` argument MUST be pre-redacted via ``_redact_for_log`` before
construction (mandate per security review). It is truncated to 200
chars and incorporated into ``detail``.
"""
problem_type = "https://gflow-cli.dev/errors/api-error"
charged = "maybe"
next_action = "none"
title = "Flow API error"
_default_remediation = (
"Check request parameters and network connection, then retry the API call."
)
def __init__(self, *args: Any, code: int | None = None, **kwargs: Any) -> None:
self.code = code
# `bool` is a subclass of `int`, so `isinstance(True, int)` is True.
# Exclude bools explicitly so an accidental FlowApiError(True, ...) takes
# the new-style path (and surfaces as a TypeError downstream) instead of
# silently being treated as legacy with status=1.
if args and isinstance(args[0], int) and not isinstance(args[0], bool):
status = args[0]
body = args[1] if len(args) > 1 else ""
route_kw = kwargs.pop("route", "")
super().__init__(
f"HTTP {status}: {body[:200]}",
status=status,
instance=kwargs.pop("instance", None),
route=route_kw,
remediation_hint=kwargs.pop("remediation_hint", None),
# Forwarded like its siblings above. This branch pops named kwargs one
# by one, so an unlisted one is dropped in silence — and since
# `retryable` moved onto the base it now LOOKS accepted here while
# doing nothing (council D1). No caller passes it today; the cost of
# it being wrong later is a doomed retry nobody can explain.
retryable=kwargs.pop("retryable", None),
charged=kwargs.pop("charged", None),
next_action=kwargs.pop("next_action", None),
operation_id=kwargs.pop("operation_id", None),
)
self.body = body
else:
super().__init__(*args, **kwargs)
self.body = ""
class AuthExpiredError(FlowApiError):
problem_type = "https://gflow-cli.dev/errors/auth-expired"
charged = "maybe"
next_action = "reauth"
title = "Authentication expired"
_default_remediation = "Run `gflow auth login --profile <name>` to refresh the session."
class AisandboxAuthError(AuthExpiredError):
"""The aisandbox-pa access token could not be obtained, or was refused.
Distinct from the generic AuthExpiredError so callers (and the scene
feature) can catch the aisandbox-specific auth failure, while still
mapping to exit code 3 via the EXIT_CODE_MAP isinstance walk (no own
entry needed — it inherits AuthExpiredError's code).
#803: this used to be documented and remediated as a SAPISID failure. No
route that raises it reads SAPISID — the credential is a Bearer token
minted by labs' `/fx/api/auth/session`, and SAPISID's only role is getting
that session to answer at all. So a SAPISID remediation names a credential
that is, by the time we are here, demonstrably working. Prefer an explicit
``remediation_hint`` at each raise site; the default below has to stay true
on every route that can reach it.
"""
problem_type = "https://gflow-cli.dev/errors/aisandbox-auth"
charged = "maybe"
next_action = "reauth"
title = "aisandbox-pa authentication failed"
_default_remediation = (
"Flow's session did not yield an API token that aisandbox-pa accepted. "
"If Flow serves this account from flow.google.com, re-authenticating will "
"not help — that host mints no such token. Otherwise re-run `gflow auth "
"login --profile <name>` and retry. See issue #803."
)
CONTENT_SAFETY_REASONS: frozenset[str] = frozenset(
{
"PUBLIC_ERROR_UNSAFE_GENERATION",
"PUBLIC_ERROR_UNSAFE_CONTENT",
"PUBLIC_ERROR_UNSAFE_FACE",
"PUBLIC_ERROR_UNSAFE_IDENTITY",
}
)
"""Flow's content-safety ``details[].reason`` values on an HTTP 400.
Lives here, next to :class:`ContentPolicyError` whose docstring documents the
wire shape, because ``errors`` is a leaf module: ``api.client``,
``api.transports.*`` and ``diagnostics`` can all import it, and none of them can
import each other (``client`` imports ``transports``; ``diagnostics`` must stay
leaf-level because ``FlowApiClient`` owns the ``IncidentRecorder``). Before #528
this set was maintained in three places and the transports had no copy at all.
"""
def classify_content_safety(body: object) -> str | None:
"""Return Flow's content-safety ``reason``, or ``None`` if the body has none.
Accepts either the raw response text (what ``api.client`` holds) or an
already-parsed dict (what the ``ui_automation`` response listener stores),
so both callers share one implementation.
Flow's HTTP 400 error shape::
{"error": {"code": 400, "message": "...", "status": "INVALID_ARGUMENT",
"details": [{"reason": "PUBLIC_ERROR_UNSAFE_GENERATION"}]}}
"""
parsed: object = body
if isinstance(parsed, str):
try:
parsed = json.loads(parsed)
except (json.JSONDecodeError, ValueError):
return None
if not isinstance(parsed, dict):
return None
error_obj = cast("dict[str, Any]", parsed).get("error")
if not isinstance(error_obj, dict):
return None
details = cast("dict[str, Any]", error_obj).get("details")
if not isinstance(details, list):
return None
for item in cast("list[Any]", details):
if isinstance(item, dict):
reason = cast("dict[str, Any]", item).get("reason", "")
if reason in CONTENT_SAFETY_REASONS:
return cast("str", reason)
return None
class RateLimitError(FlowApiError):
problem_type = "https://gflow-cli.dev/errors/rate-limit"
charged = "no"
next_action = "retry_after"
title = "Rate limit or quota hit"
_default_remediation = (
"Daily or per-minute model quota reached; retry with a different model or "
"wait for quota reset"
)
retry_after: float | None = None
def __init__(
self,
detail: str = "",
*,
status: int | None = None,
instance: str | None = None,
route: str = "",
remediation_hint: str | None = None,
retry_after: float | None = None,
charged: Charged | None = None,
) -> None:
super().__init__(
detail,
status=status,
instance=instance,
route=route,
remediation_hint=remediation_hint,
charged=charged,
)
self.retry_after = retry_after
def to_problem_details(self) -> ProblemDetails:
pd = super().to_problem_details()
if self.retry_after is not None and self.resolved_next_action() == "retry_after":
pd["retry_after"] = self.retry_after
return pd
class ContentPolicyError(FlowApiError):
"""Flow rejected the request under its content policy.
Two known raise sites:
1. **HTTP 200 with empty ``media[]``** — the classic content-safety path
(``_common.py``). ``status`` is omitted from ``to_problem_details()``
per RFC 9457 — 200 conflates with success. The literal upstream
status (200) is recorded only via the ``error_raised`` log event as
an ``upstream_status`` extension (see observability.py).
2. **HTTP 400 with a content-safety reason** — ``_raise_for_non_retryable``
in ``client.py``. The body carries ``details[].reason`` =
``PUBLIC_ERROR_UNSAFE_GENERATION`` (or ``_CONTENT``,
``_FACE``, ``_IDENTITY``). ``status=400`` is set on the exception
but stripped from ``to_problem_details()`` per the same RFC 9457
contract.
Enforcement is at the class level (overrides ``to_problem_details``) —
relying on callers to omit ``status=`` would silently break the RFC 9457
contract the first time someone added it for symmetry with other error
classes.
"""
problem_type = "https://gflow-cli.dev/errors/content-policy"
charged = "maybe"
next_action = "fix_input"
title = "Content policy rejection"
_default_remediation = "Reduce prompt text or describe <= 1 person per scene"
def to_problem_details(self) -> ProblemDetails:
pd = super().to_problem_details()
# RFC 9457 contract: an error must not carry a 2xx status.
pd.pop("status", None)
return pd
class NetworkError(FlowApiError):
problem_type = "https://gflow-cli.dev/errors/network"
charged = "maybe"
next_action = "retry"
title = "Network failure persisted across retries"
_default_remediation = "Check connectivity and try again."
class MediaDownloadError(NetworkError):
"""The signed-media GET failed AFTER Flow reported the generation done (#896).
Raised by ``get_signed_media`` and by the clip writer when storing the bytes fails
(#1003), so catching it means the clip exists and was billed — the recorder uses it
to mark the asset generated instead of leaving it ``pending`` forever. Exits 6 like
its parent.
"""
problem_type = "https://gflow-cli.dev/errors/media-download"
charged = "no"
next_action = "retry"
title = "Generated media could not be downloaded"
def __init__(self, *args: Any, media_id: str = "", **kwargs: Any) -> None:
if kwargs.get("retryable") is False:
# #941: every site that turns the retry off is a finished, billed clip, so a
# re-run bills again; the follow-up is the free recovery by media id (#1201).
kwargs.setdefault("charged", "yes")
kwargs.setdefault("next_action", "reconcile")
kwargs.setdefault("operation_id", media_id)
super().__init__(*args, **kwargs)
self.media_id = media_id
class WireFormatError(FlowApiError):
"""Carries discovery fields so ``grep error_class=WireFormatError`` in
structured logs reveals what was unexpected, enabling new error class
proposals. Discovery payload set at raise site via the ``discovery=`` kwarg."""
problem_type = "https://gflow-cli.dev/errors/wire-format"
charged = "maybe"
next_action = "reconcile"
title = "Unexpected response shape from Flow"
_default_remediation = (
"Check request payload parameters or retry with a simpler prompt text. "
"File a bug at https://github.com/ffroliva/gflow-cli/issues with the "
"discovery payload above."
)
def __init__(
self,
detail: str = "",
*,
status: int | None = None,
instance: str | None = None,
route: str = "",
remediation_hint: str | None = None,
discovery: dict[str, Any] | None = None,
charged: Charged | None = None,
) -> None:
super().__init__(
detail,
status=status,
instance=instance,
route=route,
remediation_hint=remediation_hint,
charged=charged,
)
self.discovery = discovery or {}
class RpcResponseUnavailableError(WireFormatError):
"""A write was sent but its outcome was never seen: the reply body was unreadable,
or no reply arrived before the ceiling (#1037).
The write may already have committed; callers must recover by readback,
never infer failure or automatically submit the write again.
"""
problem_type = "https://gflow-cli.dev/errors/rpc-response-unavailable"
charged = "maybe"
next_action = "reconcile"
title = "Flow write outcome unknown"
_default_remediation = (
"The outcome is unknown: Flow may have saved this write. Open the project on "
"flow.google.com and check its title or the uploaded file before re-running. "
"Do not resubmit blindly, or you may get a duplicate project or upload."
)
class SceneConcatError(FlowApiError):
"""Raised when Flow's server-side scene concatenation job FAILS.
Distinct from a poll timeout (which raises ``TransportTimeoutError``, exit 9):
this is a terminal ``MEDIA_GENERATION_STATUS_FAILED`` / unexpected status from
``runVideoFxCheckConcatenationStatus`` (or an undecodable / non-MP4 payload).
The error detail is built from the ``status`` ONLY — never the ~20MB inline
``encodedVideo``.
"""
problem_type = "https://gflow-cli.dev/errors/scene-concat"
charged = "no"
next_action = "fix_input"
title = "Scene concatenation failed"
_default_remediation = "Ensure video clip dimensions and codecs match before concatenation"
class TransportTimeoutError(GFlowError):
"""Raised when a single API call or page wait exceeds its deadline (named in ``detail``)."""
problem_type = "https://gflow-cli.dev/errors/transport-timeout"
charged = "maybe"
next_action = "retry"
title = "Transport strategy timed out"
_default_remediation = (
"A single API call exceeded its deadline (the detail names it). "
"Check connectivity or reduce request complexity."
)
class WafRejectionError(GFlowError):
"""Raised on HTTP 403 from Flow API; likely WAF / browser-fingerprint mismatch."""
problem_type = "https://gflow-cli.dev/errors/waf-rejection"
charged = "maybe"
next_action = "retry"
title = "WAF rejection (HTTP 403)"
_default_remediation = (
"Flow returned 403; the request was blocked by a WAF or fingerprint check. "
"Re-authenticate or rotate the transport profile."
)
class ConfigurationError(GFlowError):
"""Raised when configuration is invalid (e.g. unknown transport name)."""
problem_type = "https://gflow-cli.dev/errors/configuration"
charged = "no"
next_action = "fix_input"
title = "Configuration error"
_default_remediation = (
"Check that the transport name is registered via make_transport(). "
"Run `gflow config list-transports` to see available strategies."
)
class ProfileAccessError(ConfigurationError):
"""Raised when Chrome cannot write its persistent profile directory."""
problem_type = "https://gflow-cli.dev/errors/profile-access"
charged = "no"
next_action = "fix_input"
title = "Profile directory not writable"
_default_remediation = (
"Check filesystem permissions or sandbox policy for the full profile "
"directory. Grant this process write access, or authenticate a profile "
"inside a writable GFLOW_CLI_HOME. Relocating only application-level lock "
"files is not enough; Chrome still writes its ProcessSingleton, cookie, and "
"crash-report files inside the profile."
)
@dataclass(frozen=True, slots=True)
class OwnerEvidence:
"""Private diagnostic evidence about the recorded lease owner (§6.4 of the
incident-diagnostics design). Identities are per-command HMACs — never the
raw profile name or owner token. The kernel lock is authoritative; this
metadata can be stale and never authorizes reclaim, unlink, or PID kill."""
pid: int
process_start_time: float
profile_identity: str
owner_token_identity: str
class ProfileLockedError(ConfigurationError):
"""Raised when the profile directory is held by another process.
Two known causes, each raise site supplying its own remediation: a running
``gflow serve`` daemon (browser_manager), or another Chrome — typically a
stale browser leaked by a crashed prior run — holding the dir at
persistent-context launch (issue #293).
``owner_evidence`` is a PRIVATE typed attribute set by ``ProfileLease``
contention paths for the incident recorder and local human formatter only.
It is deliberately excluded from ``to_problem_details()`` and therefore
from every MCP/HTTP/worker/structured-log surface.
"""
problem_type = "https://gflow-cli.dev/errors/profile-locked"
charged = "no"
next_action = "wait"
title = "Profile locked"
owner_evidence: OwnerEvidence | None = None
_default_remediation = (
"A live process holds this profile: a gflow command, a `gflow serve` "
"daemon, or a Chrome/python process using the profile dir. Close it and "
"retry, or use a different profile name. If nothing is running, the "
"kernel lock is already released — a leftover lock file never blocks "
"acquisition, so just retry."
)
class ProfileEngineDowngradeError(ConfigurationError):
"""Raised when a persisted profile was last written by a newer Chromium
than the engine about to open it (#477).
Chromium's downgrade cleanup on open can leave the newer store — session
cookies included — unreadable, surfacing later as a mystery logout. Like
:class:`ProfileLockedError`, this is a profile-state precondition that
fails closed before any browser starts; it inherits ConfigurationError's
exit code 11 (no own EXIT_CODE_MAP entry). The raise site supplies the
message naming both versions; login is deliberately unguarded — it re-mints
the session and rewrites the profile, so it is the recovery path.
"""
problem_type = "https://gflow-cli.dev/errors/profile-engine-downgrade"
charged = "no"
next_action = "fix_input"
title = "Profile was written by a newer Chromium"
_default_remediation = (
"Upgrade so the bundled Chromium is at least the profile's major version "
"(e.g. `uv tool upgrade gflow-cli`, then `playwright install chromium`). "
"If the profile was captured with `--browser chrome`, reinstall Google "
"Chrome in its default location instead — the chrome channel then opens "
"the profile and this check does not apply. Or re-create the profile "
"with `gflow auth login`."
)
class BrowserEngineUnavailableError(ConfigurationError):
"""Raised when GFLOW_CLI_BROWSER_ENGINE selects an engine that is unavailable.
Two causes: the optional ``patchright`` package is not installed, or its
browser driver is missing. Caught at the engine-resolver seam and re-raised
here (never a raw ``ImportError``, which would be SHA-hashed to a generic
exit 1). Distinct exit code 24 (not ConfigurationError's 11) so scripted
callers can branch on "install the engine" versus a generic config mistake.
The remediation hint differs per cause and is supplied at the raise site.
"""
problem_type = "https://gflow-cli.dev/errors/browser-engine-unavailable"
charged = "no"
next_action = "fix_input"
title = "Selected browser engine is unavailable"
_default_remediation = (
"The selected browser engine is unavailable. Install it with "
"`pip install 'gflow-cli[patchright]'`, or unset GFLOW_CLI_BROWSER_ENGINE to use the "
"default playwright engine."
)
class ModelModeIncompatibilityError(ConfigurationError):
"""Raised when the chosen video model is incompatible with the requested
generation mode (issue #125).
One case remains: ``omni-flash`` for **chains**. Single-clip start-frame
i2v was wire-verified 2026-08-03 and the end frame on 2026-09-02, but N
seeded links back-to-back has not been, so chains stay on the Veo 3.1
family.
History: omni-flash was excluded from i2v entirely after a 2026-05-30
capture showed Flow silently dropping the frame refs at submit and billing
the run as text-to-video. The start-frame path was re-verified on the wire
and re-enabled (#125); the END frame followed once Flow shipped first+last
for Omni 1.1 Flash and two accounts reproduced the
``StartAndEndImage`` route at zero credits (#626). What guards the i2v path
now is a post-submit route check in the transport, not this error — it
validates the route Flow actually used rather than a static capability
table that can go stale in either direction.
Raised pre-submit at the CLI boundary, so it never spends a credit.
Distinct exit code 17 (not Click's exit 2, not generic exit 1) so
scripted callers can branch on "I picked an incompatible
model/mode" without parsing stderr.
"""
problem_type = "https://gflow-cli.dev/errors/model-mode-incompatibility"
charged = "no"
next_action = "fix_input"
title = "Model is incompatible with the requested generation mode"
_default_remediation = (
"The selected video model does not support this generation mode. "
"omni-flash is not accepted for `gflow video chain`: chains stay on a "
"Veo 3.1 model (veo-lite / veo-fast / veo-quality / veo-lite-lp). "
"Single-clip i2v — including --end-frame — is unaffected. "
"See issues #125 and #626."
)
class VideoModelSelectionError(ConfigurationError):
"""Raised when the requested video model could not be selected in Flow's UI
for an i2v generation (issue #125).
The model picker option was not found (e.g. a selector drift / render race).
For i2v this is FATAL rather than a silent fallback: leaving Flow on its
default model (``omni-flash``) would drop the start/end frames and route to
T2V, charging a credit for a text-only video. Raised pre-submit by the
transport, so no credit is spent.
Distinct exit code 18 so scripted callers can branch on "the model UI failed"
(a retryable transport/selector issue) versus exit 17 "I picked an
incompatible model" (a request mistake).
"""
problem_type = "https://gflow-cli.dev/errors/video-model-selection"
charged = "no"
next_action = "fix_input"
title = "Could not select the requested video model"
_default_remediation = (
"gflow could not select the requested model in Flow's editor (the model "
"picker option was not found). This is usually transient — retry the "
"command. If it persists, Flow's model-picker UI may have changed; please "
"report it referencing issue #125."
)
class UpscaleUnavailableError(GFlowError):
"""Raised when an upscale target resolution is unavailable for the account
(issue #171; shared by the image and video upscale paths, #966).
The canonical case: a non-Ultra (e.g. Pro) account requests ``--scale 4k``.
Flow's ``upsampleImage`` endpoint returns HTTP 403 for the tier gate, which is
indistinguishable on the wire from a WAF/fingerprint 403. The transport
disambiguates by context (the request was a 4K upscale, the session is valid,
reCAPTCHA was accepted) and raises THIS error rather than ``WafRejectionError``.
Exit code 22 (not WAF's 10) so scripted callers can branch on "upgrade your
subscription" versus "the request was blocked / rotate profile". 22 is shared with
:class:`ServerCancelUnavailableError` (#1198); branch on the ``type`` URI to tell
them apart.
The caller MUST NOT auto-retry a tier 403 — retrying only inflates per-profile
WAF heat without ever succeeding.
"""
problem_type = "https://gflow-cli.dev/errors/upscale-unavailable"
charged = "no"
next_action = "none"
title = "Upscale unavailable for this account"
_default_remediation = (
"This upscale resolution is not available on your account. 4K upscaling "
"requires a Flow Ultra subscription — use --scale 2k, or upgrade your plan. "
"If you just upgraded, re-run `gflow auth login --profile <name>` to refresh "
"the session."
)
class ExtendUnavailableError(GFlowError):
"""Raised when no Veo *extend* model is orderable for this account/aspect.
Flow's extend family is tier-gated: `veo_3_1_extend_*_ultra` is
``SERVICE_TIER_ADVANCED``-only, the un-suffixed variants serve
INTERMEDIATE/ENTRY, and every entry carries a per-tier ``creditMapping`` whose
cost reads ``"UNAVAILABLE"`` where the account cannot order it. There is also
no SQUARE key in either family. So "which model?" has no static answer — it is
resolved per run from ``flow.projectInitialData``.
This error means that resolution found nothing: an unsupported aspect, a
cohort without the extend capability, or a tier whose every candidate reads
``UNAVAILABLE``. Raising beats falling back to a hardcoded key — a pinned key
that the account cannot order produces a 403 on every attempt, which is the
exact failure mode of the third-party CLI that prompted this feature.
Distinct exit code 35 (not WAF's 10) for the same reason
:class:`UpscaleUnavailableError` has 22: both are tier gates that look like a
WAF 403 on the wire, and a caller told "you were blocked, cool down 30 minutes"
would wait for a condition that never changes. The caller MUST NOT auto-retry.
On flow.google.com it is also raised when Flow shows the clip editor's Extend menu
item disabled (#1334): measured beside a Google AI plan-upgrade link on an account
holding 12 credits. That raise site carries its own remediation, since the page does
not say whether the plan or the balance gates the item.
"""
problem_type = "https://gflow-cli.dev/errors/extend-unavailable"
charged = "no"
next_action = "none"
title = "Video extend unavailable for this account"
_default_remediation = (
"No extend model is available for this account and aspect ratio. Extend "
"supports 16:9 and 9:16 only (there is no square variant). If you are on a "
"lower tier, the faster extend models may be gated — check `gflow models`. "
"If you just upgraded, re-run `gflow auth login --profile <name>` to refresh "
"the session."
)
class UiSelectorDriftError(GFlowError):
"""Raised when a UI-automation selector cascade cannot reach the control it needs.
Two shapes, and the second is easy to forget: the selector **finds nothing**, or it
finds the element and the element **will not take the interaction** — occluded,
disabled, or never holding still (#593's blocked overlay, #776's click that expired
while the control read visible and enabled). Both mean the same thing to a caller —
gflow cannot drive this control — which is why they share an exit code, and why the
``detail`` has to say which one happened.
Indicates that Flow's frontend has changed in a way that invalidates one
of the selector probes (mode-switch trigger, mode tab, sub-mode tab, etc.),
or that something on the page is in the way.
The ``detail`` names the probe label and includes the debug screenshot or
diagnostics JSON path when one was captured.
This is a hard failure — gflow cannot safely proceed without the control —
but it is *diagnosed*, not opaque: the user gets the probe name and the
captured artifact for inspection. Exit code 23 lets scripted callers branch on
"the UI changed and needs a selector update" versus generic error (1).
"""
problem_type = "https://gflow-cli.dev/errors/ui-selector-drift"
charged = "maybe"
next_action = "none"
title = "Flow UI selector drift"
_default_remediation = (
"A Flow editor UI element could not be located — Google may have updated "
"their frontend. Check for a newer gflow-cli release, then file a bug at "
"https://github.com/ffroliva/gflow-cli/issues referencing the probe name "
"and attaching the diagnostics JSON and/or debug screenshot referenced in "
"this message, plus the incident bundle's report.md when one was written "
"(review artifacts before sharing — screenshots may show your account "
"name/avatar; do NOT include tokens or signed URLs)."
)
class CreditCapExceededError(GFlowError):
"""Flow's quoted generation cost is over the caller's per-command cap."""
problem_type = "https://gflow-cli.dev/errors/credit-cap-exceeded"
title = "Credit cap exceeded"
_default_remediation = "Raise --max-credits or choose a cheaper generation setting."
charged: Charged = "no"
next_action: NextAction = "fix_input"
quoted: int | None = None
max_credits: int = 0
def __init__(
self,
detail: str = "",
*,
quoted: int | None = None,
max_credits: int = 0,
route: str = "",
completed_media_ids: list[str] | None = None,
) -> None:
detail = detail or (
f"Flow quoted {quoted} credits, exceeding the maximum of {max_credits}."
if quoted is not None
else f"Flow's credit quote was unavailable; the maximum is {max_credits}."
)
super().__init__(
detail,
status=422,
route=route,
remediation_hint=(
"This surface shows no price before submit; run without a credit cap."
if quoted is None
else None
),
charged="no",
next_action="fix_input",
)
self.quoted = quoted
self.max_credits = max_credits
self.completed_media_ids = completed_media_ids or []
def to_problem_details(self) -> ProblemDetails:
out = super().to_problem_details()
out["quoted"] = self.quoted
out["max_credits"] = self.max_credits
if getattr(self, "completed_media_ids", None):
out["completed_media_ids"] = self.completed_media_ids
return out
class InsufficientCreditsError(GFlowError):
"""Raised when Flow refuses a generation because the account is short of credits.
**Short of, not necessarily out of.** Veo tiers cost different amounts, so the
threshold is per-model: measured 2026-09-07, `ci-probe` held **50** credits and
still rendered the warning. An empty balance is one way to reach this; an
expensive model on a partial balance is another, and the error must not tell a
user with credits that they have none.
Flow does not disable the submit control when the balance falls short — it
**replaces** it. The ``arrow_forward`` anchor disappears and a
``prompt-warning-button`` carrying ``aria-label='Insufficient credits warning'``
takes its place (note Flow's own word: *insufficient*, not *none*). Measured by
A/B on 2026-09-07 on the migrated host: same probe, same code, ~60 s apart, a
short account and a funded one rendering the mirror image of each other.
Finding: ``docs/superpowers/spikes/2026-09-07-credit-shortfall-looks-like-selector-drift.md``.
That is why this class exists rather than reusing
:class:`UiSelectorDriftError`. A missing anchor was being reported as "Google may
have updated their frontend — file a bug", over a credit shortfall: a wrong diagnosis
pointed at a wrong culprit, which also manufactures frontend-drift reports that no
code change can ever fix. Exit code 37 lets a scripted caller branch on "top up the
account" versus "the UI moved" (23), which is the whole point of separating them.
Nothing is submitted when this is raised, so no credit is spent — there were none
to spend.
"""
problem_type = "https://gflow-cli.dev/errors/insufficient-credits"
charged = "no"
next_action = "wait"
title = "Insufficient Flow credits"
_default_remediation = (
"Your Google account does not have enough Flow credits for this model, so Flow "
"replaced the submit control with its 'Insufficient credits' warning. This is a "