-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodels.dart
More file actions
1483 lines (1287 loc) · 48.2 KB
/
Copy pathmodels.dart
File metadata and controls
1483 lines (1287 loc) · 48.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
/// Domain model used by the UI. Decoupled from wire types so we can evolve
/// either side independently.
library;
// Re-export the chat item tree + event folding so existing importers of
// `models.dart` keep resolving them after the SPEC-19 split.
export 'chat_items.dart';
/// An agent the host can spawn, surfaced by `agents.list` for the picker.
class AgentDescriptor {
const AgentDescriptor({
required this.id,
required this.label,
required this.transport,
required this.available,
this.fingerprint = '',
this.configOptions = const [],
});
final String id;
final String label;
/// `native` | `acp`.
final String transport;
final bool available;
/// Hash of the harness's resolved binary + catalog-affecting config inputs
/// (SPEC-27). Empty when the server didn't advertise one. Used to detect a
/// stale cached capability catalog.
final String fingerprint;
/// The harness's cached capability catalog — the `configOptions` snapshot
/// from the server's throwaway probe (SPEC-27), rendered pre-session by the
/// SPEC-26 generic renderer. Empty when the harness advertises no options
/// (default-only) or the field is absent.
final List<SessionConfigOption> configOptions;
static AgentDescriptor? fromJson(Map<String, dynamic> j) {
final id = j['id'] as String?;
if (id == null) return null;
return AgentDescriptor(
id: id,
label: (j['label'] as String?) ?? id,
transport: (j['transport'] as String?) ?? 'native',
available: (j['available'] as bool?) ?? true,
fingerprint: (j['fingerprint'] is String)
? j['fingerprint'] as String
: '',
configOptions:
((j['configOptions'] is List)
? j['configOptions'] as List<dynamic>
: const <dynamic>[])
.whereType<Map<dynamic, dynamic>>()
.map(
(m) =>
SessionConfigOption.fromJson(Map<String, dynamic>.from(m)),
)
.whereType<SessionConfigOption>()
.toList(),
);
}
}
/// A single pre-spawn config pick carried on `session.spawn` (SPEC-27): the
/// [id] of a harness [SessionConfigOption] and the chosen [value] (a [String]
/// for a select option, a [bool] for a boolean). The server maps [id] to the
/// transport-specific apply-at-launch param (ACP `session/set_config_option`
/// `configId`, or codex thread/turn params).
class ConfigOptionPick {
const ConfigOptionPick({required this.id, required this.value});
final String id;
/// A [String] for a select option, a [bool] for a boolean.
final Object value;
Map<String, dynamic> toJson() => {'id': id, 'value': value};
}
/// One command exposed by the agent — extension, prompt template, or skill.
class SlashCmd {
const SlashCmd({
required this.name,
required this.description,
required this.source,
this.location,
});
/// Without the leading `/`. e.g. `skill:foo`, `fix-tests`, `session-name`.
final String name;
final String description;
/// `extension` | `prompt` | `skill`
final String source;
/// `user` | `project` | `path` — optional.
final String? location;
String get invocation => '/$name';
static SlashCmd? fromJson(Map<String, dynamic> j) {
final name = j['name'] as String?;
if (name == null) return null;
return SlashCmd(
name: name,
description: (j['description'] as String?) ?? '',
source: (j['source'] as String?) ?? 'extension',
location: j['location'] as String?,
);
}
}
/// A model the agent can run, as pushed via `session.meta`. Also used for the
/// currently-active model.
class ModelInfo {
const ModelInfo({
required this.provider,
required this.id,
required this.name,
});
final String provider;
final String id;
final String name;
static ModelInfo? fromJson(Map<String, dynamic> j) {
final provider = j['provider'] as String?;
final id = j['id'] as String?;
if (provider == null || id == null) return null;
return ModelInfo(
provider: provider,
id: id,
name: (j['name'] as String?) ?? id,
);
}
}
/// Error reported by the pi extension when a built-in control action fails
/// (e.g. `/compact` before the session is ready, `/model` switch rejected).
/// Pushed via `session.action_error`; surfaces as a transient snackbar.
class ActionError {
const ActionError({
required this.seq,
required this.action,
required this.reason,
});
final int seq;
final String action;
final String reason;
}
/// Per-session model + thinking-level snapshot. Drives the subtle header
/// indicator and the `/model` picker. Pushed via the `session.meta` event.
class SessionMeta {
const SessionMeta({
this.model,
required this.thinking,
required this.models,
this.modes,
this.configOptions = const [],
});
final ModelInfo? model;
final String thinking;
final List<ModelInfo> models;
/// ACP session modes (e.g. ask/code/architect), when the agent is an ACP
/// agent that advertises them. Native pi has no modes (null); ACP has no
/// model/thinking. Drives the composer's mode selector.
final SessionModes? modes;
/// Generic, category-tagged config selectors (ACP `configOptions`), ordered
/// by agent priority. Empty when the agent emits only the legacy
/// `model`/`thinking`/`modes` fields (back-compat). See SPEC-26.
final List<SessionConfigOption> configOptions;
static SessionMeta fromJson(Map<String, dynamic> j) {
final rawModel = j['model'];
final rawModes = j['modes'];
return SessionMeta(
model: rawModel is Map
? ModelInfo.fromJson(Map<String, dynamic>.from(rawModel))
: null,
thinking: (j['thinking'] as String?) ?? '',
models: ((j['models'] as List?) ?? const [])
.whereType<Map<dynamic, dynamic>>()
.map((m) => ModelInfo.fromJson(Map<String, dynamic>.from(m)))
.whereType<ModelInfo>()
.toList(),
modes: rawModes is Map
? SessionModes.fromJson(Map<String, dynamic>.from(rawModes))
: null,
configOptions:
((j['configOptions'] is List)
? j['configOptions'] as List
: const <dynamic>[])
.whereType<Map<dynamic, dynamic>>()
.map(
(m) =>
SessionConfigOption.fromJson(Map<String, dynamic>.from(m)),
)
.whereType<SessionConfigOption>()
.toList(),
);
}
}
/// Whether a [SessionConfigOption] is a value picker or an on/off toggle.
/// ACP defaults an option to `select` when `type` is absent.
enum ConfigOptionType { select, boolean }
/// One choice within a select [SessionConfigOption] — either directly under
/// `options` (flat) or inside a [ConfigOptionGroup].
class ConfigOptionValue {
const ConfigOptionValue({
required this.value,
required this.name,
this.description,
});
final String value;
final String name;
final String? description;
static ConfigOptionValue? fromJson(Map<String, dynamic> j) {
final value = j['value'] as String?;
if (value == null) return null;
return ConfigOptionValue(
value: value,
name: (j['name'] as String?) ?? value,
description: j['description'] as String?,
);
}
}
/// A named group of [ConfigOptionValue]s for a grouped select option. The
/// composer renders these as labeled sections.
class ConfigOptionGroup {
const ConfigOptionGroup({required this.name, required this.options});
final String name;
final List<ConfigOptionValue> options;
static ConfigOptionGroup? fromJson(Map<String, dynamic> j) {
final name = j['name'] as String?;
if (name == null) return null;
return ConfigOptionGroup(
name: name,
options: _parseOptionValues(j['options']),
);
}
}
List<ConfigOptionValue> _parseOptionValues(Object? raw) =>
((raw as List?) ?? const [])
.whereType<Map<dynamic, dynamic>>()
.map((m) => ConfigOptionValue.fromJson(Map<String, dynamic>.from(m)))
.whereType<ConfigOptionValue>()
.toList();
/// A generic, category-tagged session config selector advertised by the agent
/// (ACP `configOptions`). Supersedes the legacy `model`/`thinking`/`modes`
/// fields on [SessionMeta]. Ordered by agent priority; the composer renders
/// each option by [category]. See SPEC-26.
class SessionConfigOption {
const SessionConfigOption({
required this.id,
required this.name,
this.description,
this.category,
required this.type,
required this.currentValue,
this.options = const [],
this.groups = const [],
});
final String id;
final String name;
final String? description;
/// Semantic, UX-only hint: known values are `mode`, `model`, `model_config`,
/// `thought_level`. Open string — unknown/`_`-prefixed values are preserved
/// and rendered with the generic select.
final String? category;
final ConfigOptionType type;
/// The active value: a [String] for `select`, a [bool] for `boolean`.
final Object currentValue;
/// Flat choices for a select option; empty when grouped or boolean.
final List<ConfigOptionValue> options;
/// Named groups for a grouped select option; empty when flat or boolean.
final List<ConfigOptionGroup> groups;
static SessionConfigOption? fromJson(Map<String, dynamic> j) {
final id = j['id'] as String?;
final name = j['name'] as String?;
if (id == null || name == null) return null;
final type = j['type'] == 'boolean'
? ConfigOptionType.boolean
: ConfigOptionType.select;
final rawValue = j['currentValue'];
final currentValue = rawValue is bool || rawValue is String
? rawValue as Object
: (type == ConfigOptionType.boolean ? false : '');
return SessionConfigOption(
id: id,
name: name,
description: j['description'] as String?,
category: j['category'] as String?,
type: type,
currentValue: currentValue,
options: _parseOptionValues(j['options']),
groups: ((j['groups'] as List?) ?? const [])
.whereType<Map<dynamic, dynamic>>()
.map((m) => ConfigOptionGroup.fromJson(Map<String, dynamic>.from(m)))
.whereType<ConfigOptionGroup>()
.toList(),
);
}
}
/// One selectable agent mode (ACP session mode).
class SessionMode {
const SessionMode({required this.id, required this.name});
final String id;
final String name;
static SessionMode? fromJson(Map<String, dynamic> j) {
final id = j['id'] as String?;
if (id == null) return null;
return SessionMode(id: id, name: (j['name'] as String?) ?? id);
}
}
/// The set of agent modes and the one currently active (ACP `SessionModeState`).
class SessionModes {
const SessionModes({required this.current, required this.available});
final String current;
final List<SessionMode> available;
static SessionModes fromJson(Map<String, dynamic> j) => SessionModes(
current: (j['current'] as String?) ?? '',
available: ((j['available'] as List?) ?? const [])
.whereType<Map<dynamic, dynamic>>()
.map((m) => SessionMode.fromJson(Map<String, dynamic>.from(m)))
.whereType<SessionMode>()
.toList(),
);
}
class Project {
Project({
required this.id,
required this.name,
required this.path,
this.pinned = false,
this.lastActivityAt = 0,
});
final String id;
final String name;
final String path;
final bool pinned;
final int lastActivityAt;
}
/// A single CI check on a PR head, normalized server-side from `gh`'s
/// `statusCheckRollup` (see server `PrCheckDTO`). Rendered in the PR pill's
/// hover popover.
class PrCheck {
const PrCheck({
required this.name,
required this.bucket,
this.workflowName,
this.detailsUrl,
});
/// The check/context name, e.g. `test` or `CodeRabbit`.
final String name;
/// `pass` | `fail` | `pending` | `skipping` | `cancel`.
final String bucket;
/// Owning workflow (Actions checks), or null for a legacy status context.
final String? workflowName;
/// Deep link to the check's details, or null when the provider gave none.
final String? detailsUrl;
static PrCheck? fromJson(Map<String, dynamic> j) {
final name = j['name'];
if (name is! String) return null;
return PrCheck(
name: name,
bucket: j['bucket'] is String ? j['bucket'] as String : 'pending',
workflowName: j['workflowName'] is String
? j['workflowName'] as String
: null,
detailsUrl: j['detailsUrl'] is String ? j['detailsUrl'] as String : null,
);
}
}
/// An open pull request tied to a worktree's branch (surfaced via `gh`).
class PullRequest {
const PullRequest({
required this.number,
required this.url,
required this.state,
required this.title,
required this.isDraft,
this.mergeable,
this.mergeStateStatus,
this.baseRefName,
this.checks = const [],
this.checkRollup = 'none',
this.unresolvedComments = 0,
this.stale = false,
this.unresolvedUnknown = false,
});
final int number;
final String url;
final String state;
final String title;
final bool isDraft;
/// MERGEABLE | CONFLICTING | UNKNOWN, or null when `gh` didn't report it.
final String? mergeable;
/// CLEAN | BLOCKED | BEHIND | DIRTY | …, or null when unreported.
final String? mergeStateStatus;
/// The branch this PR merges into. "Wrap up" fast-forwards this one after the
/// PR lands; null on a server that predates the field, and the server then
/// falls back to the repo's default branch.
final String? baseRefName;
/// Per-check status for the hover popover. Empty when there are no checks.
final List<PrCheck> checks;
/// Aggregate CI verdict: `pass` | `fail` | `pending` | `none`.
final String checkRollup;
/// Count of unresolved review threads on the PR.
final int unresolvedComments;
/// True when this PR was not re-fetched successfully (a throttled/failed
/// lookup); the last-known state is retained and the pill is shown dimmed
/// (SPEC-32 G2). Defaults false on any server that predates the field.
final bool stale;
/// True when `unresolvedComments` was shed to save quota, so its value is not
/// reliable and the count should be hidden rather than shown as a lie.
/// Defaults false on any server that predates the field.
final bool unresolvedUnknown;
static PullRequest? fromJson(Map<String, dynamic> j) {
final number = j['number'];
if (number is! num) return null;
return PullRequest(
number: number.toInt(),
url: j['url'] is String ? j['url'] as String : '',
state: j['state'] is String ? j['state'] as String : 'OPEN',
title: j['title'] is String ? j['title'] as String : '',
isDraft: j['isDraft'] == true,
mergeable: j['mergeable'] is String ? j['mergeable'] as String : null,
mergeStateStatus: j['mergeStateStatus'] is String
? j['mergeStateStatus'] as String
: null,
baseRefName: j['baseRefName'] is String
? j['baseRefName'] as String
: null,
checks: ((j['checks'] as List?) ?? const [])
.whereType<Map<dynamic, dynamic>>()
.map((c) => PrCheck.fromJson(Map<String, dynamic>.from(c)))
.whereType<PrCheck>()
.toList(),
checkRollup: j['checkRollup'] is String
? j['checkRollup'] as String
: 'none',
unresolvedComments: (j['unresolvedComments'] as num?)?.toInt() ?? 0,
stale: j['stale'] == true,
unresolvedUnknown: j['unresolvedUnknown'] == true,
);
}
}
/// An open pull request as returned by the `pr.list` command, used to populate
/// the "New worktree from PR" picker.
class OpenPr {
const OpenPr({
required this.number,
required this.title,
required this.headRefName,
required this.isDraft,
required this.url,
});
final int number;
final String title;
final String headRefName;
final bool isDraft;
final String url;
static OpenPr fromJson(Map<String, dynamic> j) => OpenPr(
number: (j['number'] as num?)?.toInt() ?? 0,
title: j['title'] is String ? j['title'] as String : '',
headRefName: j['headRefName'] is String ? j['headRefName'] as String : '',
isDraft: j['isDraft'] == true,
url: j['url'] is String ? j['url'] as String : '',
);
}
/// Context-window + cost snapshot for one session (SPEC-37), pushed via the
/// `session.usage` event.
///
/// Every reading is nullable because the three sources report different subsets:
/// codex sends a full token breakdown and window but no cost, ACP sends only
/// used/size/cost, and pi (which reports nothing over ACP) sends what
/// `ctx.getContextUsage()` knows. **Null means unmeasured, never zero** — the
/// same rule [BudgetBucket] follows, because a zeroed bar and an unknown bar
/// mean opposite things.
class SessionUsage {
const SessionUsage({
this.contextTokens,
this.contextWindow,
this.totals,
this.cost,
required this.measuredAt,
});
/// Tokens currently occupying the context window — the numerator of
/// [fraction]. This is the last request's total, not the session total.
final int? contextTokens;
/// Context window size in tokens, when the agent reports one.
final int? contextWindow;
/// Cumulative session token counts — **billing**, not context occupancy.
/// Deliberately a separate field so it can never be drawn against
/// [contextWindow].
final SessionUsageTotals? totals;
/// Cumulative session cost, when the agent prices its own calls.
final UsageCost? cost;
/// Epoch ms this snapshot was measured (0 when the server omitted it).
final int measuredAt;
/// Share of the context window in use, or null when either half is unmeasured.
///
/// Clamped to 1.0: providers occasionally report a context slightly past the
/// advertised window, which would otherwise overflow the bar.
double? get fraction {
final used = contextTokens;
final window = contextWindow;
if (used == null || window == null || window <= 0) return null;
return (used / window).clamp(0.0, 1.0);
}
static int? _int(Object? v) => v is num ? v.toInt() : null;
static SessionUsage fromJson(Map<String, dynamic> j) => SessionUsage(
contextTokens: _int(j['contextTokens']),
contextWindow: _int(j['contextWindow']),
totals: j['totals'] is Map
? SessionUsageTotals.fromJson(
Map<String, dynamic>.from(j['totals'] as Map),
)
: null,
cost: j['cost'] is Map
? UsageCost.fromJson(Map<String, dynamic>.from(j['cost'] as Map))
: null,
measuredAt: _int(j['measuredAt']) ?? 0,
);
}
/// Cumulative per-category token counts for a session (SPEC-37) — what the
/// session has *billed*, as opposed to what currently occupies the context.
/// Only codex reports these; every field is null for the other agents.
class SessionUsageTotals {
const SessionUsageTotals({
this.total,
this.input,
this.cachedInput,
this.cacheWrite,
this.output,
this.reasoning,
});
final int? total;
final int? input;
/// Input tokens served from the provider's prompt cache.
final int? cachedInput;
/// Input tokens written *into* the cache.
final int? cacheWrite;
final int? output;
/// Reasoning/thinking output tokens, when billed separately.
final int? reasoning;
static SessionUsageTotals fromJson(Map<String, dynamic> j) {
int? at(String k) => j[k] is num ? (j[k] as num).toInt() : null;
return SessionUsageTotals(
total: at('total'),
input: at('input'),
cachedInput: at('cachedInput'),
cacheWrite: at('cacheWrite'),
output: at('output'),
reasoning: at('reasoning'),
);
}
}
/// Cumulative session cost. Both halves are required: an amount with no currency
/// cannot be rendered honestly, so a partial cost is treated as no cost at all.
class UsageCost {
const UsageCost({required this.amount, required this.currency});
final double amount;
final String currency;
static UsageCost? fromJson(Map<String, dynamic> j) {
final amount = j['amount'];
final currency = j['currency'];
if (amount is! num || currency is! String) return null;
return UsageCost(amount: amount.toDouble(), currency: currency);
}
}
/// Health of the GitHub API budget, driven server-side by time-to-empty rather
/// than percentage remaining (SPEC-32 §6.1). `unknown` means never measured
/// (distinct from a real, measured value) and drives a dimmed icon.
enum BudgetLevel { healthy, warm, critical, paused, unknown }
BudgetLevel parseBudgetLevel(String s) => switch (s) {
'healthy' => BudgetLevel.healthy,
'warm' => BudgetLevel.warm,
'critical' => BudgetLevel.critical,
'paused' => BudgetLevel.paused,
_ => BudgetLevel.unknown,
};
/// One GitHub rate-limit bucket (`core`, `graphql`, or `search`). A bucket is
/// `null` on the owning [GithubBudget] when it has not been measured yet —
/// **unmeasured is not the same as empty**, and the two render differently, so
/// callers must never coerce a missing bucket into a zeroed one.
class BudgetBucket {
const BudgetBucket({
required this.limit,
required this.remaining,
required this.resetAt,
required this.mine,
required this.others,
});
final int limit;
final int remaining;
/// Epoch **milliseconds** when the window resets (the server already
/// converted from GitHub's seconds). The `search` bucket resets per minute;
/// the two hourly buckets on a fixed absolute reset.
final int resetAt;
/// Requests attributed to makit in this window.
final int mine;
/// Derived spend by other tools on the same token (`limit-remaining-mine`).
final int others;
/// Returns null when [limit]/[remaining] are missing or non-numeric — the
/// caller treats that as an unmeasured bucket, not a zeroed one.
static BudgetBucket? fromJson(Map<String, dynamic> j) {
final limit = j['limit'];
final remaining = j['remaining'];
if (limit is! num || remaining is! num) return null;
return BudgetBucket(
limit: limit.toInt(),
remaining: remaining.toInt(),
resetAt: j['resetAt'] is num ? (j['resetAt'] as num).toInt() : 0,
mine: j['mine'] is num ? (j['mine'] as num).toInt() : 0,
others: j['others'] is num ? (j['others'] as num).toInt() : 0,
);
}
}
/// One per-minute slot of the trailing 60-minute burn history, used by the
/// popover's sparkline. Oldest first.
class BudgetHistorySlot {
const BudgetHistorySlot({required this.mine, required this.others});
final int mine;
final int others;
static BudgetHistorySlot? fromJson(Map<String, dynamic> j) {
final mine = j['mine'];
final others = j['others'];
if (mine is! num && others is! num) return null;
return BudgetHistorySlot(
mine: mine is num ? mine.toInt() : 0,
others: others is num ? others.toInt() : 0,
);
}
}
/// Gateway spend counters (SPEC-32 §6.4). Present only once the gateway has
/// run at least one measurement; a `null` [GithubBudget.stats] means unmeasured.
class BudgetStats {
const BudgetStats({required this.execs, required this.cacheHits});
final int execs;
final int cacheHits;
static BudgetStats fromJson(Map<String, dynamic> j) => BudgetStats(
execs: j['execs'] is num ? (j['execs'] as num).toInt() : 0,
cacheHits: j['cacheHits'] is num ? (j['cacheHits'] as num).toInt() : 0,
);
}
/// The GitHub API budget snapshot pushed via the `github.budget` frame
/// (SPEC-32 §6.6), surfaced by the desktop sidebar footer icon + popover.
///
/// Tolerant by construction: any of the three buckets may be `null`
/// (unmeasured), [msUntilEmpty]/[retryAfterMs] are meaningfully nullable
/// ("never empties" / "no burst limit"), [history] defaults to empty, and
/// [stats] is `null` until the gateway has measured.
class GithubBudget {
const GithubBudget({
required this.core,
required this.graphql,
required this.search,
required this.burnPerHour,
required this.msUntilEmpty,
required this.level,
required this.throttles,
required this.retryAfterMs,
required this.measuredAt,
required this.history,
required this.stats,
});
/// REST bucket (5,000/hour), or null when unmeasured.
final BudgetBucket? core;
/// GraphQL points bucket (5,000/hour) — makit's hot path — or null.
final BudgetBucket? graphql;
/// Search bucket (30/**minute**), or null. makit never searches, so a
/// non-idle search bucket is itself information (something else on the token).
final BudgetBucket? search;
/// Observed requests/hour over the trailing window.
final int burnPerHour;
/// Ms until the governing bucket empties at [burnPerHour], or null when it
/// will never empty (burn 0). Null is meaningful — do not coerce to 0.
final int? msUntilEmpty;
final BudgetLevel level;
/// Active throttles in ladder order; drives the popover banner + badge.
final List<String> throttles;
/// Set while a secondary (burst) limit is in force; null otherwise. Null is
/// meaningful ("no burst limit") — do not coerce to 0.
final int? retryAfterMs;
final int measuredAt;
/// Trailing 60 per-minute burn slots, oldest first. Empty when unreported.
final List<BudgetHistorySlot> history;
/// Gateway spend counters, or null when unmeasured.
final BudgetStats? stats;
/// Tolerant decode: never throws, never drops the whole snapshot for one bad
/// field. A missing/garbage/null bucket becomes a `null` field (unmeasured),
/// not a zeroed bucket.
static GithubBudget fromJson(Map<String, dynamic> j) {
final rawBuckets = j['buckets'];
final buckets = rawBuckets is Map
? Map<String, dynamic>.from(rawBuckets)
: const <String, dynamic>{};
BudgetBucket? bucket(String name) {
final v = buckets[name];
return v is Map
? BudgetBucket.fromJson(Map<String, dynamic>.from(v))
: null;
}
return GithubBudget(
core: bucket('core'),
graphql: bucket('graphql'),
search: bucket('search'),
burnPerHour: j['burnPerHour'] is num
? (j['burnPerHour'] as num).toInt()
: 0,
msUntilEmpty: j['msUntilEmpty'] is num
? (j['msUntilEmpty'] as num).toInt()
: null,
level: parseBudgetLevel(j['level'] is String ? j['level'] as String : ''),
// `as List?` would THROW on a present non-null non-list (e.g. a bare
// string), taking down the whole frame -- and decode failures are
// swallowed, so the footer would silently go stale. Degrade to empty.
throttles:
(j['throttles'] is List ? j['throttles'] as List : const <Object?>[])
.whereType<String>()
.toList(),
retryAfterMs: j['retryAfterMs'] is num
? (j['retryAfterMs'] as num).toInt()
: null,
measuredAt: j['measuredAt'] is num ? (j['measuredAt'] as num).toInt() : 0,
history: (j['history'] is List ? j['history'] as List : const <Object?>[])
.whereType<Map<dynamic, dynamic>>()
.map((m) => BudgetHistorySlot.fromJson(Map<String, dynamic>.from(m)))
.whereType<BudgetHistorySlot>()
.toList(),
stats: j['stats'] is Map
? BudgetStats.fromJson(Map<String, dynamic>.from(j['stats'] as Map))
: null,
);
}
}
/// One git worktree of a repo. `isPrimary` marks the repo's main checkout;
/// other worktrees are feature branches created for sessions. Diff stats are
/// measured against the repo's default branch.
class Worktree {
const Worktree({
required this.id,
required this.path,
required this.branch,
required this.isPrimary,
required this.insertions,
required this.deletions,
required this.filesChanged,
required this.sessionIds,
this.uncommittedFiles = 0,
this.aheadCount = 0,
this.behindCount = 0,
this.committedAt,
this.pr,
});
final String id;
final String path;
final String? branch;
final bool isPrimary;
final int insertions;
final int deletions;
final int filesChanged;
final List<String> sessionIds;
/// Files with uncommitted changes (staged + unstaged + untracked).
final int uncommittedFiles;
/// Commits not yet pushed to the remote (what a push would send).
final int aheadCount;
/// Commits on the upstream not yet local (what a pull would fetch).
final int behindCount;
/// HEAD commit time, or null when unavailable.
final DateTime? committedAt;
final PullRequest? pr;
bool get hasChanges => insertions > 0 || deletions > 0 || filesChanged > 0;
static Worktree? fromJson(Map<String, dynamic> j) {
final path = j['path'];
if (path is! String) return null;
final rawPr = j['pr'];
return Worktree(
id: j['id'] is String ? j['id'] as String : path,
path: path,
branch: j['branch'] is String ? j['branch'] as String : null,
isPrimary: j['isPrimary'] == true,
insertions: (j['insertions'] as num?)?.toInt() ?? 0,
deletions: (j['deletions'] as num?)?.toInt() ?? 0,
filesChanged: (j['filesChanged'] as num?)?.toInt() ?? 0,
uncommittedFiles: (j['uncommittedFiles'] as num?)?.toInt() ?? 0,
aheadCount: (j['aheadCount'] as num?)?.toInt() ?? 0,
behindCount: (j['behindCount'] as num?)?.toInt() ?? 0,
sessionIds: ((j['sessionIds'] as List?) ?? const [])
.whereType<String>()
.toList(),
committedAt: (j['committedAt'] as num?) != null
? DateTime.fromMillisecondsSinceEpoch(
(j['committedAt'] as num).toInt(),
)
: null,
pr: rawPr is Map
? PullRequest.fromJson(Map<String, dynamic>.from(rawPr))
: null,
);
}
}
/// A repo on the home screen: a [Project] enriched with git intelligence —
/// its default/current branch and live worktrees.
/// Where an effective per-repo value came from. Drives the badge; the app is told
/// this rather than deriving it, so one rule lives on the server.
enum SettingSource { override, environment, defaultValue }
SettingSource _sourceFrom(Object? raw) => switch (raw) {
'override' => SettingSource.override,
'environment' => SettingSource.environment,
// Anything unrecognised reads as the default rather than throwing: a newer
// server adding a source must not crash an older app.
_ => SettingSource.defaultValue,
};
/// An effective value and its source.
class Resolved<T> {
const Resolved(this.value, this.source);
final T value;
final SettingSource source;
/// True when a repo-level value replaces the inherited one — the only state that
/// earns a reset affordance.
bool get isOverride => source == SettingSource.override;
@override
bool operator ==(Object other) =>
other is Resolved<T> && other.value == value && other.source == source;
@override
int get hashCode => Object.hash(value, source);
}
/// What detection concluded about a repo's forge.
class RepoForge {
const RepoForge({required this.software, required this.host, this.authed});
final String software;
final String host;
/// Whether a credential is configured for that host. Absent for GitHub, where
/// `gh`'s budget is not host-specific authentication.
final bool? authed;
static RepoForge? fromJson(Object? raw) {
if (raw is! Map) return null;
final j = Map<String, dynamic>.from(raw);
final software = j['software'];
final host = j['host'];
if (software is! String || host is! String) return null;
return RepoForge(
software: software,
host: host,
authed: j['authed'] is bool ? j['authed'] as bool : null,
);
}
}
/// Per-repo settings as the server resolved them.
class RepoSettings {
const RepoSettings({
required this.worktreeRoot,
required this.provider,
required this.hasRemote,
this.defaultBranch,
this.logoHue,
this.forge,
});
final Resolved<String> worktreeRoot;
final Resolved<String> provider;
/// False = no `origin`, so no forge is possible. A different statement from
/// "not identified yet", which is [forge] being null.
final bool hasRemote;
/// Present ONLY when overridden; otherwise read `RepoInfo.defaultBranch`.
final Resolved<String>? defaultBranch;
final int? logoHue;
/// Null means detection has not run for this repo yet, never "no forge".
final RepoForge? forge;
static RepoSettings? fromJson(Object? raw) {
if (raw is! Map) return null;
final j = Map<String, dynamic>.from(raw);
final root = _resolvedString(j['worktreeRoot']);
if (root == null) return null;
return RepoSettings(
worktreeRoot: root,
provider:
_resolvedString(j['provider']) ??
const Resolved('auto', SettingSource.defaultValue),
hasRemote: j['hasRemote'] == true,
defaultBranch: _resolvedString(j['defaultBranch']),
logoHue: j['logoHue'] is num ? (j['logoHue'] as num).toInt() : null,