forked from Dicklesworthstone/pi_agent_rust
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror.rs
More file actions
2641 lines (2390 loc) · 87.2 KB
/
error.rs
File metadata and controls
2641 lines (2390 loc) · 87.2 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
//! Error types for the Pi application.
use crate::provider_metadata::{canonical_provider_id, provider_auth_env_keys};
use std::sync::OnceLock;
use thiserror::Error;
/// Result type alias using our error type.
pub type Result<T> = std::result::Result<T, Error>;
/// Main error type for the Pi application.
#[derive(Error, Debug)]
pub enum Error {
/// Configuration errors
#[error("Configuration error: {0}")]
Config(String),
/// Session errors
#[error("Session error: {0}")]
Session(String),
/// Session not found
#[error("Session not found: {path}")]
SessionNotFound { path: String },
/// Provider/API errors
#[error("Provider error: {provider}: {message}")]
Provider { provider: String, message: String },
/// Authentication errors
#[error("Authentication error: {0}")]
Auth(String),
/// Tool execution errors
#[error("Tool error: {tool}: {message}")]
Tool { tool: String, message: String },
/// Validation errors
#[error("Validation error: {0}")]
Validation(String),
/// Extension errors
#[error("Extension error: {0}")]
Extension(String),
/// IO errors
#[error("IO error: {0}")]
Io(#[from] Box<std::io::Error>),
/// JSON errors
#[error("JSON error: {0}")]
Json(#[from] Box<serde_json::Error>),
/// SQLite errors
#[error("SQLite error: {0}")]
Sqlite(#[from] Box<sqlmodel_core::Error>),
/// User aborted operation
#[error("Operation aborted")]
Aborted,
/// API errors (generic)
#[error("API error: {0}")]
Api(String),
}
/// Stable machine codes for auth/config diagnostics across provider families.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuthDiagnosticCode {
MissingApiKey,
InvalidApiKey,
QuotaExceeded,
MissingOAuthAuthorizationCode,
OAuthTokenExchangeFailed,
OAuthTokenRefreshFailed,
MissingAzureDeployment,
MissingRegion,
MissingProject,
MissingProfile,
MissingEndpoint,
MissingCredentialChain,
UnknownAuthFailure,
}
impl AuthDiagnosticCode {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::MissingApiKey => "auth.missing_api_key",
Self::InvalidApiKey => "auth.invalid_api_key",
Self::QuotaExceeded => "auth.quota_exceeded",
Self::MissingOAuthAuthorizationCode => "auth.oauth.missing_authorization_code",
Self::OAuthTokenExchangeFailed => "auth.oauth.token_exchange_failed",
Self::OAuthTokenRefreshFailed => "auth.oauth.token_refresh_failed",
Self::MissingAzureDeployment => "config.azure.missing_deployment",
Self::MissingRegion => "config.auth.missing_region",
Self::MissingProject => "config.auth.missing_project",
Self::MissingProfile => "config.auth.missing_profile",
Self::MissingEndpoint => "config.auth.missing_endpoint",
Self::MissingCredentialChain => "auth.credential_chain.missing",
Self::UnknownAuthFailure => "auth.unknown_failure",
}
}
#[must_use]
pub const fn remediation(self) -> &'static str {
match self {
Self::MissingApiKey => "Set the provider API key env var or run `/login <provider>`.",
Self::InvalidApiKey => "Rotate or replace the API key and verify provider permissions.",
Self::QuotaExceeded => {
"Verify billing/quota limits for this API key or organization, then retry."
}
Self::MissingOAuthAuthorizationCode => {
"Re-run `/login` and paste a full callback URL or authorization code."
}
Self::OAuthTokenExchangeFailed => {
"Retry login flow and verify token endpoint/client configuration."
}
Self::OAuthTokenRefreshFailed => {
"Re-authenticate with `/login` and confirm refresh-token validity."
}
Self::MissingAzureDeployment => {
"Configure Azure resource+deployment in models.json before dispatch."
}
Self::MissingRegion => "Set provider region/cluster configuration before retrying.",
Self::MissingProject => "Set provider project/workspace identifier before retrying.",
Self::MissingProfile => "Set credential profile/source configuration before retrying.",
Self::MissingEndpoint => "Configure provider base URL/endpoint in models.json.",
Self::MissingCredentialChain => {
"Configure credential-chain sources (env/profile/role) before retrying."
}
Self::UnknownAuthFailure => {
"Inspect auth diagnostics and retry with explicit credentials."
}
}
}
#[must_use]
pub const fn redaction_policy(self) -> &'static str {
match self {
Self::MissingApiKey
| Self::InvalidApiKey
| Self::QuotaExceeded
| Self::MissingOAuthAuthorizationCode
| Self::OAuthTokenExchangeFailed
| Self::OAuthTokenRefreshFailed
| Self::MissingAzureDeployment
| Self::MissingRegion
| Self::MissingProject
| Self::MissingProfile
| Self::MissingEndpoint
| Self::MissingCredentialChain
| Self::UnknownAuthFailure => "redact-secrets",
}
}
}
/// Structured auth/config diagnostic metadata for downstream tooling.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AuthDiagnostic {
pub code: AuthDiagnosticCode,
pub remediation: &'static str,
pub redaction_policy: &'static str,
}
impl Error {
/// Create a configuration error.
pub fn config(message: impl Into<String>) -> Self {
Self::Config(message.into())
}
/// Create a session error.
pub fn session(message: impl Into<String>) -> Self {
Self::Session(message.into())
}
/// Create a provider error.
pub fn provider(provider: impl Into<String>, message: impl Into<String>) -> Self {
Self::Provider {
provider: provider.into(),
message: message.into(),
}
}
/// Create an authentication error.
pub fn auth(message: impl Into<String>) -> Self {
Self::Auth(message.into())
}
/// Create a tool error.
pub fn tool(tool: impl Into<String>, message: impl Into<String>) -> Self {
Self::Tool {
tool: tool.into(),
message: message.into(),
}
}
/// Create a validation error.
pub fn validation(message: impl Into<String>) -> Self {
Self::Validation(message.into())
}
/// Create an extension error.
pub fn extension(message: impl Into<String>) -> Self {
Self::Extension(message.into())
}
/// Create an API error.
pub fn api(message: impl Into<String>) -> Self {
Self::Api(message.into())
}
/// Map this error to a hostcall taxonomy code.
///
/// The hostcall ABI requires every error to be one of:
/// `timeout`, `denied`, `io`, `invalid_request`, or `internal`.
pub const fn hostcall_error_code(&self) -> &'static str {
match self {
Self::Validation(_) => "invalid_request",
Self::Io(_) | Self::Session(_) | Self::SessionNotFound { .. } | Self::Sqlite(_) => "io",
Self::Auth(_) => "denied",
Self::Aborted => "timeout",
Self::Json(_)
| Self::Extension(_)
| Self::Config(_)
| Self::Provider { .. }
| Self::Tool { .. }
| Self::Api(_) => "internal",
}
}
/// Stable machine-readable error category for automation and diagnostics.
#[must_use]
pub const fn category_code(&self) -> &'static str {
match self {
Self::Config(_) => "config",
Self::Session(_) | Self::SessionNotFound { .. } => "session",
Self::Provider { .. } => "provider",
Self::Auth(_) => "auth",
Self::Tool { .. } => "tool",
Self::Validation(_) => "validation",
Self::Extension(_) => "extension",
Self::Io(_) => "io",
Self::Json(_) => "json",
Self::Sqlite(_) => "sqlite",
Self::Aborted => "runtime",
Self::Api(_) => "api",
}
}
/// Classify auth/config errors into stable machine-readable diagnostics.
#[must_use]
pub fn auth_diagnostic(&self) -> Option<AuthDiagnostic> {
match self {
Self::Auth(message) => classify_auth_diagnostic(None, message),
Self::Provider { provider, message } => {
classify_auth_diagnostic(Some(provider.as_str()), message)
}
_ => None,
}
}
/// Map internal errors to a stable, user-facing hint taxonomy.
#[must_use]
pub fn hints(&self) -> ErrorHints {
let mut hints = match self {
Self::Config(message) => config_hints(message),
Self::Session(message) => session_hints(message),
Self::SessionNotFound { path } => build_hints(
"Session file not found.",
vec![
"Use `pi --continue` to open the most recent session.".to_string(),
"Verify the path or move the session back into the sessions directory."
.to_string(),
],
vec![("path", path.clone())],
),
Self::Provider { provider, message } => provider_hints(provider, message),
Self::Auth(message) => auth_hints(message),
Self::Tool { tool, message } => tool_hints(tool, message),
Self::Validation(message) => build_hints(
"Validation failed for input or config.",
vec![
"Check the specific fields mentioned in the error.".to_string(),
"Review CLI flags or settings for typos.".to_string(),
],
vec![("details", message.clone())],
),
Self::Extension(message) => build_hints(
"Extension failed to load or run.",
vec![
"Try `--no-extensions` to isolate the issue.".to_string(),
"Check the extension manifest and dependencies.".to_string(),
],
vec![("details", message.clone())],
),
Self::Io(err) => io_hints(err),
Self::Json(err) => build_hints(
"JSON parsing failed.",
vec![
"Validate the JSON syntax (no trailing commas).".to_string(),
"Check that the file is UTF-8 and not truncated.".to_string(),
],
vec![("details", err.to_string())],
),
Self::Sqlite(err) => sqlite_hints(err),
Self::Aborted => build_hints(
"Operation aborted.",
Vec::new(),
vec![(
"details",
"Operation cancelled by user or runtime.".to_string(),
)],
),
Self::Api(message) => build_hints(
"API request failed.",
vec![
"Check your network connection and retry.".to_string(),
"Verify your API key and provider selection.".to_string(),
],
vec![("details", message.clone())],
),
};
hints.context.push((
"error_category".to_string(),
self.category_code().to_string(),
));
if let Some(diagnostic) = self.auth_diagnostic() {
hints.context.push((
"diagnostic_code".to_string(),
diagnostic.code.as_str().to_string(),
));
hints.context.push((
"diagnostic_remediation".to_string(),
diagnostic.remediation.to_string(),
));
hints.context.push((
"redaction_policy".to_string(),
diagnostic.redaction_policy.to_string(),
));
}
hints
}
}
/// Structured hints for error remediation.
#[derive(Debug, Clone)]
pub struct ErrorHints {
/// Brief summary of the error category.
pub summary: String,
/// Actionable hints for the user.
pub hints: Vec<String>,
/// Key-value context pairs for display.
pub context: Vec<(String, String)>,
}
fn build_hints(summary: &str, hints: Vec<String>, context: Vec<(&str, String)>) -> ErrorHints {
ErrorHints {
summary: summary.to_string(),
hints,
context: context
.into_iter()
.map(|(label, value)| (label.to_string(), value))
.collect(),
}
}
fn contains_any(haystack: &str, needles: &[&str]) -> bool {
needles.iter().any(|needle| haystack.contains(needle))
}
const fn build_auth_diagnostic(code: AuthDiagnosticCode) -> AuthDiagnostic {
AuthDiagnostic {
code,
remediation: code.remediation(),
redaction_policy: code.redaction_policy(),
}
}
#[allow(clippy::too_many_lines)]
fn classify_auth_diagnostic(provider: Option<&str>, message: &str) -> Option<AuthDiagnostic> {
let lower = message.to_lowercase();
let provider_lower = provider.map(str::to_lowercase);
if contains_any(
&lower,
&[
"missing authorization code",
"authorization code is missing",
],
) {
return Some(build_auth_diagnostic(
AuthDiagnosticCode::MissingOAuthAuthorizationCode,
));
}
if contains_any(&lower, &["token exchange failed", "invalid token response"]) {
return Some(build_auth_diagnostic(
AuthDiagnosticCode::OAuthTokenExchangeFailed,
));
}
if contains_any(
&lower,
&[
"token refresh failed",
"oauth token refresh failed",
"refresh token",
],
) {
return Some(build_auth_diagnostic(
AuthDiagnosticCode::OAuthTokenRefreshFailed,
));
}
if contains_any(
&lower,
&[
"missing api key",
"api key not configured",
"api key is required",
"you didn't provide an api key",
"no api key provided",
"missing bearer",
"authorization header missing",
],
) {
return Some(build_auth_diagnostic(AuthDiagnosticCode::MissingApiKey));
}
if contains_any(
&lower,
&[
"insufficient_quota",
"quota exceeded",
"quota has been exceeded",
"billing hard limit",
"billing_not_active",
"not enough credits",
"credit balance is too low",
],
) {
return Some(build_auth_diagnostic(AuthDiagnosticCode::QuotaExceeded));
}
if contains_any(
&lower,
&[
"401",
"unauthorized",
"403",
"forbidden",
"invalid api key",
"incorrect api key",
"malformed api key",
"api key is malformed",
"revoked",
"deactivated",
"disabled api key",
"expired api key",
],
) {
return Some(build_auth_diagnostic(AuthDiagnosticCode::InvalidApiKey));
}
if contains_any(&lower, &["resource+deployment", "missing deployment"]) {
return Some(build_auth_diagnostic(
AuthDiagnosticCode::MissingAzureDeployment,
));
}
if contains_any(&lower, &["missing region", "region is required"]) {
return Some(build_auth_diagnostic(AuthDiagnosticCode::MissingRegion));
}
if contains_any(&lower, &["missing project", "project is required"]) {
return Some(build_auth_diagnostic(AuthDiagnosticCode::MissingProject));
}
if contains_any(&lower, &["missing profile", "profile is required"]) {
return Some(build_auth_diagnostic(AuthDiagnosticCode::MissingProfile));
}
if contains_any(
&lower,
&[
"missing endpoint",
"missing base url",
"base url is required",
],
) {
return Some(build_auth_diagnostic(AuthDiagnosticCode::MissingEndpoint));
}
if contains_any(
&lower,
&[
"credential chain",
"aws_access_key_id",
"credential source",
"missing credentials",
],
) || provider_lower
.as_deref()
.is_some_and(|provider_id| provider_id.contains("bedrock") && lower.contains("credential"))
{
return Some(build_auth_diagnostic(
AuthDiagnosticCode::MissingCredentialChain,
));
}
if lower.contains("oauth")
|| lower.contains("authentication")
|| lower.contains("credential")
|| lower.contains("api key")
{
return Some(build_auth_diagnostic(
AuthDiagnosticCode::UnknownAuthFailure,
));
}
None
}
fn config_hints(message: &str) -> ErrorHints {
let lower = message.to_lowercase();
if contains_any(&lower, &["json", "parse", "serde"]) {
return build_hints(
"Configuration file is not valid JSON.",
vec![
"Fix JSON formatting in the active settings file.".to_string(),
"Run `pi config` to see which settings file is in use.".to_string(),
],
vec![("details", message.to_string())],
);
}
if contains_any(&lower, &["missing", "not found", "no such file"]) {
return build_hints(
"Configuration file is missing.",
vec![
"Create `~/.pi/agent/settings.json` or set `PI_CONFIG_PATH`.".to_string(),
"Run `pi config` to confirm the resolved path.".to_string(),
],
vec![("details", message.to_string())],
);
}
build_hints(
"Configuration error.",
vec![
"Review your settings file for incorrect values.".to_string(),
"Run `pi config` to verify settings precedence.".to_string(),
],
vec![("details", message.to_string())],
)
}
fn session_hints(message: &str) -> ErrorHints {
let lower = message.to_lowercase();
if contains_any(&lower, &["empty session file", "empty session"]) {
return build_hints(
"Session file is empty or corrupted.",
vec![
"Start a new session with `pi --no-session`.".to_string(),
"Inspect the session file for truncation.".to_string(),
],
vec![("details", message.to_string())],
);
}
if contains_any(&lower, &["failed to read", "read dir", "read session"]) {
return build_hints(
"Failed to read session data.",
vec![
"Check file permissions for the sessions directory.".to_string(),
"Verify `PI_SESSIONS_DIR` if you set it.".to_string(),
],
vec![("details", message.to_string())],
);
}
build_hints(
"Session error.",
vec![
"Try `pi --continue` or specify `--session <path>`.".to_string(),
"Check session file integrity in the sessions directory.".to_string(),
],
vec![("details", message.to_string())],
)
}
#[allow(clippy::too_many_lines)]
fn provider_hints(provider: &str, message: &str) -> ErrorHints {
let lower = message.to_lowercase();
let key_hint = provider_key_hint(provider);
let context = vec![
("provider", provider.to_string()),
("details", message.to_string()),
];
if contains_any(
&lower,
&[
"missing api key",
"you didn't provide an api key",
"no api key provided",
"authorization header missing",
],
) {
return build_hints(
"Provider API key is missing.",
vec![
key_hint,
"Set the API key and retry the request.".to_string(),
],
context,
);
}
if contains_any(
&lower,
&["401", "unauthorized", "invalid api key", "api key"],
) {
return build_hints(
"Provider authentication failed.",
vec![key_hint, "If using OAuth, run `/login` again.".to_string()],
context,
);
}
if contains_any(&lower, &["403", "forbidden"]) {
return build_hints(
"Provider access forbidden.",
vec![
"Verify the account has access to the requested model.".to_string(),
"Check organization/project permissions for the API key.".to_string(),
],
context,
);
}
if contains_any(
&lower,
&[
"insufficient_quota",
"quota exceeded",
"quota has been exceeded",
"billing hard limit",
"billing_not_active",
"not enough credits",
"credit balance is too low",
],
) {
return build_hints(
"Provider quota or billing limit reached.",
vec![
"Verify billing/credits and organization quota for this API key.".to_string(),
key_hint,
],
context,
);
}
if contains_any(&lower, &["429", "rate limit", "too many requests"]) {
return build_hints(
"Provider rate limited the request.",
vec![
"Wait and retry, or reduce request rate.".to_string(),
"Consider smaller max_tokens to lower load.".to_string(),
],
context,
);
}
if contains_any(&lower, &["529", "overloaded"]) {
return build_hints(
"Provider is overloaded.",
vec![
"Retry after a short delay.".to_string(),
"Switch to a different model if available.".to_string(),
],
context,
);
}
if contains_any(&lower, &["timeout", "timed out"]) {
return build_hints(
"Provider request timed out.",
vec![
"Check network stability and retry.".to_string(),
"Lower max_tokens to shorten responses.".to_string(),
],
context,
);
}
if contains_any(&lower, &["400", "bad request", "invalid request"]) {
return build_hints(
"Provider rejected the request.",
vec![
"Check model name, tools schema, and request size.".to_string(),
"Reduce message size or tool payloads.".to_string(),
],
context,
);
}
if contains_any(&lower, &["500", "internal server error", "server error"]) {
return build_hints(
"Provider encountered a server error.",
vec![
"Retry after a short delay.".to_string(),
"If persistent, try a different model/provider.".to_string(),
],
context,
);
}
build_hints(
"Provider request failed.",
vec![
key_hint,
"Check network connectivity and provider status.".to_string(),
],
context,
)
}
fn provider_key_hint(provider: &str) -> String {
let canonical = canonical_provider_id(provider).unwrap_or(provider);
let env_keys = provider_auth_env_keys(provider);
if !env_keys.is_empty() {
let key_list = env_keys
.iter()
.map(|key| format!("`{key}`"))
.collect::<Vec<_>>()
.join(" or ");
if canonical == "anthropic" {
return format!("Set {key_list} (or use `/login anthropic`).");
}
if canonical == "github-copilot" {
return format!("Set {key_list} (or use `/login github-copilot`).");
}
return format!("Set {key_list} for provider `{canonical}`.");
}
format!("Check API key configuration for provider `{provider}`.")
}
fn auth_hints(message: &str) -> ErrorHints {
let lower = message.to_lowercase();
if contains_any(
&lower,
&["missing authorization code", "authorization code"],
) {
return build_hints(
"OAuth login did not complete.",
vec![
"Run `/login` again to restart the flow.".to_string(),
"Ensure the browser redirect URL was opened.".to_string(),
],
vec![("details", message.to_string())],
);
}
if contains_any(&lower, &["token exchange failed", "invalid token response"]) {
return build_hints(
"OAuth token exchange failed.",
vec![
"Retry `/login` to refresh credentials.".to_string(),
"Check network connectivity during the login flow.".to_string(),
],
vec![("details", message.to_string())],
);
}
build_hints(
"Authentication error.",
vec![
"Verify API keys or run `/login`.".to_string(),
"Check auth.json permissions in the Pi config directory.".to_string(),
],
vec![("details", message.to_string())],
)
}
fn tool_hints(tool: &str, message: &str) -> ErrorHints {
let lower = message.to_lowercase();
if contains_any(&lower, &["not found", "no such file", "command not found"]) {
return build_hints(
"Tool executable or target not found.",
vec![
"Check PATH and tool installation.".to_string(),
"Verify the tool input path exists.".to_string(),
],
vec![("tool", tool.to_string()), ("details", message.to_string())],
);
}
build_hints(
"Tool execution failed.",
vec![
"Check the tool output for details.".to_string(),
"Re-run with simpler inputs to isolate the failure.".to_string(),
],
vec![("tool", tool.to_string()), ("details", message.to_string())],
)
}
fn io_hints(err: &std::io::Error) -> ErrorHints {
let details = err.to_string();
match err.kind() {
std::io::ErrorKind::NotFound => build_hints(
"Required file or directory not found.",
vec![
"Verify the path exists and is spelled correctly.".to_string(),
"Check `PI_CONFIG_PATH` or `PI_SESSIONS_DIR` overrides.".to_string(),
],
vec![
("error_kind", format!("{:?}", err.kind())),
("details", details),
],
),
std::io::ErrorKind::PermissionDenied => build_hints(
"Permission denied while accessing a file.",
vec![
"Check file permissions or ownership.".to_string(),
"Try a different location with write access.".to_string(),
],
vec![
("error_kind", format!("{:?}", err.kind())),
("details", details),
],
),
std::io::ErrorKind::TimedOut => build_hints(
"I/O operation timed out.",
vec![
"Check network or filesystem latency.".to_string(),
"Retry after confirming connectivity.".to_string(),
],
vec![
("error_kind", format!("{:?}", err.kind())),
("details", details),
],
),
std::io::ErrorKind::ConnectionRefused => build_hints(
"Connection refused.",
vec![
"Check network connectivity or proxy settings.".to_string(),
"Verify the target service is reachable.".to_string(),
],
vec![
("error_kind", format!("{:?}", err.kind())),
("details", details),
],
),
_ => build_hints(
"I/O error occurred.",
vec![
"Check file paths and permissions.".to_string(),
"Retry after resolving any transient issues.".to_string(),
],
vec![
("error_kind", format!("{:?}", err.kind())),
("details", details),
],
),
}
}
fn sqlite_hints(err: &sqlmodel_core::Error) -> ErrorHints {
let details = err.to_string();
let lower = details.to_lowercase();
if contains_any(&lower, &["database is locked", "busy"]) {
return build_hints(
"SQLite database is locked.",
vec![
"Close other Pi instances using the same database.".to_string(),
"Retry once the lock clears.".to_string(),
],
vec![("details", details)],
);
}
build_hints(
"SQLite error.",
vec![
"Ensure the database path is writable.".to_string(),
"Check for schema or migration issues.".to_string(),
],
vec![("details", details)],
)
}
impl From<std::io::Error> for Error {
fn from(value: std::io::Error) -> Self {
Self::Io(Box::new(value))
}
}
impl From<asupersync::sync::LockError> for Error {
fn from(value: asupersync::sync::LockError) -> Self {
match value {
asupersync::sync::LockError::Cancelled => Self::Aborted,
asupersync::sync::LockError::Poisoned
| asupersync::sync::LockError::PolledAfterCompletion => {
Self::session(value.to_string())
}
}
}
}
impl From<serde_json::Error> for Error {
fn from(value: serde_json::Error) -> Self {
Self::Json(Box::new(value))
}
}
impl From<sqlmodel_core::Error> for Error {
fn from(value: sqlmodel_core::Error) -> Self {
Self::Sqlite(Box::new(value))
}
}
// ─── Context overflow detection ─────────────────────────────────────────
/// All 15 pi-mono overflow substring patterns (case-insensitive).
const OVERFLOW_PATTERNS: &[&str] = &[
"prompt is too long",
"input is too long for requested model",
"exceeds the context window",
// "input token count.*exceeds the maximum" handled by regex below
// "maximum prompt length is \\d+" handled by regex below
"reduce the length of the messages",
// "maximum context length is \\d+ tokens" handled by regex below
// "exceeds the limit of \\d+" handled by regex below
"exceeds the available context size",
"greater than the context length",
"context window exceeds limit",
"exceeded model token limit",
// "context[_ ]length[_ ]exceeded" handled by regex below
"too many tokens",
"token limit exceeded",
];
static OVERFLOW_RE: OnceLock<regex::RegexSet> = OnceLock::new();
static RETRYABLE_RE: OnceLock<regex::Regex> = OnceLock::new();
/// Check whether an error message indicates the prompt exceeded the context
/// window. Matches the 15 pi-mono overflow patterns plus Cerebras/Mistral
/// status code pattern.
///
/// Also detects "silent" overflow when `usage_input_tokens` exceeds
/// `context_window`.
pub fn is_context_overflow(
error_message: &str,
usage_input_tokens: Option<u64>,
context_window: Option<u32>,
) -> bool {
// Silent overflow: usage exceeds context window.
if let (Some(input_tokens), Some(window)) = (usage_input_tokens, context_window) {
if input_tokens > u64::from(window) {
return true;
}
}
let lower = error_message.to_lowercase();
// Simple substring checks.
if OVERFLOW_PATTERNS
.iter()
.any(|pattern| lower.contains(pattern))
{
return true;
}
// Regex patterns for the remaining pi-mono checks.
let re = OVERFLOW_RE.get_or_init(|| {
regex::RegexSet::new([
r"input token count.*exceeds the maximum",
r"maximum prompt length is \d+",
r"maximum context length is \d+ tokens",
r"exceeds the limit of \d+",
r"context[_ ]length[_ ]exceeded",
// Cerebras/Mistral: "4XX (no body)" pattern.
r"^4(00|13)\s*(status code)?\s*\(no body\)",
])
.expect("overflow regex set")
});
re.is_match(&lower)
}
// ─── Retryable error classification ─────────────────────────────────────
/// Check whether an error is retryable (transient). Matches pi-mono's
/// `_isRetryableError()` logic:
///
/// 1. Error message must be non-empty.
/// 2. Must NOT be context overflow (those need compaction, not retry).
/// 3. Must match a retryable pattern (rate limit, server error, etc.).
pub fn is_retryable_error(
error_message: &str,
usage_input_tokens: Option<u64>,
context_window: Option<u32>,
) -> bool {
if error_message.is_empty() {
return false;
}
// Context overflow is NOT retryable.
if is_context_overflow(error_message, usage_input_tokens, context_window) {
return false;
}
let lower = error_message.to_lowercase();
let re = RETRYABLE_RE.get_or_init(|| {
regex::Regex::new(
r"overloaded|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server error|internal error|connection.?error|connection.?refused|other side closed|fetch failed|upstream.?connect|reset before headers|terminated|retry delay",
)
.expect("retryable regex")
});
re.is_match(&lower)
}