pantheon-opencode 1.6.1 → 1.6.2-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/AGENTS.global.md +11 -11
  2. package/AGENTS.md +2 -2
  3. package/CHANGELOG.md +29 -0
  4. package/README.md +100 -19
  5. package/README.pt-BR.md +27 -11
  6. package/bin/pantheon-init.mjs +106 -19
  7. package/package.json +3 -2
  8. package/plugin.json +1 -1
  9. package/pyproject.toml +1 -1
  10. package/scripts/build-agents-md.mjs +1 -1
  11. package/scripts/doctor.mjs +213 -45
  12. package/scripts/install/agents-md.mjs +2 -1
  13. package/scripts/install/config-migration.mjs +344 -393
  14. package/scripts/install/config-paths.mjs +15 -0
  15. package/scripts/install/mcp-permissions.mjs +164 -0
  16. package/scripts/install/opencode-version.mjs +31 -13
  17. package/scripts/install/opencode-wildcard.mjs +106 -0
  18. package/scripts/install/opencode.mjs +240 -69
  19. package/scripts/install/plan-artifact.mjs +12 -1
  20. package/scripts/install/plugin.mjs +17 -1
  21. package/scripts/install/v2-capabilities.mjs +5 -6
  22. package/scripts/package-evidence.mjs +1 -0
  23. package/scripts/sandbox-env.sh +174 -0
  24. package/scripts/setup-v2-config.mjs +1703 -0
  25. package/scripts/setup.mjs +415 -0
  26. package/scripts/sync-tui.mjs +9 -1
  27. package/scripts/test-opencode-v2-sandbox.sh +438 -151
  28. package/scripts/update-skills-lock.mjs +30 -0
  29. package/skills-lock.json +10 -10
  30. package/src/agents/aphrodite.md +5 -2
  31. package/src/agents/apollo.md +5 -0
  32. package/src/agents/athena.md +6 -1
  33. package/src/agents/demeter.md +5 -1
  34. package/src/agents/gaia.md +4 -0
  35. package/src/agents/hephaestus.md +6 -1
  36. package/src/agents/hermes.md +6 -3
  37. package/src/agents/iris.md +5 -1
  38. package/src/agents/mnemosyne.md +20 -50
  39. package/src/agents/nyx.md +5 -1
  40. package/src/agents/prometheus.md +4 -0
  41. package/src/agents/talos.md +4 -0
  42. package/src/agents/themis.md +4 -0
  43. package/src/agents/zeus.md +9 -3
  44. package/src/instructions/agent-return-format.instructions.md +1 -1
  45. package/src/instructions/memory-protocol.instructions.md +3 -3
  46. package/src/instructions/test-economy.instructions.md +6 -6
  47. package/src/mcp/pantheon_vision.py +37 -36
  48. package/src/pantheon/cost-command.ts +30 -133
  49. package/src/pantheon/model-pricing.ts +1 -536
  50. package/src/pantheon/v2-vision.ts +34 -29
  51. package/src/pantheon/vision.ts +43 -10
  52. package/src/plugin-v2.ts +30 -53
  53. package/src/plugins/tui/THIRD_PARTY_NOTICES.md +24 -0
  54. package/src/plugins/tui/dist/cost-data-CCZUs1aJ.js +749 -0
  55. package/src/plugins/tui/dist/cost-data-CCZUs1aJ.js.map +1 -0
  56. package/src/plugins/tui/dist/quota-adapters.d.ts +89 -0
  57. package/src/plugins/tui/dist/quota-adapters.d.ts.map +1 -0
  58. package/src/plugins/tui/dist/quota-adapters.js +1142 -0
  59. package/src/plugins/tui/dist/quota-adapters.js.map +1 -0
  60. package/src/plugins/tui/dist/quota-cli.d.ts +17 -0
  61. package/src/plugins/tui/dist/quota-cli.d.ts.map +1 -0
  62. package/src/plugins/tui/dist/quota-cli.js +184 -0
  63. package/src/plugins/tui/dist/quota-cli.js.map +1 -0
  64. package/src/plugins/tui/dist/quota-rpc-DMmXBhBe.js +684 -0
  65. package/src/plugins/tui/dist/quota-rpc-DMmXBhBe.js.map +1 -0
  66. package/src/plugins/tui/dist/server-v2.d.ts +14 -0
  67. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -0
  68. package/src/plugins/tui/dist/server-v2.js +796 -0
  69. package/src/plugins/tui/dist/server-v2.js.map +1 -0
  70. package/src/plugins/tui/dist/tui-v2.d.ts +375 -53
  71. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  72. package/src/plugins/tui/dist/tui-v2.js +5876 -530
  73. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  74. package/src/plugins/tui/dist/tui.js +1 -1
  75. package/src/plugins/tui/dist/usage-history-contract-nt1rnBPE.js +118 -0
  76. package/src/plugins/tui/dist/usage-history-contract-nt1rnBPE.js.map +1 -0
  77. package/src/plugins/tui/dist/usage-history-worker.js +25 -0
  78. package/src/plugins/tui/dist/usage-history-worker.js.map +1 -0
  79. package/src/plugins/tui/index-v2.ts +3 -6
  80. package/src/plugins/tui/package-lock.json +17 -2
  81. package/src/plugins/tui/package.json +6 -3
  82. package/src/plugins/tui/src/context-gauge.ts +59 -0
  83. package/src/plugins/tui/src/cost-data.ts +607 -0
  84. package/src/plugins/tui/src/go-key-diagnostic-ui.ts +100 -0
  85. package/src/plugins/tui/src/go-key-diagnostic.ts +125 -0
  86. package/src/plugins/tui/src/index-v2.tsx +231 -240
  87. package/src/plugins/tui/src/model-pricing.ts +536 -0
  88. package/src/plugins/tui/src/model-usage-limits.ts +4 -0
  89. package/src/plugins/tui/src/quota-adapters.ts +1598 -0
  90. package/src/plugins/tui/src/quota-cli.ts +237 -0
  91. package/src/plugins/tui/src/quota-rpc.ts +373 -0
  92. package/src/plugins/tui/src/quota-v2-model.ts +1032 -0
  93. package/src/plugins/tui/src/quota-v2.tsx +1238 -0
  94. package/src/plugins/tui/src/server-v2.ts +985 -0
  95. package/src/plugins/tui/src/sidebar-width.ts +129 -0
  96. package/src/plugins/tui/src/usage-history-contract.ts +217 -0
  97. package/src/plugins/tui/src/usage-history-validation.ts +104 -0
  98. package/src/plugins/tui/src/usage-history-view.tsx +236 -0
  99. package/src/plugins/tui/src/usage-history-worker.ts +25 -0
  100. package/src/plugins/tui/src/usage-view-model.ts +272 -0
  101. package/src/plugins/tui/tsconfig.typecheck.json +6 -1
  102. package/src/plugins/tui/tsdown.config.ts +44 -5
  103. package/src/routing.yml +72 -13
  104. package/src/skills/README.md +4 -0
  105. package/src/skills/agent-coordination/SKILL.md +0 -3
  106. package/src/skills/artifact-management/SKILL.md +0 -3
  107. package/src/skills/auto-continue/SKILL.md +0 -3
  108. package/src/skills/code-review-checklist/SKILL.md +0 -3
  109. package/src/skills/context-compression/SKILL.md +0 -3
  110. package/src/skills/memory-bank/SKILL.md +6 -28
  111. package/src/skills/session-goal/SKILL.md +0 -3
  112. package/src/skills/simplify/SKILL.md +5 -4
  113. package/src/skills/tdd-with-agents/SKILL.md +0 -3
  114. package/src/skills/visual-review-pipeline/SKILL.md +0 -1
  115. package/src/pantheon/memory-context.ts +0 -1017
@@ -0,0 +1,129 @@
1
+ /** Conservative content budget; the host sidebar slot does not report its runtime width. */
2
+ export const SIDEBAR_CONTENT_WIDTH = 34
3
+
4
+ export const GRAPHEMES = new Intl.Segmenter(undefined, { granularity: 'grapheme' })
5
+
6
+ /** A grapheme the host draws two cells wide: emoji presentation, an extended
7
+ * pictograph (a bare `❤` counts too, exactly as the host's `emoji-regex`
8
+ * does) and a regional-indicator pair (a flag). */
9
+ const EMOJI_GLYPH = /\p{Emoji_Presentation}|\p{Extended_Pictographic}|\p{Regional_Indicator}/u
10
+ /** VS16 asks for emoji presentation; without it `1` is one cell, with it the
11
+ * keycap sequence is drawn as one two-cell glyph. */
12
+ const EMOJI_PRESENTATION_SELECTOR = '\uFE0F'
13
+ /** Unicode default-ignorable code points carry no width of their own. */
14
+ const IGNORABLE_GLYPH = /^\p{Default_Ignorable_Code_Point}$/u
15
+ /** East Asian Wide/Fullwidth ranges — two cells, never the ambiguous width
16
+ * (the host measures ambiguous as narrow, so `▸`/`✓`/`—` stay one cell).
17
+ * Generated from the host's own measurement (`string-width` over every code
18
+ * point, emoji excluded), so this table can be regenerated verbatim when the
19
+ * host upgrades its Unicode data instead of being hand-edited. */
20
+ const CELL_WIDE_RANGES: readonly (readonly [number, number])[] = [
21
+ [0x1100, 0x115e],
22
+ [0x2329, 0x232a],
23
+ [0x2630, 0x2637],
24
+ [0x268a, 0x268f],
25
+ [0x2e80, 0x2e99],
26
+ [0x2e9b, 0x2ef3],
27
+ [0x2f00, 0x2fd5],
28
+ [0x2ff0, 0x302f],
29
+ [0x3031, 0x303c],
30
+ [0x303e, 0x303e],
31
+ [0x3041, 0x3096],
32
+ [0x3099, 0x30ff],
33
+ [0x3105, 0x312f],
34
+ [0x3131, 0x3163],
35
+ [0x3165, 0x318e],
36
+ [0x3190, 0x31e5],
37
+ [0x31ef, 0x321e],
38
+ [0x3220, 0x3247],
39
+ [0x3250, 0x3296],
40
+ [0x3298, 0x3298],
41
+ [0x329a, 0xa48c],
42
+ [0xa490, 0xa4c6],
43
+ [0xa960, 0xa97c],
44
+ [0xac00, 0xd7a3],
45
+ [0xf900, 0xfaff],
46
+ [0xfe10, 0xfe19],
47
+ [0xfe30, 0xfe52],
48
+ [0xfe54, 0xfe66],
49
+ [0xfe68, 0xfe6b],
50
+ [0xff01, 0xff60],
51
+ [0xffe0, 0xffe6],
52
+ [0x16fe0, 0x16fe4],
53
+ [0x16ff0, 0x16ff6],
54
+ [0x17000, 0x18cda],
55
+ [0x18cff, 0x18d20],
56
+ [0x18d80, 0x18df2],
57
+ [0x18e00, 0x19191],
58
+ [0x191a0, 0x191d2],
59
+ [0x1aff0, 0x1aff3],
60
+ [0x1aff5, 0x1affb],
61
+ [0x1affd, 0x1affe],
62
+ [0x1b000, 0x1b128],
63
+ [0x1b132, 0x1b132],
64
+ [0x1b150, 0x1b152],
65
+ [0x1b155, 0x1b155],
66
+ [0x1b164, 0x1b168],
67
+ [0x1b170, 0x1b2fb],
68
+ [0x1d300, 0x1d356],
69
+ [0x1d360, 0x1d376],
70
+ [0x1f200, 0x1f200],
71
+ [0x1f210, 0x1f219],
72
+ [0x1f21b, 0x1f22e],
73
+ [0x1f230, 0x1f231],
74
+ [0x1f23b, 0x1f23b],
75
+ [0x1f240, 0x1f248],
76
+ [0x1f260, 0x1f265],
77
+ [0x20000, 0x2fffd],
78
+ [0x30000, 0x3fffd],
79
+ ]
80
+
81
+ /** One code point the terminal draws no cell for: control characters, the
82
+ * zero-width joiners/marks, combining marks and variation selectors. */
83
+ function isZeroWidthCodePoint(code: number, glyph: string): boolean {
84
+ if (code <= 0x1f || (code >= 0x7f && code <= 0x9f)) return true
85
+ if (code >= 0x200b && code <= 0x200f) return true
86
+ if (code === 0xfeff) return true
87
+ if (code >= 0x300 && code <= 0x36f) return true
88
+ if (code >= 0x1ab0 && code <= 0x1aff) return true
89
+ if (code >= 0x1dc0 && code <= 0x1dff) return true
90
+ if (code >= 0x20d0 && code <= 0x20ff) return true
91
+ if (code >= 0xfe00 && code <= 0xfe0f) return true
92
+ if (code >= 0xfe20 && code <= 0xfe2f) return true
93
+ if (code >= 0xe0100 && code <= 0xe01ef) return true
94
+ if (code >= 0xd800 && code <= 0xdfff) return true // a lone surrogate
95
+ return IGNORABLE_GLYPH.test(glyph)
96
+ }
97
+
98
+ function isWideCodePoint(code: number): boolean {
99
+ for (const [low, high] of CELL_WIDE_RANGES) {
100
+ if (code < low) return false
101
+ if (code <= high) return true
102
+ }
103
+ return false
104
+ }
105
+
106
+ /** Cells one grapheme occupies. */
107
+ function graphemeWidth(segment: string): number {
108
+ if (EMOJI_GLYPH.test(segment)) return 2
109
+ // A lone VS16 carries no width; after a base it asks for emoji presentation.
110
+ if (segment.length > 1 && segment.includes(EMOJI_PRESENTATION_SELECTOR)) return 2
111
+ let width = 0
112
+ for (const glyph of segment) {
113
+ const code = glyph.codePointAt(0) ?? 0
114
+ if (isZeroWidthCodePoint(code, glyph)) continue
115
+ width += isWideCodePoint(code) ? 2 : 1
116
+ }
117
+ return width
118
+ }
119
+
120
+ /** Terminal cells `value` occupies — the unit every column in this plugin is
121
+ * measured in. Mirrors the host (that is how `@opentui/core` sizes a text
122
+ * run): emoji count as two cells, East Asian Wide/Fullwidth as two, East
123
+ * Asian Ambiguous as one, combining marks and variation selectors as none.
124
+ * Pure. */
125
+ export function cellWidth(value: string): number {
126
+ let width = 0
127
+ for (const { segment } of GRAPHEMES.segment(value)) width += graphemeWidth(segment)
128
+ return width
129
+ }
@@ -0,0 +1,217 @@
1
+ export const MAX_HISTORY_BUCKETS = 366
2
+ export const MAX_HISTORY_MODELS = 64
3
+ export const MAX_HISTORY_QUERY_MS = 5_000
4
+
5
+ export type UsageHistoryRpcPeriod = '7d' | '15d' | '30d' | 'total'
6
+
7
+ interface UsageHistorySourceTotals {
8
+ input: number
9
+ output: number
10
+ cacheRead: number
11
+ cacheWrite: number
12
+ total: number
13
+ }
14
+
15
+ interface UsageHistorySourceBucket extends UsageHistorySourceTotals {
16
+ date: string
17
+ estimatedUsd?: number
18
+ pricingComplete: boolean
19
+ }
20
+
21
+ interface UsageHistorySourceModel {
22
+ providerID: string
23
+ modelID: string
24
+ totals: UsageHistorySourceTotals
25
+ buckets: UsageHistorySourceBucket[]
26
+ estimatedUsd?: number
27
+ pricingComplete: boolean
28
+ }
29
+
30
+ interface UsageHistorySourceResult {
31
+ period: UsageHistoryRpcPeriod
32
+ coverageStart: string | null
33
+ partial: boolean
34
+ rows: number
35
+ buckets: UsageHistorySourceBucket[]
36
+ totals: UsageHistorySourceTotals
37
+ models: UsageHistorySourceModel[]
38
+ pricing: {
39
+ status: 'empty' | 'unavailable' | 'partial' | 'complete'
40
+ complete: boolean
41
+ estimatedUsd?: number
42
+ unpricedModels: number
43
+ }
44
+ }
45
+
46
+ export interface UsageHistoryRpcTotals {
47
+ input: number
48
+ output: number
49
+ cacheRead: number
50
+ cacheWrite: number
51
+ total: number
52
+ }
53
+
54
+ export interface UsageHistoryRpcBucket extends UsageHistoryRpcTotals {
55
+ date: string
56
+ estimatedUsd?: number
57
+ pricingComplete: boolean
58
+ }
59
+
60
+ export interface UsageHistoryRpcModel {
61
+ providerID: string
62
+ modelID: string
63
+ totals: UsageHistoryRpcTotals
64
+ estimatedUsd?: number
65
+ pricingComplete: boolean
66
+ }
67
+
68
+ export interface UsageHistoryRpcAvailable {
69
+ status: 'available' | 'partial'
70
+ period: UsageHistoryRpcPeriod
71
+ coverageStart: string | null
72
+ partial: boolean
73
+ truncated: boolean
74
+ rows: number
75
+ buckets: UsageHistoryRpcBucket[]
76
+ totals: UsageHistoryRpcTotals
77
+ models: UsageHistoryRpcModel[]
78
+ pricing: {
79
+ status: 'empty' | 'unavailable' | 'partial' | 'complete'
80
+ complete: boolean
81
+ billed: false
82
+ estimatedUsd?: number
83
+ unpricedModels: number
84
+ }
85
+ }
86
+
87
+ export interface UsageHistoryRpcUnavailable {
88
+ status: 'unavailable'
89
+ reason: 'invalid_period' | 'history_unavailable' | 'history_timeout'
90
+ }
91
+
92
+ export type UsageHistoryRpcResult = UsageHistoryRpcAvailable | UsageHistoryRpcUnavailable
93
+
94
+ export const USAGE_HISTORY_PERIODS: readonly UsageHistoryRpcPeriod[] = ['7d', '15d', '30d', 'total']
95
+
96
+ const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER
97
+ const SAFE_LABEL = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/
98
+ const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/
99
+
100
+ function safeCount(value: number, markTruncated: () => void): number {
101
+ if (!Number.isFinite(value) || value < 0) {
102
+ markTruncated()
103
+ return 0
104
+ }
105
+ if (!Number.isSafeInteger(value)) {
106
+ markTruncated()
107
+ return Math.min(Math.floor(value), MAX_SAFE_INTEGER)
108
+ }
109
+ return value
110
+ }
111
+
112
+ function safeEstimate(value: number | undefined, markTruncated: () => void): number | undefined {
113
+ if (value === undefined) return undefined
114
+ if (!Number.isFinite(value) || value < 0) {
115
+ markTruncated()
116
+ return undefined
117
+ }
118
+ const rounded = Math.round(value * 1e8) / 1e8
119
+ if (!Number.isFinite(rounded)) {
120
+ markTruncated()
121
+ return undefined
122
+ }
123
+ return rounded
124
+ }
125
+
126
+ function safeLabel(value: string, markTruncated: () => void): string {
127
+ if (!SAFE_LABEL.test(value)) {
128
+ markTruncated()
129
+ return 'unknown'
130
+ }
131
+ return value
132
+ }
133
+
134
+ function projectTotals(
135
+ value: UsageHistorySourceTotals,
136
+ markTruncated: () => void,
137
+ ): UsageHistoryRpcTotals {
138
+ return {
139
+ input: safeCount(value.input, markTruncated),
140
+ output: safeCount(value.output, markTruncated),
141
+ cacheRead: safeCount(value.cacheRead, markTruncated),
142
+ cacheWrite: safeCount(value.cacheWrite, markTruncated),
143
+ total: safeCount(value.total, markTruncated),
144
+ }
145
+ }
146
+
147
+ /** Project cost-command output to a bounded, non-identifying TUI contract. */
148
+ export function projectUsageHistoryResult(
149
+ result: UsageHistorySourceResult,
150
+ ): UsageHistoryRpcAvailable {
151
+ let unsafeOrTruncated = false
152
+ const markTruncated = (): void => {
153
+ unsafeOrTruncated = true
154
+ }
155
+ const sourceBuckets = result.buckets
156
+ const sourceModels = result.models
157
+ if (sourceBuckets.length > MAX_HISTORY_BUCKETS || sourceModels.length > MAX_HISTORY_MODELS) {
158
+ markTruncated()
159
+ }
160
+ const buckets = sourceBuckets.slice(-MAX_HISTORY_BUCKETS).flatMap((bucket) => {
161
+ if (!ISO_DATE.test(bucket.date)) {
162
+ markTruncated()
163
+ return []
164
+ }
165
+ const estimatedUsd = safeEstimate(bucket.estimatedUsd, markTruncated)
166
+ return [
167
+ {
168
+ date: bucket.date,
169
+ ...projectTotals(bucket, markTruncated),
170
+ ...(estimatedUsd === undefined ? {} : { estimatedUsd }),
171
+ pricingComplete: bucket.pricingComplete === true,
172
+ },
173
+ ]
174
+ })
175
+ const models = sourceModels.slice(0, MAX_HISTORY_MODELS).map((model) => {
176
+ const estimatedUsd = safeEstimate(model.estimatedUsd, markTruncated)
177
+ return {
178
+ providerID: safeLabel(model.providerID, markTruncated),
179
+ modelID: safeLabel(model.modelID, markTruncated),
180
+ totals: projectTotals(model.totals, markTruncated),
181
+ ...(estimatedUsd === undefined ? {} : { estimatedUsd }),
182
+ pricingComplete: model.pricingComplete === true,
183
+ }
184
+ })
185
+ let coverageStart = result.coverageStart
186
+ if (coverageStart !== null && !ISO_DATE.test(coverageStart)) {
187
+ markTruncated()
188
+ coverageStart = null
189
+ }
190
+ const pricingEstimate = safeEstimate(result.pricing.estimatedUsd, markTruncated)
191
+ const rows = safeCount(result.rows, markTruncated)
192
+ const totals = projectTotals(result.totals, markTruncated)
193
+ const unpricedModels = safeCount(result.pricing.unpricedModels, markTruncated)
194
+ const truncated = unsafeOrTruncated
195
+ return {
196
+ status: result.partial || truncated ? 'partial' : 'available',
197
+ period: result.period,
198
+ coverageStart,
199
+ partial: result.partial,
200
+ truncated,
201
+ rows,
202
+ buckets,
203
+ totals,
204
+ models,
205
+ pricing: {
206
+ status: result.pricing.status,
207
+ complete: result.pricing.complete === true,
208
+ billed: false,
209
+ ...(pricingEstimate === undefined ? {} : { estimatedUsd: pricingEstimate }),
210
+ unpricedModels,
211
+ },
212
+ }
213
+ }
214
+
215
+ export function isUsageHistoryPeriod(value: unknown): value is UsageHistoryRpcPeriod {
216
+ return typeof value === 'string' && USAGE_HISTORY_PERIODS.includes(value as UsageHistoryRpcPeriod)
217
+ }
@@ -0,0 +1,104 @@
1
+ import type {
2
+ UsageHistoryRpcBucket,
3
+ UsageHistoryRpcModel,
4
+ UsageHistoryRpcResult,
5
+ UsageHistoryRpcTotals,
6
+ } from './usage-history-contract'
7
+ import type { ActiveContextCostResult } from './usage-view-model'
8
+
9
+ function asRecord(value: unknown): Record<string, unknown> | null {
10
+ return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : null
11
+ }
12
+
13
+ function isTotals(value: unknown): value is UsageHistoryRpcTotals {
14
+ const totals = asRecord(value)
15
+ return (
16
+ totals !== null &&
17
+ ['input', 'output', 'cacheRead', 'cacheWrite', 'total'].every(
18
+ (key) =>
19
+ typeof totals[key] === 'number' && Number.isSafeInteger(totals[key]) && totals[key] >= 0,
20
+ )
21
+ )
22
+ }
23
+
24
+ function isHistoryBucket(value: unknown): value is UsageHistoryRpcBucket {
25
+ const bucket = asRecord(value)
26
+ return (
27
+ bucket !== null &&
28
+ typeof bucket.date === 'string' &&
29
+ /^\d{4}-\d{2}-\d{2}$/.test(bucket.date) &&
30
+ isTotals(bucket) &&
31
+ typeof bucket.pricingComplete === 'boolean' &&
32
+ (bucket.estimatedUsd === undefined ||
33
+ (typeof bucket.estimatedUsd === 'number' && Number.isFinite(bucket.estimatedUsd)))
34
+ )
35
+ }
36
+
37
+ function isHistoryModel(value: unknown): value is UsageHistoryRpcModel {
38
+ const model = asRecord(value)
39
+ return (
40
+ model !== null &&
41
+ typeof model.providerID === 'string' &&
42
+ typeof model.modelID === 'string' &&
43
+ isTotals(model.totals) &&
44
+ typeof model.pricingComplete === 'boolean' &&
45
+ (model.estimatedUsd === undefined ||
46
+ (typeof model.estimatedUsd === 'number' && Number.isFinite(model.estimatedUsd)))
47
+ )
48
+ }
49
+
50
+ export function isUsageHistoryRpcResult(value: unknown): value is UsageHistoryRpcResult {
51
+ const result = asRecord(value)
52
+ if (!result) return false
53
+ if (result.status === 'unavailable') {
54
+ return ['invalid_period', 'history_unavailable', 'history_timeout'].includes(
55
+ String(result.reason),
56
+ )
57
+ }
58
+ if (result.status !== 'available' && result.status !== 'partial') return false
59
+ const pricing = asRecord(result.pricing)
60
+ return (
61
+ ['7d', '15d', '30d', 'total'].includes(String(result.period)) &&
62
+ (result.coverageStart === null || typeof result.coverageStart === 'string') &&
63
+ typeof result.partial === 'boolean' &&
64
+ typeof result.truncated === 'boolean' &&
65
+ typeof result.rows === 'number' &&
66
+ Number.isSafeInteger(result.rows) &&
67
+ result.rows >= 0 &&
68
+ Array.isArray(result.buckets) &&
69
+ result.buckets.every(isHistoryBucket) &&
70
+ isTotals(result.totals) &&
71
+ Array.isArray(result.models) &&
72
+ result.models.every(isHistoryModel) &&
73
+ pricing !== null &&
74
+ ['empty', 'unavailable', 'partial', 'complete'].includes(String(pricing.status)) &&
75
+ typeof pricing.complete === 'boolean' &&
76
+ pricing.billed === false &&
77
+ typeof pricing.unpricedModels === 'number' &&
78
+ Number.isSafeInteger(pricing.unpricedModels) &&
79
+ pricing.unpricedModels >= 0 &&
80
+ (pricing.estimatedUsd === undefined ||
81
+ (typeof pricing.estimatedUsd === 'number' && Number.isFinite(pricing.estimatedUsd)))
82
+ )
83
+ }
84
+
85
+ export function isActiveContextCostResult(value: unknown): value is ActiveContextCostResult {
86
+ const result = asRecord(value)
87
+ if (result?.billed !== false) return false
88
+ if (result.cacheDiscountApplied !== false) return false
89
+ if (result.basis !== 'pre-cache-context-tokens-times-input-price') return false
90
+ if (result.status === 'estimated') {
91
+ return typeof result.estimatedUsd === 'number' && Number.isFinite(result.estimatedUsd)
92
+ }
93
+ return (
94
+ result.status === 'unavailable' &&
95
+ [
96
+ 'invalid-context-token-count',
97
+ 'missing-model-identity',
98
+ 'no-pricing',
99
+ 'unknown-model',
100
+ 'ambiguous-model',
101
+ 'missing-cache-price',
102
+ ].includes(String(result.reason))
103
+ )
104
+ }
@@ -0,0 +1,236 @@
1
+ /** @jsxImportSource @opentui/solid */
2
+
3
+ import type { Context, KeymapLayer, PanelInput } from '@opencode/plugin/tui/context'
4
+ import { createEffect, createSignal, For, type JSX, onCleanup, Show } from 'solid-js'
5
+ import { quotaRpc } from './quota-rpc'
6
+ import type { UsageHistoryRpcPeriod, UsageHistoryRpcResult } from './usage-history-contract'
7
+ import { isActiveContextCostResult, isUsageHistoryRpcResult } from './usage-history-validation'
8
+ import {
9
+ type ActiveContextCostResult,
10
+ activeContextEstimateErrorLines,
11
+ activeContextEstimateLines,
12
+ activeContextEstimateMissingLines,
13
+ activeContextEstimatePendingLines,
14
+ USAGE_HISTORY_PERIOD_BINDINGS,
15
+ usageHistoryChartLines,
16
+ usageHistoryControlsLines,
17
+ usageHistoryCoverageLabel,
18
+ usageHistoryPartialWarning,
19
+ usageHistoryPricingLabel,
20
+ usageHistorySelectorLines,
21
+ usageHistoryTextLines,
22
+ usageHistoryUnavailableMessage,
23
+ } from './usage-view-model'
24
+
25
+ function location(context: Context): ReturnType<Context['data']['location']['default']> {
26
+ return context.location ?? context.data.location.default()
27
+ }
28
+
29
+ export function ActiveContextEstimate(props: {
30
+ context: Context
31
+ providerID: string | null
32
+ modelID: string | null
33
+ contextTokens: number | null
34
+ width: number
35
+ }): JSX.Element {
36
+ const [result, setResult] = createSignal<ActiveContextCostResult | null>(null)
37
+ const [loading, setLoading] = createSignal(false)
38
+ const [failed, setFailed] = createSignal(false)
39
+ const client = props.context.client.rpc(quotaRpc)
40
+
41
+ createEffect(() => {
42
+ const providerID = props.providerID
43
+ const modelID = props.modelID
44
+ const contextTokens = props.contextTokens
45
+ if (contextTokens === null) {
46
+ setResult(null)
47
+ setFailed(false)
48
+ setLoading(false)
49
+ return
50
+ }
51
+ if (!providerID || !modelID) {
52
+ setResult({
53
+ status: 'unavailable',
54
+ billed: false,
55
+ basis: 'pre-cache-context-tokens-times-input-price',
56
+ cacheDiscountApplied: false,
57
+ reason: 'missing-model-identity',
58
+ })
59
+ setFailed(false)
60
+ setLoading(false)
61
+ return
62
+ }
63
+
64
+ const controller = new AbortController()
65
+ let current = true
66
+ setResult(null)
67
+ setFailed(false)
68
+ setLoading(true)
69
+ try {
70
+ void client
71
+ .active_context_cost(
72
+ { providerID, modelID, contextTokens },
73
+ { signal: controller.signal, location: location(props.context) },
74
+ )
75
+ .then((response) => {
76
+ if (!current) return
77
+ if (isActiveContextCostResult(response)) setResult(response)
78
+ else setFailed(true)
79
+ })
80
+ .catch(() => {
81
+ if (current) setFailed(true)
82
+ })
83
+ .finally(() => {
84
+ if (current) setLoading(false)
85
+ })
86
+ } catch {
87
+ setFailed(true)
88
+ setLoading(false)
89
+ }
90
+
91
+ onCleanup(() => {
92
+ current = false
93
+ controller.abort()
94
+ })
95
+ })
96
+
97
+ const lines = (): string[] => {
98
+ if (loading()) return activeContextEstimatePendingLines(props.width)
99
+ if (failed()) return activeContextEstimateErrorLines(props.width)
100
+ const current = result()
101
+ if (current) return activeContextEstimateLines(current, props.width)
102
+ return activeContextEstimateMissingLines(props.width)
103
+ }
104
+
105
+ return (
106
+ <box flexDirection="column">
107
+ <For each={lines()}>{(line) => <text>{line}</text>}</For>
108
+ </box>
109
+ )
110
+ }
111
+
112
+ export function UsageHistorySection(props: {
113
+ context: Context
114
+ panel: PanelInput
115
+ width: number
116
+ }): JSX.Element {
117
+ const [period, setPeriod] = createSignal<UsageHistoryRpcPeriod>('7d')
118
+ const [result, setResult] = createSignal<UsageHistoryRpcResult | null>(null)
119
+ const [loading, setLoading] = createSignal(true)
120
+ const [requestFailed, setRequestFailed] = createSignal(false)
121
+ const client = props.context.client.rpc(quotaRpc)
122
+
123
+ const keymap = (): KeymapLayer => ({
124
+ mode: 'global',
125
+ enabled: () => props.panel.focused === true,
126
+ commands: USAGE_HISTORY_PERIOD_BINDINGS.map(({ period: selected, bind, label }) => ({
127
+ id: `pantheon.quota.history.${selected}`,
128
+ title: `Histórico de uso: ${label}`,
129
+ bind,
130
+ run: () => {
131
+ if (props.panel.focused !== true) return false
132
+ setPeriod(selected)
133
+ return undefined
134
+ },
135
+ })),
136
+ })
137
+ props.context.keymap.layer(keymap)
138
+
139
+ createEffect(() => {
140
+ const selectedPeriod = period()
141
+ const controller = new AbortController()
142
+ let current = true
143
+ setLoading(true)
144
+ setRequestFailed(false)
145
+ setResult(null)
146
+
147
+ try {
148
+ void client
149
+ .usage_history(
150
+ { period: selectedPeriod },
151
+ { signal: controller.signal, location: location(props.context) },
152
+ )
153
+ .then((response) => {
154
+ if (!current) return
155
+ if (isUsageHistoryRpcResult(response)) setResult(response)
156
+ else setRequestFailed(true)
157
+ })
158
+ .catch(() => {
159
+ if (current) setRequestFailed(true)
160
+ })
161
+ .finally(() => {
162
+ if (current) setLoading(false)
163
+ })
164
+ } catch {
165
+ setRequestFailed(true)
166
+ setLoading(false)
167
+ }
168
+
169
+ onCleanup(() => {
170
+ current = false
171
+ controller.abort()
172
+ })
173
+ })
174
+
175
+ const chartLines = (): string[] => {
176
+ const current = result()
177
+ return current?.status === 'available' || current?.status === 'partial'
178
+ ? usageHistoryChartLines(current, props.width)
179
+ : []
180
+ }
181
+ const unavailable = (): string | null => {
182
+ const current = result()
183
+ return current ? usageHistoryUnavailableMessage(current) : null
184
+ }
185
+ const available = ():
186
+ | Extract<UsageHistoryRpcResult, { status: 'available' | 'partial' }>
187
+ | undefined => {
188
+ const current = result()
189
+ return current?.status === 'available' || current?.status === 'partial' ? current : undefined
190
+ }
191
+ const warning = (): string[] => {
192
+ const current = result()
193
+ if (current?.status !== 'available' && current?.status !== 'partial') return []
194
+ const message = usageHistoryPartialWarning(current)
195
+ return message ? usageHistoryTextLines(message, props.width) : []
196
+ }
197
+
198
+ return (
199
+ <box flexDirection="column" paddingTop={1}>
200
+ <text attributes={1}>Histórico de uso</text>
201
+ <For each={usageHistorySelectorLines(period(), props.width)}>
202
+ {(line) => <text>{line}</text>}
203
+ </For>
204
+ <For each={usageHistoryControlsLines(props.width)}>{(line) => <text>{line}</text>}</For>
205
+ <Show when={loading()}>
206
+ <text>Carregando histórico…</text>
207
+ </Show>
208
+ <Show when={!loading() && requestFailed()}>
209
+ <For each={usageHistoryTextLines('Falha ao consultar o histórico.', props.width)}>
210
+ {(line) => <text>{line}</text>}
211
+ </For>
212
+ </Show>
213
+ <Show when={!loading() && unavailable()}>
214
+ {(message) => (
215
+ <For each={usageHistoryTextLines(message(), props.width)}>
216
+ {(line) => <text>{line}</text>}
217
+ </For>
218
+ )}
219
+ </Show>
220
+ <Show when={!loading() && !requestFailed() && available()}>
221
+ {(history) => (
222
+ <box flexDirection="column">
223
+ <For each={usageHistoryTextLines(usageHistoryCoverageLabel(history()), props.width)}>
224
+ {(line) => <text>{line}</text>}
225
+ </For>
226
+ <For each={warning()}>{(line) => <text>{line}</text>}</For>
227
+ <For each={usageHistoryTextLines(usageHistoryPricingLabel(history()), props.width)}>
228
+ {(line) => <text>{line}</text>}
229
+ </For>
230
+ <For each={chartLines()}>{(line) => <text>{line}</text>}</For>
231
+ </box>
232
+ )}
233
+ </Show>
234
+ </box>
235
+ )
236
+ }