pantheon-opencode 1.6.1 → 1.6.2-beta.10

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 (169) hide show
  1. package/AGENTS.global.md +11 -11
  2. package/AGENTS.md +2 -2
  3. package/CHANGELOG.md +179 -0
  4. package/README.md +268 -20
  5. package/README.pt-BR.md +34 -11
  6. package/bin/pantheon-init.mjs +301 -32
  7. package/package.json +13 -4
  8. package/plugin.json +1 -1
  9. package/prompts/README.md +58 -0
  10. package/prompts/debug-issue.prompt.md +46 -0
  11. package/prompts/dynamic/agora-generated.txt +38 -0
  12. package/prompts/dynamic/orchestrate-generated.txt +51 -0
  13. package/prompts/focus.prompt.md +42 -0
  14. package/prompts/implement-feature.prompt.md +39 -0
  15. package/prompts/optimize-database.prompt.md +58 -0
  16. package/prompts/orchestrate-with-zeus.prompt.md +441 -0
  17. package/prompts/plan-architecture.prompt.md +59 -0
  18. package/prompts/quick-discovery-large-codebase.prompt.md +294 -0
  19. package/prompts/quick-plan-large-feature.prompt.md +197 -0
  20. package/prompts/semantic-summarize.md +50 -0
  21. package/prompts/sketch.prompt.md +91 -0
  22. package/prompts/subtask.prompt.md +131 -0
  23. package/pyproject.toml +1 -1
  24. package/scripts/build-agents-md.mjs +1 -1
  25. package/scripts/decision-router-budget.mjs +780 -0
  26. package/scripts/decision-router-v2-budget.mjs +218 -0
  27. package/scripts/decision-router-v2-egress.mjs +272 -0
  28. package/scripts/decision-router.mjs +758 -0
  29. package/scripts/docs-check-changelog.mjs +5 -3
  30. package/scripts/doctor.mjs +213 -45
  31. package/scripts/install/agents-md.mjs +2 -1
  32. package/scripts/install/component-selection.mjs +9 -4
  33. package/scripts/install/config-migration.mjs +344 -393
  34. package/scripts/install/config-paths.mjs +15 -0
  35. package/scripts/install/decision-layer-preview.mjs +376 -0
  36. package/scripts/install/decision-router-config.mjs +560 -0
  37. package/scripts/install/health-check.mjs +20 -11
  38. package/scripts/install/interactive.mjs +103 -14
  39. package/scripts/install/interrupt.mjs +4 -3
  40. package/scripts/install/mcp-permissions.mjs +164 -0
  41. package/scripts/install/migrate.mjs +123 -72
  42. package/scripts/install/opencode-version.mjs +31 -13
  43. package/scripts/install/opencode-wildcard.mjs +106 -0
  44. package/scripts/install/opencode.mjs +411 -184
  45. package/scripts/install/plan-artifact.mjs +12 -1
  46. package/scripts/install/plan.mjs +8 -1
  47. package/scripts/install/plugin.mjs +18 -1
  48. package/scripts/install/state.mjs +12 -0
  49. package/scripts/install/strings.mjs +22 -0
  50. package/scripts/install/v2-capabilities.mjs +5 -6
  51. package/scripts/install/venv.mjs +34 -17
  52. package/scripts/mcp_resources.py +11 -9
  53. package/scripts/package-evidence.mjs +1 -0
  54. package/scripts/release-notes.mjs +30 -7
  55. package/scripts/restore.mjs +22 -10
  56. package/scripts/sandbox-env.sh +174 -0
  57. package/scripts/setup-v2-config.mjs +1703 -0
  58. package/scripts/setup.mjs +415 -0
  59. package/scripts/sync-tui.mjs +9 -1
  60. package/scripts/test-opencode-v2-sandbox.sh +448 -157
  61. package/scripts/update-skills-lock.mjs +30 -0
  62. package/scripts/versioning.mjs +41 -5
  63. package/skills-lock.json +10 -10
  64. package/src/agents/aphrodite.md +11 -3
  65. package/src/agents/apollo.md +6 -0
  66. package/src/agents/athena.md +7 -1
  67. package/src/agents/demeter.md +6 -2
  68. package/src/agents/gaia.md +5 -0
  69. package/src/agents/hephaestus.md +7 -2
  70. package/src/agents/hermes.md +14 -13
  71. package/src/agents/iris.md +6 -2
  72. package/src/agents/mnemosyne.md +21 -50
  73. package/src/agents/nyx.md +6 -2
  74. package/src/agents/prometheus.md +5 -1
  75. package/src/agents/talos.md +10 -1
  76. package/src/agents/themis.md +5 -1
  77. package/src/agents/zeus.md +61 -65
  78. package/src/instructions/agent-return-format.instructions.md +1 -1
  79. package/src/instructions/memory-protocol.instructions.md +3 -3
  80. package/src/instructions/test-economy.instructions.md +6 -6
  81. package/src/mcp/eval_store.py +11 -4
  82. package/src/mcp/mcp_resources.py +11 -9
  83. package/src/mcp/memory_mcp.py +293 -150
  84. package/src/mcp/pantheon_vision.py +37 -36
  85. package/src/pantheon/cost-command.ts +30 -133
  86. package/src/pantheon/jev-decision-tool.ts +347 -0
  87. package/src/pantheon/jev-decisions.ts +625 -0
  88. package/src/pantheon/local-decision-agents.ts +170 -0
  89. package/src/pantheon/local-decision-budget.ts +1046 -0
  90. package/src/pantheon/local-decision-egress-gate.ts +144 -0
  91. package/src/pantheon/local-decision-prompt.ts +256 -0
  92. package/src/pantheon/local-decision-provider-matrix.ts +44 -0
  93. package/src/pantheon/local-decision-router.ts +225 -0
  94. package/src/pantheon/local-decision-skills.ts +281 -0
  95. package/src/pantheon/local-decision-tool.ts +160 -0
  96. package/src/pantheon/local-decision-turn.ts +101 -0
  97. package/src/pantheon/local-decision-usage-evidence.internal.ts +168 -0
  98. package/src/pantheon/local-orchestration.ts +322 -0
  99. package/src/pantheon/model-pricing.ts +1 -536
  100. package/src/pantheon/pantheon-decision-catalog.ts +101 -0
  101. package/src/pantheon/v2-decision-budget.ts +456 -0
  102. package/src/pantheon/v2-decision-contracts.ts +300 -0
  103. package/src/pantheon/v2-decision-egress.ts +203 -0
  104. package/src/pantheon/v2-decision-events.ts +180 -0
  105. package/src/pantheon/v2-decision-heuristic.ts +121 -0
  106. package/src/pantheon/v2-decision-points/p1-agent.ts +91 -0
  107. package/src/pantheon/v2-decision-points/p10-claims.ts +243 -0
  108. package/src/pantheon/v2-decision-points/p11-catalog.ts +220 -0
  109. package/src/pantheon/v2-decision-points/p2-skill.ts +83 -0
  110. package/src/pantheon/v2-decision-points/p3-complexity.ts +108 -0
  111. package/src/pantheon/v2-decision-points/p4-memory.ts +137 -0
  112. package/src/pantheon/v2-decision-points/p5-themis-verify.ts +190 -0
  113. package/src/pantheon/v2-decision-points/p6-council.ts +161 -0
  114. package/src/pantheon/v2-decision-points/p7-loop.ts +263 -0
  115. package/src/pantheon/v2-decision-points/p8-guardrail.ts +367 -0
  116. package/src/pantheon/v2-decision-points/p9-memory-compaction.ts +304 -0
  117. package/src/pantheon/v2-decision-points.ts +242 -0
  118. package/src/pantheon/v2-decision-policy.ts +166 -0
  119. package/src/pantheon/v2-decision-premises.ts +146 -0
  120. package/src/pantheon/v2-decision-prompt-surface.ts +115 -0
  121. package/src/pantheon/v2-decision-rank.ts +91 -0
  122. package/src/pantheon/v2-decision-registry.ts +391 -0
  123. package/src/pantheon/v2-decision-resource-ids.ts +127 -0
  124. package/src/pantheon/v2-decision-shadow.ts +123 -0
  125. package/src/pantheon/v2-decision-telemetry.ts +214 -0
  126. package/src/pantheon/v2-decision-verify.ts +51 -0
  127. package/src/pantheon/v2-hook-engine.ts +307 -0
  128. package/src/pantheon/v2-native-decisions.ts +365 -0
  129. package/src/pantheon/v2-shell-hooks.ts +66 -2
  130. package/src/pantheon/v2-tools.ts +38 -15
  131. package/src/pantheon/v2-vision.ts +34 -29
  132. package/src/pantheon/vision.ts +43 -10
  133. package/src/plugin-v2.ts +449 -79
  134. package/src/plugin.ts +4 -0
  135. package/src/plugins/tui/THIRD_PARTY_NOTICES.md +24 -0
  136. package/src/plugins/tui/dist/server-v2.d.ts +22 -0
  137. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -0
  138. package/src/plugins/tui/dist/server-v2.js +26 -0
  139. package/src/plugins/tui/dist/server-v2.js.map +1 -0
  140. package/src/plugins/tui/dist/tui-v2.d.ts +54 -51
  141. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  142. package/src/plugins/tui/dist/tui-v2.js +762 -529
  143. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  144. package/src/plugins/tui/dist/tui.js +1 -1
  145. package/src/plugins/tui/index-v2.ts +3 -6
  146. package/src/plugins/tui/package-lock.json +17 -2
  147. package/src/plugins/tui/package.json +6 -3
  148. package/src/plugins/tui/src/context-gauge.ts +59 -0
  149. package/src/plugins/tui/src/cost-data.ts +607 -0
  150. package/src/plugins/tui/src/index-v2.tsx +360 -242
  151. package/src/plugins/tui/src/model-pricing.ts +536 -0
  152. package/src/plugins/tui/src/model-usage-limits.ts +4 -0
  153. package/src/plugins/tui/src/server-v2.ts +21 -0
  154. package/src/plugins/tui/src/sidebar-width.ts +129 -0
  155. package/src/plugins/tui/tsconfig.typecheck.json +1 -1
  156. package/src/plugins/tui/tsdown.config.ts +34 -5
  157. package/src/routing.yml +72 -13
  158. package/src/skills/README.md +4 -0
  159. package/src/skills/agent-coordination/SKILL.md +0 -3
  160. package/src/skills/artifact-management/SKILL.md +0 -3
  161. package/src/skills/auto-continue/SKILL.md +0 -3
  162. package/src/skills/code-review-checklist/SKILL.md +0 -3
  163. package/src/skills/context-compression/SKILL.md +0 -3
  164. package/src/skills/memory-bank/SKILL.md +6 -28
  165. package/src/skills/session-goal/SKILL.md +0 -3
  166. package/src/skills/simplify/SKILL.md +5 -4
  167. package/src/skills/tdd-with-agents/SKILL.md +0 -3
  168. package/src/skills/visual-review-pipeline/SKILL.md +0 -1
  169. package/src/pantheon/memory-context.ts +0 -1017
@@ -8,8 +8,41 @@ import { homedir } from 'node:os'
8
8
  import { join } from 'node:path'
9
9
  import { Plugin } from '@opencode/plugin/tui'
10
10
  import type { Context, KeymapLayer, PanelInput } from '@opencode/plugin/tui/context'
11
- import type { Accessor } from 'solid-js'
11
+ import type { Accessor, JSX } from 'solid-js'
12
12
  import { createEffect, createMemo, createSignal, For, on, onCleanup, onMount, Show } from 'solid-js'
13
+ import {
14
+ type ContextProgressTone,
15
+ contextBar,
16
+ contextUsageTone,
17
+ formatContextWindow,
18
+ formatSpent,
19
+ formatTokenCount,
20
+ } from './context-gauge'
21
+ import {
22
+ MODEL_USAGE_MESSAGE_LIMIT,
23
+ MODEL_USAGE_SESSION_LIMIT,
24
+ MODEL_USAGE_VISIBLE_CEILING,
25
+ } from './model-usage-limits'
26
+ import { cellWidth, GRAPHEMES, SIDEBAR_CONTENT_WIDTH } from './sidebar-width'
27
+
28
+ export type { ContextProgressTone } from './context-gauge'
29
+ export {
30
+ CONTEXT_BAR_CELLS,
31
+ CONTEXT_BAR_EMPTY_CELL,
32
+ CONTEXT_BAR_FILLED_CELL,
33
+ contextBar,
34
+ contextBarFilled,
35
+ contextUsageTone,
36
+ formatContextWindow,
37
+ formatSpent,
38
+ formatTokenCount,
39
+ } from './context-gauge'
40
+ export {
41
+ MODEL_USAGE_MESSAGE_LIMIT,
42
+ MODEL_USAGE_SESSION_LIMIT,
43
+ MODEL_USAGE_VISIBLE_CEILING,
44
+ } from './model-usage-limits'
45
+ export { cellWidth } from './sidebar-width'
13
46
 
14
47
  const SINGLETON = Symbol.for('pantheon.tui.v2.loaded')
15
48
 
@@ -254,6 +287,184 @@ export function resolveContextLimit(models: readonly any[], ref: unknown): numbe
254
287
  return null
255
288
  }
256
289
 
290
+ /* ─── Active model & context snapshot ─────────────────────
291
+ * `resolveActiveModelRef` and `resolveModelContextSnapshot` (and the private
292
+ * helpers below them) moved here verbatim from the removed `quota-v2-model.ts`
293
+ * when the native quota surface was deleted: the sidebar's Context gauge is
294
+ * their only remaining consumer. They read only host-published transcript and
295
+ * model-catalog data — no RPC and no provider call. They are deliberately
296
+ * distinct from the looser helpers above (`modelRefID`, `resolveContextLimit`,
297
+ * `transcriptWindow`): identity matching here is provider-qualified and the
298
+ * context window excludes messages with no reported usage. */
299
+
300
+ export type ModelContextSnapshot = { tokens: number; percent: number; limit: number }
301
+
302
+ function asRecord(value: unknown): Record<string, unknown> | undefined {
303
+ return typeof value === 'object' && value !== null
304
+ ? (value as Record<string, unknown>)
305
+ : undefined
306
+ }
307
+
308
+ function modelID(ref: unknown): string | null {
309
+ const record = asRecord(ref)
310
+ const id = typeof ref === 'string' ? ref : (record?.id ?? record?.modelID)
311
+ return typeof id === 'string' && id.trim() !== '' ? id : null
312
+ }
313
+
314
+ function messageModelRef(message: Record<string, unknown>): unknown {
315
+ return message.model ?? message
316
+ }
317
+
318
+ function modelProvider(ref: unknown, models: readonly unknown[]): string | null {
319
+ const direct = asRecord(ref)?.providerID
320
+ if (typeof direct === 'string' && direct.trim() !== '') return direct.trim()
321
+ const id = modelID(ref)
322
+ if (id === null) return null
323
+ const segment = id.slice(id.lastIndexOf('/') + 1)
324
+ const providers = new Set<string>()
325
+ for (const candidate of models) {
326
+ const item = asRecord(candidate)
327
+ if (!item) continue
328
+ if (item.id !== id && item.modelID !== id && item.id !== segment && item.modelID !== segment)
329
+ continue
330
+ if (typeof item.providerID === 'string' && item.providerID.trim() !== '') {
331
+ providers.add(item.providerID.trim())
332
+ }
333
+ }
334
+ const explicitProvider = id.includes('/') ? id.slice(0, id.indexOf('/')) : null
335
+ if (explicitProvider && providers.has(explicitProvider)) return explicitProvider
336
+ return providers.size === 1 ? ([...providers][0] ?? null) : null
337
+ }
338
+
339
+ function modelIdentity(
340
+ ref: unknown,
341
+ models: readonly unknown[],
342
+ ): {
343
+ key: string
344
+ id: string
345
+ providerID: string | null
346
+ label: string
347
+ } | null {
348
+ const id = modelID(ref)
349
+ if (id === null) return null
350
+ const providerID = modelProvider(ref, models)
351
+ const segment = id.slice(id.lastIndexOf('/') + 1)
352
+ return {
353
+ key: `${providerID ?? ''}\u0000${id}`,
354
+ id,
355
+ providerID,
356
+ label: segment || id,
357
+ }
358
+ }
359
+
360
+ function tokenCount(message: Record<string, unknown>): number | null {
361
+ const tokens = asRecord(message.tokens)
362
+ if (!tokens) return null
363
+ const cache = asRecord(tokens.cache)
364
+ const values = [tokens.input, tokens.output, tokens.reasoning, cache?.read, cache?.write]
365
+ const reported = values.filter(
366
+ (value): value is number => typeof value === 'number' && Number.isFinite(value) && value >= 0,
367
+ )
368
+ return reported.length === 0 ? null : reported.reduce((sum, value) => sum + value, 0)
369
+ }
370
+
371
+ function contextLimit(ref: unknown, models: readonly unknown[]): number | null {
372
+ const id = modelID(ref)
373
+ if (id === null) return null
374
+ const providerID = modelProvider(ref, models)
375
+ if (providerID === null) return null
376
+ const segment = id.slice(id.lastIndexOf('/') + 1)
377
+ const matches = models.filter((value) => {
378
+ const model = asRecord(value)
379
+ if (!model) return false
380
+ const idMatches =
381
+ model.id === id || model.modelID === id || model.id === segment || model.modelID === segment
382
+ return idMatches && model.providerID === providerID
383
+ })
384
+ const limits = new Set<number>()
385
+ for (const candidate of matches) {
386
+ const limit = asRecord(asRecord(candidate)?.limit)?.context
387
+ if (typeof limit === 'number' && Number.isFinite(limit) && limit > 0) limits.add(limit)
388
+ }
389
+ return limits.size === 1 ? ([...limits][0] ?? null) : null
390
+ }
391
+
392
+ function liveTranscriptWindow(
393
+ messages: readonly unknown[],
394
+ revertMessageID: string | null | undefined,
395
+ ): { start: number; end: number } {
396
+ let end = messages.length
397
+ if (revertMessageID) {
398
+ const boundary = messages.findIndex((message) => asRecord(message)?.id === revertMessageID)
399
+ if (boundary >= 0) end = boundary
400
+ }
401
+ let start = 0
402
+ for (let index = end - 1; index >= 0; index -= 1) {
403
+ if (asRecord(messages[index])?.type === 'compaction') {
404
+ start = index + 1
405
+ break
406
+ }
407
+ }
408
+ return { start, end }
409
+ }
410
+
411
+ function latestContext(
412
+ messages: readonly unknown[],
413
+ modelRef: unknown,
414
+ models: readonly unknown[],
415
+ revertMessageID?: string | null,
416
+ ): ModelContextSnapshot | null {
417
+ const target = modelIdentity(modelRef, models)
418
+ if (target === null || target.providerID === null) return null
419
+ const limit = contextLimit(modelRef, models)
420
+ if (limit === null || limit <= 0) return null
421
+ const { start, end } = liveTranscriptWindow(messages, revertMessageID)
422
+ for (let index = end - 1; index >= start; index -= 1) {
423
+ const message = asRecord(messages[index])
424
+ if (message?.type !== 'assistant') continue
425
+ const identity = modelIdentity(messageModelRef(message), models)
426
+ if (identity?.id !== target.id || identity.providerID !== target.providerID) continue
427
+ const tokens = tokenCount(message)
428
+ if (tokens === null || tokens <= 0) continue
429
+ return { tokens, percent: Math.round((tokens / limit) * 100), limit }
430
+ }
431
+ return null
432
+ }
433
+
434
+ /** Snapshot for one exact model identity in the bounded active transcript. */
435
+ export function resolveModelContextSnapshot(
436
+ messages: readonly unknown[],
437
+ modelRef: unknown,
438
+ models: readonly unknown[],
439
+ revertMessageID?: string | null,
440
+ ): ModelContextSnapshot | null {
441
+ return latestContext(
442
+ messages.slice(-MODEL_USAGE_MESSAGE_LIMIT),
443
+ modelRef,
444
+ models,
445
+ revertMessageID,
446
+ )
447
+ }
448
+
449
+ /** Select the pinned chat model before transcript or configured-agent fallbacks. */
450
+ export function resolveActiveModelRef(
451
+ sessionModel: unknown,
452
+ activeMessages: readonly unknown[],
453
+ fallbackModel: unknown = null,
454
+ ): unknown {
455
+ if (modelID(sessionModel) !== null) return sessionModel
456
+
457
+ const firstMessage = Math.max(0, activeMessages.length - MODEL_USAGE_MESSAGE_LIMIT)
458
+ for (let index = activeMessages.length - 1; index >= firstMessage; index -= 1) {
459
+ const message = asRecord(activeMessages[index])
460
+ if (message?.type !== 'assistant') continue
461
+ const ref = messageModelRef(message)
462
+ if (modelID(ref) !== null) return ref
463
+ }
464
+
465
+ return modelID(fallbackModel) === null ? null : fallbackModel
466
+ }
467
+
257
468
  /** Native token total: input + output + reasoning + cache read + cache write. */
258
469
  export function messageTokensTotal(tokens: any): number {
259
470
  const cacheRead = numberOrNull(tokens?.cache?.read) ?? 0
@@ -320,20 +531,6 @@ export function computeContextUsage(
320
531
  return null
321
532
  }
322
533
 
323
- /** Semantic tone for a context percentage, inclusive at the top of each band:
324
- * info (blue) up to 25%, success (green) up to 50%, warning (yellow) up to
325
- * 90%, error (red) above it. Four explicit stages, each backed by a feedback
326
- * token, so the gauge follows the active theme. Pure. */
327
- export function contextUsageTone(percent: number): ContextProgressTone {
328
- if (percent > 90) return 'error'
329
- if (percent > 50) return 'warning'
330
- if (percent > 25) return 'success'
331
- return 'info'
332
- }
333
-
334
- /** The gauge's four stages, one per theme feedback token. */
335
- export type ContextProgressTone = 'info' | 'success' | 'warning' | 'error'
336
-
337
534
  /** Color for one gauge stage. Filled cells and the percent value both come from
338
535
  * this one call, so the bar and its number can never disagree. `theme` is the
339
536
  * host's resolved theme (loosely typed at runtime); a missing token falls back
@@ -458,67 +655,6 @@ export function turnTokensPerSecond(
458
655
  * are optional; the block renders no line when neither is available. */
459
656
  export type ContextPerformance = { cacheHit: number | null; tokensPerSecond: number | null }
460
657
 
461
- /** Thousands-separated token total: `55320` → `55,320` (en-US, matching the
462
- * native block this one replaces). Null for a missing/invalid value. Pure. */
463
- export function formatTokenCount(tokens: number | null | undefined): string | null {
464
- const value = numberOrNull(tokens)
465
- if (value === null || value < 0) return null
466
- return Math.round(value).toLocaleString('en-US')
467
- }
468
-
469
- /** Context-window label: `1_000_000` → `1.0M`, `200_000` → `200K`,
470
- * `128_000` → `128K`, `32_768` → `32K`. Sub-million limits truncate to whole K
471
- * so the printed window never overstates the model's capacity. Pure. */
472
- export function formatContextWindow(limit: number | null | undefined): string | null {
473
- const value = numberOrNull(limit)
474
- if (value === null || value <= 0) return null
475
- if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`
476
- if (value >= 1_000) return `${Math.floor(value / 1_000)}K`
477
- return `${Math.floor(value)}`
478
- }
479
-
480
- /** Cells in the Context gauge: always rendered in full, so the bar never
481
- * changes width between refreshes. With the space, the percent and the
482
- * `of <window>` tail (at most 9 columns) the line stays inside 34 columns. */
483
- export const CONTEXT_BAR_CELLS = 12
484
- /** Filled cell (U+25B0) and empty cell (U+25B1), both single-width. */
485
- export const CONTEXT_BAR_FILLED_CELL = '\u25B0'
486
- export const CONTEXT_BAR_EMPTY_CELL = '\u25B1'
487
-
488
- /** Filled cells for a percentage: rounded, clamped to `0..cells`, so 0% is an
489
- * empty bar and anything at or above 100% is a full one. Pure. */
490
- export function contextBarFilled(percent: number, cells = CONTEXT_BAR_CELLS): number {
491
- const total = Math.max(1, Math.floor(cells))
492
- const filled = Math.round((percent / 100) * total)
493
- if (!Number.isFinite(filled)) return 0
494
- return Math.min(total, Math.max(0, filled))
495
- }
496
-
497
- /** The gauge split into its toned half (filled cells) and its muted half (empty
498
- * cells), so the caller colors each side. Null when the percentage is missing:
499
- * the Context block then keeps its tokens + cost rows and renders no bar. Pure. */
500
- export function contextBar(
501
- percent: number | null | undefined,
502
- cells = CONTEXT_BAR_CELLS,
503
- ): { filled: string; empty: string } | null {
504
- const value = numberOrNull(percent)
505
- if (value === null) return null
506
- const total = Math.max(1, Math.floor(cells))
507
- const filled = contextBarFilled(value, total)
508
- return {
509
- filled: CONTEXT_BAR_FILLED_CELL.repeat(filled),
510
- empty: CONTEXT_BAR_EMPTY_CELL.repeat(total - filled),
511
- }
512
- }
513
-
514
- /** USD spent with two decimals (`$0.18`), the native block's format. Null for
515
- * a missing/negative value. Pure. */
516
- export function formatSpent(cost: number | null | undefined): string | null {
517
- const value = numberOrNull(cost)
518
- if (value === null || value < 0) return null
519
- return `$${value.toFixed(2)}`
520
- }
521
-
522
658
  /** One rendered context row. `lead` and `tail` carry the gauge bar when the row
523
659
  * has one (`lead` is toned with the value, `tail` is muted), so the 12 cells
524
660
  * stay contiguous while the empty half still reads as background. */
@@ -551,7 +687,7 @@ export function contextBlockRows(
551
687
  const spent: ContextRow | null =
552
688
  spentValue === null
553
689
  ? null
554
- : { lead: null, value: spentValue, tail: null, suffix: ' spent', tone: null }
690
+ : { lead: null, value: spentValue, tail: null, suffix: ' gasto na sessão', tone: null }
555
691
  if (usage === null) return spent === null ? null : { tokens: null, percent: null, spent }
556
692
 
557
693
  const tokensValue = formatTokenCount(usage.tokens)
@@ -586,12 +722,6 @@ export function contextBlockRows(
586
722
  * a message without `cost` contributes 0 and is omitted (never a guessed
587
723
  * price). */
588
724
 
589
- /** Models rendered in the Context block before the aggregate `… +N` line. */
590
- export const MODEL_USAGE_VISIBLE_CEILING = 3
591
- /** Newest messages read per session — bounds the O(n) walk on long sessions. */
592
- export const MODEL_USAGE_MESSAGE_LIMIT = 400
593
- /** Sessions read per family (root + delegations) for the aggregate. */
594
- export const MODEL_USAGE_SESSION_LIMIT = 8
595
725
  /** Column widths for one model row (labels are muted, numbers right-aligned). */
596
726
  export const MODEL_USAGE_MODEL_WIDTH = 12
597
727
  export const MODEL_USAGE_TOKEN_WIDTH = 6
@@ -617,14 +747,14 @@ export function collectModelUsage(messages: readonly any[]): ModelUsage[] {
617
747
  if (id === null || model === null) continue
618
748
  const providerID = typeof message.model?.providerID === 'string' ? message.model.providerID : ''
619
749
  const key = `${providerID}\u0000${id}`
620
- const tokenCount = message.tokens ? messageTokensTotal(message.tokens) : 0
750
+ const tokensTotal = message.tokens ? messageTokensTotal(message.tokens) : 0
621
751
  const cost = numberOrNull(message.cost) ?? 0
622
752
  const current = totals.get(key)
623
753
  if (current) {
624
- current.tokens += Math.max(0, tokenCount)
754
+ current.tokens += Math.max(0, tokensTotal)
625
755
  current.cost += Math.max(0, cost)
626
756
  } else {
627
- totals.set(key, { model, tokens: Math.max(0, tokenCount), cost: Math.max(0, cost) })
757
+ totals.set(key, { model, tokens: Math.max(0, tokensTotal), cost: Math.max(0, cost) })
628
758
  }
629
759
  }
630
760
  return [...totals.values()]
@@ -697,6 +827,68 @@ export function modelUsageRowText(row: ModelUsageRow): string {
697
827
  return `${row.model.padEnd(MODEL_USAGE_MODEL_WIDTH)} ${row.tokens.padStart(MODEL_USAGE_TOKEN_WIDTH)} ${row.cost.padStart(MODEL_USAGE_COST_WIDTH)}`
698
828
  }
699
829
 
830
+ /** Wrap on grapheme boundaries, measuring terminal cells rather than code units.
831
+ * (Body moved verbatim from the removed quota module's `quotaTextLines`.) */
832
+ function wrapTextLines(text: string, width: number, indent: number): string[] {
833
+ const max = Number.isFinite(width) ? Math.max(0, Math.floor(width)) : 0
834
+ if (max < 1) return []
835
+ const padding = ' '.repeat(Math.min(Math.max(0, indent), Math.max(0, max - 2)))
836
+ const lines: string[] = []
837
+ let line = padding
838
+ const segmenter = new Intl.Segmenter()
839
+ for (const word of text.trim().split(/\s+/)) {
840
+ if (!word) continue
841
+ if (line.trim() && cellWidth(line) + 1 + cellWidth(word) > max) {
842
+ lines.push(line.trimEnd())
843
+ line = padding
844
+ }
845
+ if (line.trim()) line += ' '
846
+ for (const { segment } of segmenter.segment(word)) {
847
+ const glyphWidth = cellWidth(segment)
848
+ if (glyphWidth > max) continue
849
+ if (cellWidth(line) + glyphWidth > max) {
850
+ if (line.trim()) lines.push(line.trimEnd())
851
+ line = glyphWidth + cellWidth(padding) <= max ? padding : ''
852
+ }
853
+ line += segment
854
+ }
855
+ }
856
+ if (line.trim()) lines.push(line.trimEnd())
857
+ return lines
858
+ }
859
+
860
+ /** Wrap sidebar text by terminal cells, preserving the complete values. */
861
+ export function sidebarTextLines(value: string): string[] {
862
+ return wrapTextLines(value, SIDEBAR_CONTENT_WIDTH, 0)
863
+ }
864
+
865
+ /** Align a monetary value when it fits, otherwise preserve it on a new line. */
866
+ export function sidebarMoneyLines(label: string, value: string): string[] {
867
+ const gap = SIDEBAR_CONTENT_WIDTH - cellWidth(label) - cellWidth(value)
868
+ return gap >= 1
869
+ ? [`${label}${' '.repeat(gap)}${value}`]
870
+ : [...sidebarTextLines(label), ...sidebarTextLines(value)]
871
+ }
872
+
873
+ /** Keep the existing OpenCode periods together when possible. */
874
+ export function contextSpendLines(value: string): string[] {
875
+ const match = /^(.*\S)\s+(<?\$\S+)$/.exec(value)
876
+ return match?.[1] && match[2] && cellWidth(value) <= SIDEBAR_CONTENT_WIDTH
877
+ ? sidebarMoneyLines(match[1], match[2])
878
+ : sidebarTextLines(value)
879
+ }
880
+
881
+ /** Keep ordinary rows aligned; give oversized values their own lines. */
882
+ export function modelUsageRowLines(row: ModelUsageRow): string[] {
883
+ const single = modelUsageRowText(row)
884
+ if (cellWidth(single) <= SIDEBAR_CONTENT_WIDTH) return [single]
885
+ return [
886
+ ...sidebarTextLines(row.model),
887
+ ...sidebarTextLines(`Tokens ${row.tokens}`),
888
+ ...sidebarTextLines(`USD ${row.cost}`),
889
+ ]
890
+ }
891
+
700
892
  /** Muted aggregate line for the models beyond the cap (`… +2 $0.03`). Null
701
893
  * when every model fits. Pure. */
702
894
  export function hiddenModelUsageText(hidden: number, hiddenCost: number): string | null {
@@ -1172,10 +1364,10 @@ export function statsRangeMatches(
1172
1364
  return sameUnit || asMilliseconds
1173
1365
  }
1174
1366
 
1175
- /** The `Context` block's last line: both spend windows on one muted row
1176
- * (`hoje $0.42 · 30d $9.80`). A window without a usable amount is omitted, and
1177
- * no usable window at all yields null so the line (and not the block) is
1178
- * dropped. Pure. */
1367
+ /** The `Context` block's last line: OpenCode stats source and both spend windows
1368
+ * on one muted row (`OpenCode · hoje $0.42 · 30d $9.80`). A window without a
1369
+ * usable amount is omitted, and no usable window at all yields null so the
1370
+ * line (and not the block) is dropped. Pure. */
1179
1371
  export function contextSpendLine(totals: SpendTotals | null): string | null {
1180
1372
  if (totals === null) return null
1181
1373
  const parts: string[] = []
@@ -1183,138 +1375,13 @@ export function contextSpendLine(totals: SpendTotals | null): string | null {
1183
1375
  if (today !== null) parts.push(`${SPEND_TODAY_LABEL} ${today}`)
1184
1376
  const thirtyDays = formatSpendUSD(totals.thirtyDays)
1185
1377
  if (thirtyDays !== null) parts.push(`${SPEND_30D_LABEL} ${thirtyDays}`)
1186
- return parts.length === 0 ? null : parts.join(SPEND_LINE_SEPARATOR)
1378
+ return parts.length === 0
1379
+ ? null
1380
+ : `OpenCode${SPEND_LINE_SEPARATOR}${parts.join(SPEND_LINE_SEPARATOR)}`
1187
1381
  }
1188
1382
 
1189
1383
  /** Grapheme iterator: a cut never splits a surrogate pair, a combining mark
1190
1384
  * from its base or a ZWJ emoji sequence, so truncation stays cell-exact. */
1191
- const GRAPHEMES = new Intl.Segmenter(undefined, { granularity: 'grapheme' })
1192
-
1193
- /** A grapheme the host draws two cells wide: emoji presentation, an extended
1194
- * pictograph (a bare `❤` counts too, exactly as the host's `emoji-regex`
1195
- * does) and a regional-indicator pair (a flag). */
1196
- const EMOJI_GLYPH = /\p{Emoji_Presentation}|\p{Extended_Pictographic}|\p{Regional_Indicator}/u
1197
- /** VS16 asks for emoji presentation; without it `1` is one cell, with it the
1198
- * keycap sequence is drawn as one two-cell glyph. */
1199
- const EMOJI_PRESENTATION_SELECTOR = '\uFE0F'
1200
- /** Unicode default-ignorable code points carry no width of their own. */
1201
- const IGNORABLE_GLYPH = /^\p{Default_Ignorable_Code_Point}$/u
1202
- /** East Asian Wide/Fullwidth ranges — two cells, never the ambiguous width
1203
- * (the host measures ambiguous as narrow, so `▸`/`✓`/`—` stay one cell).
1204
- * Generated from the host's own measurement (`string-width` over every code
1205
- * point, emoji excluded), so this table can be regenerated verbatim when the
1206
- * host upgrades its Unicode data instead of being hand-edited. */
1207
- const CELL_WIDE_RANGES: readonly (readonly [number, number])[] = [
1208
- [0x1100, 0x115e],
1209
- [0x2329, 0x232a],
1210
- [0x2630, 0x2637],
1211
- [0x268a, 0x268f],
1212
- [0x2e80, 0x2e99],
1213
- [0x2e9b, 0x2ef3],
1214
- [0x2f00, 0x2fd5],
1215
- [0x2ff0, 0x302f],
1216
- [0x3031, 0x303c],
1217
- [0x303e, 0x303e],
1218
- [0x3041, 0x3096],
1219
- [0x3099, 0x30ff],
1220
- [0x3105, 0x312f],
1221
- [0x3131, 0x3163],
1222
- [0x3165, 0x318e],
1223
- [0x3190, 0x31e5],
1224
- [0x31ef, 0x321e],
1225
- [0x3220, 0x3247],
1226
- [0x3250, 0x3296],
1227
- [0x3298, 0x3298],
1228
- [0x329a, 0xa48c],
1229
- [0xa490, 0xa4c6],
1230
- [0xa960, 0xa97c],
1231
- [0xac00, 0xd7a3],
1232
- [0xf900, 0xfaff],
1233
- [0xfe10, 0xfe19],
1234
- [0xfe30, 0xfe52],
1235
- [0xfe54, 0xfe66],
1236
- [0xfe68, 0xfe6b],
1237
- [0xff01, 0xff60],
1238
- [0xffe0, 0xffe6],
1239
- [0x16fe0, 0x16fe4],
1240
- [0x16ff0, 0x16ff6],
1241
- [0x17000, 0x18cda],
1242
- [0x18cff, 0x18d20],
1243
- [0x18d80, 0x18df2],
1244
- [0x18e00, 0x19191],
1245
- [0x191a0, 0x191d2],
1246
- [0x1aff0, 0x1aff3],
1247
- [0x1aff5, 0x1affb],
1248
- [0x1affd, 0x1affe],
1249
- [0x1b000, 0x1b128],
1250
- [0x1b132, 0x1b132],
1251
- [0x1b150, 0x1b152],
1252
- [0x1b155, 0x1b155],
1253
- [0x1b164, 0x1b168],
1254
- [0x1b170, 0x1b2fb],
1255
- [0x1d300, 0x1d356],
1256
- [0x1d360, 0x1d376],
1257
- [0x1f200, 0x1f200],
1258
- [0x1f210, 0x1f219],
1259
- [0x1f21b, 0x1f22e],
1260
- [0x1f230, 0x1f231],
1261
- [0x1f23b, 0x1f23b],
1262
- [0x1f240, 0x1f248],
1263
- [0x1f260, 0x1f265],
1264
- [0x20000, 0x2fffd],
1265
- [0x30000, 0x3fffd],
1266
- ]
1267
-
1268
- /** One code point the terminal draws no cell for: control characters, the
1269
- * zero-width joiners/marks, combining marks and variation selectors. */
1270
- function isZeroWidthCodePoint(code: number, glyph: string): boolean {
1271
- if (code <= 0x1f || (code >= 0x7f && code <= 0x9f)) return true
1272
- if (code >= 0x200b && code <= 0x200f) return true
1273
- if (code === 0xfeff) return true
1274
- if (code >= 0x300 && code <= 0x36f) return true
1275
- if (code >= 0x1ab0 && code <= 0x1aff) return true
1276
- if (code >= 0x1dc0 && code <= 0x1dff) return true
1277
- if (code >= 0x20d0 && code <= 0x20ff) return true
1278
- if (code >= 0xfe00 && code <= 0xfe0f) return true
1279
- if (code >= 0xfe20 && code <= 0xfe2f) return true
1280
- if (code >= 0xe0100 && code <= 0xe01ef) return true
1281
- if (code >= 0xd800 && code <= 0xdfff) return true // a lone surrogate
1282
- return IGNORABLE_GLYPH.test(glyph)
1283
- }
1284
-
1285
- function isWideCodePoint(code: number): boolean {
1286
- for (const [low, high] of CELL_WIDE_RANGES) {
1287
- if (code < low) return false
1288
- if (code <= high) return true
1289
- }
1290
- return false
1291
- }
1292
-
1293
- /** Cells one grapheme occupies. */
1294
- function graphemeWidth(segment: string): number {
1295
- if (EMOJI_GLYPH.test(segment)) return 2
1296
- // A lone VS16 carries no width; after a base it asks for emoji presentation.
1297
- if (segment.length > 1 && segment.includes(EMOJI_PRESENTATION_SELECTOR)) return 2
1298
- let width = 0
1299
- for (const glyph of segment) {
1300
- const code = glyph.codePointAt(0) ?? 0
1301
- if (isZeroWidthCodePoint(code, glyph)) continue
1302
- width += isWideCodePoint(code) ? 2 : 1
1303
- }
1304
- return width
1305
- }
1306
-
1307
- /** Terminal cells `value` occupies — the unit every column in this plugin is
1308
- * measured in. Mirrors the host (that is how `@opentui/core` sizes a text
1309
- * run): emoji count as two cells, East Asian Wide/Fullwidth as two, East
1310
- * Asian Ambiguous as one, combining marks and variation selectors as none.
1311
- * Pure. */
1312
- export function cellWidth(value: string): number {
1313
- let width = 0
1314
- for (const { segment } of GRAPHEMES.segment(value)) width += graphemeWidth(segment)
1315
- return width
1316
- }
1317
-
1318
1385
  /** Clamp a free-form label to `max` terminal cells without wrapping. The width
1319
1386
  * is measured in display cells, never in UTF-16 code units: a CJK or emoji
1320
1387
  * label used to overflow the column it was cut for (`計画の移行` is 5 code
@@ -1347,7 +1414,7 @@ export function padCell(value: string, cells: number): string {
1347
1414
  }
1348
1415
 
1349
1416
  /** Columns the fixed header may use before it would wrap the sidebar. */
1350
- export const HEADER_MAX_WIDTH = 34
1417
+ export const HEADER_MAX_WIDTH = SIDEBAR_CONTENT_WIDTH
1351
1418
 
1352
1419
  /** Preset row of the fixed header: `▸ <preset> · <provider>`. The provider is
1353
1420
  * cut first when the row overflows, so the preset name is never the casualty;
@@ -3595,21 +3662,19 @@ export function createSidebarModel(
3595
3662
  })
3596
3663
 
3597
3664
  const contextUsage = createMemo(() => {
3598
- const list = messages()
3665
+ const list = messages().slice(-MODEL_USAGE_MESSAGE_LIMIT)
3599
3666
  if (list.length === 0) return null
3600
3667
  const refs = modelRefs()
3601
- const lastAssistant = [...list]
3602
- .reverse()
3603
- .find((message) => message?.type === 'assistant' && message?.model)
3604
- const ref = lastAssistant?.model ?? refs.sessionRef ?? refs.agentRef ?? refs.override
3605
- let limit: number | null = null
3668
+ const ref = resolveActiveModelRef(refs.sessionRef, list, refs.agentRef)
3669
+ if (ref === null) return null
3670
+ let models: unknown[] = []
3606
3671
  try {
3607
- const models = context.data.location?.model?.list?.(location)
3608
- limit = resolveContextLimit(Array.isArray(models) ? models : [], ref)
3672
+ const result = context.data.location?.model?.list?.(location)
3673
+ if (Array.isArray(result)) models = result
3609
3674
  } catch {
3610
- limit = null
3675
+ /* Unknown model limits suppress only the context gauge. */
3611
3676
  }
3612
- return computeContextUsage(list, limit, session()?.revert?.messageID)
3677
+ return resolveModelContextSnapshot(list, ref, models, session()?.revert?.messageID)
3613
3678
  })
3614
3679
 
3615
3680
  // Telemetry that rides on the messages already in hand — no extra request.
@@ -3795,13 +3860,41 @@ export function createSidebarModel(
3795
3860
  * cells), the value, the muted gauge tail (empty cells) and the muted unit
3796
3861
  * suffix (`tokens` / `of 200K` / `spent`). */
3797
3862
  function ContextRowView(props: { row: ContextRow; fg: string; muted: string }) {
3863
+ const fullWidth = () =>
3864
+ cellWidth(
3865
+ `${props.row.lead ?? ''}${props.row.tail ?? ''}${props.row.value}${props.row.suffix ?? ''}`,
3866
+ )
3798
3867
  return (
3799
- <box flexDirection="row">
3800
- <Show when={props.row.lead}>{(lead) => <text fg={props.fg}>{lead()}</text>}</Show>
3801
- <Show when={props.row.tail}>{(tail) => <text fg={props.muted}>{tail()}</text>}</Show>
3802
- <text fg={props.fg}>{props.row.value}</text>
3803
- <Show when={props.row.suffix}>{(suffix) => <text fg={props.muted}>{suffix()}</text>}</Show>
3804
- </box>
3868
+ <Show
3869
+ when={props.row.suffix !== ' gasto na sessão'}
3870
+ fallback={
3871
+ <box flexDirection="column">
3872
+ <For each={sidebarMoneyLines('gasto na sessão', props.row.value)}>
3873
+ {(line) => <text fg={props.fg}>{line}</text>}
3874
+ </For>
3875
+ </box>
3876
+ }
3877
+ >
3878
+ <Show
3879
+ when={fullWidth() <= SIDEBAR_CONTENT_WIDTH}
3880
+ fallback={
3881
+ <box flexDirection="column">
3882
+ <For each={sidebarTextLines(`${props.row.value.trim()}${props.row.suffix ?? ''}`)}>
3883
+ {(line) => <text fg={props.fg}>{line}</text>}
3884
+ </For>
3885
+ </box>
3886
+ }
3887
+ >
3888
+ <box flexDirection="row">
3889
+ <Show when={props.row.lead}>{(lead) => <text fg={props.fg}>{lead()}</text>}</Show>
3890
+ <Show when={props.row.tail}>{(tail) => <text fg={props.muted}>{tail()}</text>}</Show>
3891
+ <text fg={props.fg}>{props.row.value}</text>
3892
+ <Show when={props.row.suffix}>
3893
+ {(suffix) => <text fg={props.muted}>{suffix()}</text>}
3894
+ </Show>
3895
+ </box>
3896
+ </Show>
3897
+ </Show>
3805
3898
  )
3806
3899
  }
3807
3900
 
@@ -3829,7 +3922,12 @@ function BlockHeader(props: {
3829
3922
  )
3830
3923
  }
3831
3924
 
3832
- function Sidebar(props: { context: any; sessionID?: string }) {
3925
+ interface SidebarProps {
3926
+ context: Context
3927
+ sessionID?: string
3928
+ }
3929
+
3930
+ function Sidebar(props: SidebarProps): JSX.Element {
3833
3931
  const { context } = props
3834
3932
  const model = createSidebarModel(context, () => props.sessionID)
3835
3933
  const text = () => context.theme.text?.base
@@ -3915,16 +4013,30 @@ function Sidebar(props: { context: any; sessionID?: string }) {
3915
4013
  numbers right-aligned; the gauge above remains the block's
3916
4014
  single accent. When no message carries cost this loop is empty
3917
4015
  and the block keeps its original token/spend rows. */}
4016
+ <Show when={usageRows().length > 0}>
4017
+ <text fg={muted()}>Sessão · custo reportado</text>
4018
+ <text fg={muted()}>
4019
+ {'Modelo'.padEnd(MODEL_USAGE_MODEL_WIDTH) +
4020
+ ' Tokens'.padStart(8) +
4021
+ ' USD'.padStart(10)}
4022
+ </text>
4023
+ </Show>
3918
4024
  <For each={usageRows()}>
3919
4025
  {(row: ModelUsageRow) => (
3920
- <box flexDirection="row">
3921
- <text fg={muted()}>{row.model.padEnd(MODEL_USAGE_MODEL_WIDTH)}</text>
3922
- <text fg={text()}>{` ${row.tokens.padStart(MODEL_USAGE_TOKEN_WIDTH)}`}</text>
3923
- <text fg={text()}>{` ${row.cost.padStart(MODEL_USAGE_COST_WIDTH)}`}</text>
4026
+ <box flexDirection="column">
4027
+ <For each={modelUsageRowLines(row)}>
4028
+ {(line) => <text fg={text()}>{line}</text>}
4029
+ </For>
3924
4030
  </box>
3925
4031
  )}
3926
4032
  </For>
3927
- <Show when={usageHidden()}>{(line) => <text fg={muted()}>{line()}</text>}</Show>
4033
+ <Show when={usageHidden()}>
4034
+ {(line) => (
4035
+ <For each={sidebarTextLines(line())}>
4036
+ {(part) => <text fg={muted()}>{part}</text>}
4037
+ </For>
4038
+ )}
4039
+ </Show>
3928
4040
  </box>
3929
4041
  )}
3930
4042
  </Show>
@@ -3934,7 +4046,13 @@ function Sidebar(props: { context: any; sessionID?: string }) {
3934
4046
  <Show when={performanceLine()}>{(line) => <text fg={muted()}>{line()}</text>}</Show>
3935
4047
  {/* Spend, not budget: two local windows on one muted line. Absent
3936
4048
  whenever stats is missing or the from/to unit probe failed. */}
3937
- <Show when={spendLine()}>{(line) => <text fg={muted()}>{line()}</text>}</Show>
4049
+ <Show when={spendLine()}>
4050
+ {(line) => (
4051
+ <For each={contextSpendLines(line())}>
4052
+ {(part) => <text fg={muted()}>{part}</text>}
4053
+ </For>
4054
+ )}
4055
+ </Show>
3938
4056
  </box>
3939
4057
  </Show>
3940
4058