Skip to content

Open source AI coding agent. Designed for large projects and real world tasks.

usage summary command: 'usage' and 'usage --log'. repl fix

Dane Schneider60c858fdffb2
diff --git a/app/cli/cmd/credits.go b/app/cli/cmd/credits.go
deleted file mode 100644
index ea41d5f6..00000000
--- a/app/cli/cmd/credits.go
+++ /dev/null
@@ -1,58 +0,0 @@
-package cmd
-
-import (
- "fmt"
- "os"
- "plandex-cli/api"
- "plandex-cli/auth"
- "plandex-cli/term"
- "strings"
-
- "github.com/olekukonko/tablewriter"
- "github.com/spf13/cobra"
-)
-
-var creditsCmd = &cobra.Command{
- Use: "credits",
- Short: "Display the current credit balance if using integrated models mode",
- Run: credits,
-}
-
-func init() {
- RootCmd.AddCommand(creditsCmd)
-}
-
-func credits(cmd *cobra.Command, args []string) {
- auth.MustResolveAuthWithOrg()
-
- term.StartSpinner("")
- org, apiErr := api.Client.GetOrgSession()
- term.StopSpinner()
-
- if apiErr != nil {
- term.OutputErrorAndExit("Error getting org session: %v", apiErr)
- return
- }
-
- if !org.IntegratedModelsMode {
- fmt.Println("The org isn't using integrated models mode.")
- return
- }
-
- balance := org.CloudBillingFields.CreditsBalance
- balanceStr := fmt.Sprintf("$%s", balance.StringFixed(4))
-
- for i := 0; i < 2; i++ {
- if strings.HasSuffix(balanceStr, "0") {
- balanceStr = balanceStr[:len(balanceStr)-1]
- }
- }
-
- table := tablewriter.NewWriter(os.Stdout)
- table.SetHeader([]string{"Credits Balance"})
- table.Append([]string{balanceStr})
- table.Render()
-
- fmt.Println()
- term.PrintCmds("", "usage", "billing")
-}
diff --git a/app/cli/cmd/credits_log.go b/app/cli/cmd/credits_log.go
deleted file mode 100644
index fe48b4cc..00000000
--- a/app/cli/cmd/credits_log.go
+++ /dev/null
@@ -1,272 +0,0 @@
-package cmd
-
-import (
- "fmt"
- "plandex-cli/api"
- "plandex-cli/auth"
- "plandex-cli/term"
- "strconv"
- "strings"
- "unicode"
-
- shared "plandex-shared"
-
- "github.com/eiannone/keyboard"
- "github.com/fatih/color"
- "github.com/olekukonko/tablewriter"
- "github.com/shopspring/decimal"
- "github.com/spf13/cobra"
-)
-
-const MaxCreditsLogPageSize = 500
-
-var logCreditsPageSize int
-var logCreditsPage int
-
-var usageCmd = &cobra.Command{
- Use: "usage",
- Short: "Display the credits transactions log",
- Run: creditsLog,
-}
-
-func init() {
- usageCmd.Flags().IntVarP(&logCreditsPageSize, "page-size", "s", 100, "Number of transactions to display per page")
- usageCmd.Flags().IntVarP(&logCreditsPage, "page", "p", 1, "Page number to display")
-
- RootCmd.AddCommand(usageCmd)
-}
-
-func creditsLog(cmd *cobra.Command, args []string) {
- auth.MustResolveAuthWithOrg()
-
- term.StartSpinner("")
- res, apiErr := api.Client.GetCreditsTransactions(logCreditsPageSize, logCreditsPage)
- term.StopSpinner()
-
- if apiErr != nil {
- term.OutputErrorAndExit("Error getting credits transactions: %v", apiErr)
- return
- }
-
- transactions := res.Transactions
-
- tableString := &strings.Builder{}
- table := tablewriter.NewWriter(tableString)
- table.SetAutoWrapText(false)
- table.SetHeader([]string{"Amount", "Balance", "Transaction"})
-
- for _, transaction := range transactions {
- var sign string
- var c color.Attribute
-
- desc := transaction.CreatedAt.Local().Format("2006-01-02 15:04:05.000 EST") + "\n"
-
- if transaction.TransactionType == "debit" {
- sign = "-"
- c = term.ColorHiRed
-
- if transaction.DebitPlanName != nil {
- desc += fmt.Sprintf("Plan → %s\n", *transaction.DebitPlanName)
- }
-
- surchargePct := transaction.DebitSurcharge.Div(*transaction.DebitBaseAmount)
-
- inputPrice := transaction.DebitModelInputPricePerToken.Mul(decimal.NewFromInt(1000000)).Mul(surchargePct.Add(decimal.NewFromInt(1))).StringFixed(4)
- outputPrice := transaction.DebitModelOutputPricePerToken.Mul(decimal.NewFromInt(1000000)).Mul(surchargePct.Add(decimal.NewFromInt(1))).StringFixed(4)
-
- var cacheDiscountStr string
- var cacheDiscountPct float64
- if transaction.DebitCacheDiscount != nil {
- cacheDiscountStr = transaction.DebitCacheDiscount.StringFixed(4)
- totalAmount := transaction.DebitBaseAmount.Add(*transaction.DebitCacheDiscount)
- cacheDiscountPct = transaction.DebitCacheDiscount.Div(totalAmount).Mul(decimal.NewFromInt(100)).InexactFloat64()
- }
-
- for i := 0; i < 2; i++ {
- inputPrice = strings.TrimSuffix(inputPrice, "0")
- outputPrice = strings.TrimSuffix(outputPrice, "0")
- cacheDiscountStr = strings.TrimSuffix(cacheDiscountStr, "0")
- }
-
- desc += fmt.Sprintf("⚡️ %s\n", *transaction.DebitPurpose)
- desc += fmt.Sprintf("🧠 %s/%s\n", string(*transaction.DebitModelProvider), *transaction.DebitModelName)
- desc += fmt.Sprintf("💳 Price → $%s input / $%s output per 1M\n", inputPrice, outputPrice)
- desc += fmt.Sprintf("🪙 Used → %d input / %d output\n", *transaction.DebitInputTokens, *transaction.DebitOutputTokens)
-
- if cacheDiscountStr != "" {
- desc += fmt.Sprintf("🎯 Cache discount → $%s (%d%%)\n", cacheDiscountStr, int(cacheDiscountPct))
- }
-
- } else {
- sign = "+"
- c = term.ColorHiGreen
-
- switch *transaction.CreditType {
- case shared.CreditTypeGrant:
- desc += "Monthly subscription payment"
- case shared.CreditTypeTrial:
- desc += "Started trial"
- case shared.CreditTypePurchase:
- desc += "Purchased credits"
- case shared.CreditTypeSwitch:
- desc += "Switched to Integrated Models mode"
- }
-
- desc += "\n"
- }
-
- amountStr := transaction.Amount.StringFixed(6)
- for i := 0; i < 4; i++ {
- amountStr = strings.TrimSuffix(amountStr, "0")
- }
-
- balanceStr := transaction.EndBalance.StringFixed(4)
- for i := 0; i < 2; i++ {
- balanceStr = strings.TrimSuffix(balanceStr, "0")
- }
-
- table.Append([]string{
- color.New(c).Sprint(sign + "$" + amountStr),
- "$" + balanceStr,
-
- desc,
- })
- }
-
- table.Render()
-
- var output string
- var pageLine string
-
- if res.NumPages > 1 {
- pageLine = fmt.Sprintf("Page size %d. Showing page %d of %d", logCreditsPageSize, logCreditsPage, res.NumPages)
- if res.NumPagesMax {
- pageLine = "+"
- }
- output = pageLine + "\n\n" + tableString.String()
- } else {
- output = tableString.String()
- }
-
- term.PageOutput(output)
-
- var inputFn func()
- inputFn = func() {
- fmt.Println("\n" + pageLine)
-
- prompts := []string{}
-
- if res.NumPages > 1 && logCreditsPage < res.NumPages {
- prompts = append(prompts, "Press 'n' for next page")
- }
-
- if logCreditsPage > 1 {
- prompts = append(prompts, "Press 'p' for previous page")
- }
-
- prompts = append(prompts, "Type any number and press enter to jump to a page")
-
- prompts = append(prompts, "Press 'q' to quit")
-
- color.New(term.ColorHiMagenta, color.Bold).Println(strings.Join(prompts, "\n"))
- color.New(term.ColorHiMagenta, color.Bold).Print("> ")
-
- char, _, err := term.GetUserKeyInput()
-
- if err != nil {
- term.OutputErrorAndExit("Failed to get user input: %v", err)
- }
-
- // Check if the input is a digit
- if unicode.IsDigit(char) {
- var numberInput strings.Builder
- numberInput.WriteRune(char)
-
- fmt.Print(string(char)) // Show the initial digit
-
- for {
- char, key, err := term.GetUserKeyInput()
- if err != nil {
- term.OutputErrorAndExit("Failed to get user input: %v", err)
- }
-
- // If Enter is pressed, commit the input
- if key == keyboard.KeyEnter {
- pageNumber, err := strconv.Atoi(numberInput.String())
- if err != nil {
- fmt.Println("Invalid page number.")
- return
- }
-
- // Check if the page number is valid
- if pageNumber >= 1 && (pageNumber <= res.NumPages || res.NumPagesMax) {
- logCreditsPage = pageNumber
- creditsLog(cmd, args) // Re-run the log command with the new page
- } else {
- fmt.Println()
- fmt.Println("Invalid page number.")
- inputFn()
- }
- return
- }
-
- // If another digit is pressed, add it to the input
- if unicode.IsDigit(char) {
- numberInput.WriteRune(char)
- fmt.Print(string(char)) // Show the digit
- } else if key == keyboard.KeyBackspace || key == keyboard.KeyBackspace2 {
- // Handle backspace
- if numberInput.Len() > 0 {
- // Remove the last rune
- input := numberInput.String()
- numberInput.Reset()
- numberInput.WriteString(input[:len(input)-1])
- fmt.Print("\b \b") // Erase the digit
- }
-
- } else {
- // Handle invalid input while typing a number
- fmt.Println()
- fmt.Println("\nInvalid input. Please enter a valid page number.")
- inputFn()
- return
- }
- }
- }
-
- // Handle non-digit hotkeys
- fmt.Print(string(char))
- switch char {
- case 'n':
- if logCreditsPage < res.NumPages || res.NumPagesMax {
- logCreditsPage++
- creditsLog(cmd, args)
- } else {
- fmt.Println()
- fmt.Println("Already on last page.")
- inputFn()
- }
- case 'p':
- if logCreditsPage > 1 {
- logCreditsPage--
- creditsLog(cmd, args)
- } else {
- fmt.Println()
- fmt.Println("Already on first page.")
- inputFn()
- }
- case 'q':
- fmt.Println()
- return
- default:
- fmt.Println()
- fmt.Println("Invalid input.")
- inputFn()
- }
-
- }
-
- if res.NumPages > 1 {
- inputFn()
- }
-}
diff --git a/app/cli/cmd/load.go b/app/cli/cmd/load.go
index 2a9748ac..da212a2e 100644
--- a/app/cli/cmd/load.go
+++ b/app/cli/cmd/load.go
@@ -2,6 +2,7 @@ package cmd
import (
"fmt"
+ "os"
"plandex-cli/auth"
"plandex-cli/lib"
"plandex-cli/term"
@@ -54,6 +55,7 @@ func contextLoad(cmd *cobra.Command, args []string) {
ForceSkipIgnore: forceSkipIgnore,
ImageDetail: openai.ImageURLDetail(imageDetail),
DefsOnly: defsOnly,
+ SessionId: os.Getenv("PLANDEX_REPL_SESSION_ID"),
})
fmt.Println()
diff --git a/app/cli/cmd/plan_start_helpers.go b/app/cli/cmd/plan_start_helpers.go
index 0d3cb27a..a90fd553 100644
--- a/app/cli/cmd/plan_start_helpers.go
+++ b/app/cli/cmd/plan_start_helpers.go
@@ -1,13 +1,14 @@
package cmd
import (
- "fmt"
+ "os"
"plandex-cli/api"
"plandex-cli/lib"
"plandex-cli/term"
shared "plandex-shared"
"github.com/fatih/color"
+ "github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
)
@@ -82,7 +83,7 @@ func resolveAutoModeWithArgs(config *shared.PlanConfig, silent bool) (bool, *sha
}
fn := func() {
- fmt.Printf("🚀 Set %s to %s\n", color.New(color.Bold).Sprint("auto-mode"), color.New(color.Bold, term.ColorHiMagenta).Sprint(toSetAutoMode))
+ printAutoModeTable(config)
}
if !silent {
@@ -152,7 +153,7 @@ func resolveModelPackWithArgs(settings *shared.PlanSettings, silent bool) (*shar
}
fn := func() {
- fmt.Printf("🧠 Set model pack to %s\n", color.New(color.Bold, term.ColorHiMagenta).Sprint(packName))
+ printModelPackTable(packName)
}
if !silent {
@@ -166,7 +167,7 @@ func resolveModelPackWithArgs(settings *shared.PlanSettings, silent bool) (*shar
term.StopSpinner()
}
fn := func() {
- fmt.Printf("🧠 Using model pack %s\n", color.New(color.Bold, term.ColorHiMagenta).Sprint(packName))
+ printModelPackTable(packName)
}
if !silent {
@@ -177,3 +178,63 @@ func resolveModelPackWithArgs(settings *shared.PlanSettings, silent bool) (*shar
return originalSettings, fn
}
}
+
+func printModelPackTable(packName string) {
+ table := tablewriter.NewWriter(os.Stdout)
+ table.SetHeader([]string{"🧠 Model Pack"})
+ table.Append([]string{color.New(color.Bold, term.ColorHiMagenta).Sprint(packName)})
+ table.Render()
+}
+
+func printAutoModeTable(config *shared.PlanConfig) {
+ var contextMode string
+ if config.AutoLoadContext {
+ contextMode = "auto"
+ } else {
+ contextMode = "manual"
+ }
+
+ var applyMode string
+ if config.AutoApply {
+ applyMode = "auto"
+ } else {
+ applyMode = "approve"
+ }
+
+ var executionMode string
+ if config.AutoExec {
+ executionMode = "auto"
+ } else if config.CanExec {
+ executionMode = "approve"
+ } else {
+ executionMode = "disabled"
+ }
+
+ var commitMode string
+ if config.AutoCommit {
+ commitMode = "auto"
+ } else if config.SkipCommit {
+ commitMode = "skip"
+ } else {
+ commitMode = "manual"
+ }
+
+ table := tablewriter.NewWriter(os.Stdout)
+ table.SetAutoWrapText(false)
+ table.SetHeader([]string{
+ "🚀 Auto Mode",
+ "Context",
+ "Apply",
+ "Execution",
+ "Commits",
+ })
+ table.Append([]string{
+ color.New(color.Bold, term.ColorHiMagenta).Sprint(config.AutoMode),
+ contextMode,
+ applyMode,
+ executionMode,
+ commitMode,
+ })
+ table.Render()
+
+}
diff --git a/app/cli/cmd/repl.go b/app/cli/cmd/repl.go
index 9afedded..6ae65c8c 100644
--- a/app/cli/cmd/repl.go
+++ b/app/cli/cmd/repl.go
@@ -2,6 +2,7 @@ package cmd
import (
"fmt"
+ "log"
"os"
"path/filepath"
"plandex-cli/api"
@@ -18,6 +19,7 @@ import (
"unicode"
"github.com/fatih/color"
+ "github.com/google/uuid"
"github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
@@ -37,6 +39,8 @@ var currentPrompt *prompt.Prompt
var replConfig *shared.PlanConfig
+var sessionId string
+
func init() {
RootCmd.AddCommand(replCmd)
@@ -65,6 +69,9 @@ func setReplConfig() {
}
func runRepl(cmd *cobra.Command, args []string) {
+ sessionId = uuid.New().String()
+ log.Println("sessionId", sessionId)
+
term.SetIsRepl(true)
auth.MustResolveAuthWithOrg()
lib.MustResolveOrCreateProject()
@@ -314,7 +321,9 @@ func executor(in string, p *prompt.Prompt) {
parts := strings.Fields(lastLine)
if len(parts) > 1 {
args := parts[1:] // Skip the "plandex" or "pdx" command
- _, err := lib.ExecPlandexCommand(args)
+ _, err := lib.ExecPlandexCommandWithParams(args, lib.ExecPlandexCommandParams{
+ SessionId: sessionId,
+ })
if err != nil {
color.New(term.ColorHiRed).Printf("Error executing command: %v\n", err)
}
@@ -362,7 +371,12 @@ func executor(in string, p *prompt.Prompt) {
args = append(args, filteredPaths...)
args = append(args, "-r")
fmt.Println()
- lib.ExecPlandexCommand(args)
+ _, err := lib.ExecPlandexCommandWithParams(args, lib.ExecPlandexCommandParams{
+ SessionId: sessionId,
+ })
+ if err != nil {
+ color.New(term.ColorHiRed).Printf("Error executing command: %v\n", err)
+ }
fmt.Println()
if preservedBuffer != "" {
p.InsertTextMoveCursor(preservedBuffer, true)
@@ -494,7 +508,9 @@ func executor(in string, p *prompt.Prompt) {
execArgs = append(execArgs, "--chat")
}
execArgs = append(execArgs, args...)
- _, err := lib.ExecPlandexCommand(execArgs)
+ _, err := lib.ExecPlandexCommandWithParams(execArgs, lib.ExecPlandexCommandParams{
+ SessionId: sessionId,
+ })
if err != nil {
color.New(term.ColorHiRed).Printf("Error executing command: %v\n", err)
}
@@ -514,20 +530,22 @@ func executor(in string, p *prompt.Prompt) {
}
// Handle non-command input based on mode
- var output string
if lib.CurrentReplState.Mode == lib.ReplModeTell {
fmt.Println()
args := []string{"tell", input}
var err error
- output, err = lib.ExecPlandexCommand(args)
+ _, err = lib.ExecPlandexCommandWithParams(args, lib.ExecPlandexCommandParams{
+ SessionId: sessionId,
+ })
if err != nil {
color.New(term.ColorHiRed).Printf("Error executing tell: %v\n", err)
}
} else if lib.CurrentReplState.Mode == lib.ReplModeChat {
fmt.Println()
args := []string{"chat", input}
- var err error
- output, err = lib.ExecPlandexCommand(args)
+ output, err := lib.ExecPlandexCommandWithParams(args, lib.ExecPlandexCommandParams{
+ SessionId: sessionId,
+ })
if err != nil {
color.New(term.ColorHiRed).Printf("Error executing chat: %v\n", err)
}
@@ -557,7 +575,9 @@ func executor(in string, p *prompt.Prompt) {
if sel == beginImplOpt {
fmt.Println()
args := []string{"tell", "--from-chat"}
- _, err := lib.ExecPlandexCommand(args)
+ _, err := lib.ExecPlandexCommandWithParams(args, lib.ExecPlandexCommandParams{
+ SessionId: sessionId,
+ })
if err != nil {
color.New(term.ColorHiRed).Printf("Error executing tell: %v\n", err)
}
@@ -878,31 +898,6 @@ func replWelcome(params replWelcomeParams) {
contextMode = "manual"
}
- var applyMode string
- if config.AutoApply {
- applyMode = "auto"
- } else {
- applyMode = "approve"
- }
-
- var executionMode string
- if config.AutoExec {
- executionMode = "auto"
- } else if config.CanExec {
- executionMode = "approve"
- } else {
- executionMode = "disabled"
- }
-
- var commitMode string
- if config.AutoCommit {
- commitMode = "auto"
- } else if config.SkipCommit {
- commitMode = "skip"
- } else {
- commitMode = "manual"
- }
-
filesStr := "%s for loading files into context"
if contextMode == "auto" {
filesStr += " manually (optional)"
@@ -919,14 +914,9 @@ func replWelcome(params replWelcomeParams) {
if printAutoFn != nil {
printAutoFn()
} else {
- fmt.Printf("🚀 Using auto mode %s\n", color.New(color.Bold, term.ColorHiMagenta).Sprint(config.AutoMode))
+ printAutoModeTable(config)
}
- fmt.Printf("⚙️ %s → %s · %s → %s · %s → %s · %s → %s\n",
- color.New(color.FgHiWhite, color.Bold).Sprint("context"), contextMode,
- color.New(color.FgHiWhite, color.Bold).Sprint("apply changes"), applyMode,
- color.New(color.FgHiWhite, color.Bold).Sprint("execution"), executionMode,
- color.New(color.FgHiWhite, color.Bold).Sprint("commits"), commitMode,
- )
+
color.New(color.FgHiWhite).Printf("%s to change auto mode\n", color.New(term.ColorHiCyan, color.Bold).Sprint("\\set-auto"))
color.New(color.FgHiWhite).Printf("%s to see config\n", color.New(term.ColorHiCyan, color.Bold).Sprint("\\config"))
color.New(color.FgHiWhite).Printf("%s to customize config\n", color.New(term.ColorHiCyan, color.Bold).Sprint("\\set-config"))
@@ -935,7 +925,7 @@ func replWelcome(params replWelcomeParams) {
if printModelFn != nil {
printModelFn()
} else {
- fmt.Printf("🧠 Using model pack %s\n", color.New(color.Bold, term.ColorHiMagenta).Sprint(packName))
+ printModelPackTable(packName)
}
color.New(color.FgHiWhite).Printf("%s to see model details\n", color.New(term.ColorHiCyan, color.Bold).Sprint("\\models"))
color.New(color.FgHiWhite).Printf("%s to change models\n", color.New(term.ColorHiCyan, color.Bold).Sprint("\\set-model"))
diff --git a/app/cli/cmd/usage.go b/app/cli/cmd/usage.go
new file mode 100644
index 00000000..9daaf983
--- /dev/null
+++ b/app/cli/cmd/usage.go
@@ -0,0 +1,547 @@
+package cmd
+
+import (
+ "fmt"
+ "os"
+ "plandex-cli/api"
+ "plandex-cli/auth"
+ "plandex-cli/lib"
+ "plandex-cli/term"
+ shared "plandex-shared"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+ "unicode"
+
+ "github.com/eiannone/keyboard"
+ "github.com/fatih/color"
+ "github.com/olekukonko/tablewriter"
+ "github.com/shopspring/decimal"
+ "github.com/spf13/cobra"
+)
+
+const MaxCreditsLogPageSize = 500
+
+var logCreditsPageSize int
+var logCreditsPage int
+
+var logCreditsDebitsOnly bool
+var logCreditsCreditsOnly bool
+
+var showUsageLog bool
+
+var creditsSession bool
+var creditsToday bool
+var creditsMonth bool
+var creditsCurrentPlan bool
+
+var usageCmd = &cobra.Command{
+ Use: "usage",
+ Short: "Display credits balance and usage report",
+ Run: usage,
+}
+
+func init() {
+ RootCmd.AddCommand(usageCmd)
+
+ usageCmd.Flags().BoolVar(&showUsageLog, "log", false, "Show usage log")
+ usageCmd.Flags().IntVarP(&logCreditsPageSize, "page-size", "s", 100, "Number of transactions to display per page")
+ usageCmd.Flags().IntVarP(&logCreditsPage, "page", "p", 1, "Page number to display")
+ usageCmd.Flags().BoolVar(&logCreditsDebitsOnly, "debits", false, "Show only debits in the log")
+ usageCmd.Flags().BoolVar(&logCreditsCreditsOnly, "purchases", false, "Show only purchases in the log")
+
+ usageCmd.Flags().BoolVar(&creditsToday, "today", false, "Show usage for today")
+ usageCmd.Flags().BoolVar(&creditsMonth, "month", false, "Show usage for current billing month")
+ usageCmd.Flags().BoolVar(&creditsCurrentPlan, "plan", false, "Show usage for the current plan")
+}
+
+func usage(cmd *cobra.Command, args []string) {
+ if showUsageLog {
+ showLog(cmd, args)
+ } else {
+ showUsage()
+ }
+}
+
+func formatSpend(spend decimal.Decimal) string {
+ if spend.IsZero() {
+ return "$0.00"
+ }
+
+ spendStr := fmt.Sprintf("$%s", spend.StringFixed(4))
+ for i := 0; i < 2; i++ {
+ if strings.HasSuffix(spendStr, "0") {
+ spendStr = spendStr[:len(spendStr)-1]
+ }
+ }
+ if spendStr == "$0.00" {
+ return "<$0.0001"
+ }
+ return spendStr
+}
+
+func showUsage() {
+ auth.MustResolveAuthWithOrg()
+
+ if !(creditsSession || creditsToday || creditsMonth || creditsCurrentPlan) {
+ if os.Getenv("PLANDEX_REPL_SESSION_ID") != "" {
+ creditsSession = true
+ } else {
+ creditsToday = true
+ }
+ }
+
+ var sessionId string
+ if creditsSession {
+ sessionId = os.Getenv("PLANDEX_REPL_SESSION_ID")
+ if sessionId == "" {
+ term.OutputErrorAndExit("Session ID is not set. The --session flag should be used in the Plandex REPL.")
+ }
+ }
+
+ var dayStart *time.Time
+ if creditsToday {
+ now := time.Now()
+ midnight := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
+ dayStart = &midnight
+ }
+
+ var planId string
+ var currentPlanName string
+ if creditsCurrentPlan {
+ lib.MustResolveProject()
+ planId = lib.CurrentPlanId
+ plan, apiErr := api.Client.GetPlan(planId)
+ if apiErr != nil {
+ term.OutputErrorAndExit("Error getting plan: %v", apiErr)
+ }
+ currentPlanName = plan.Name
+ }
+
+ req := shared.CreditsLogRequest{
+ SessionId: sessionId,
+ DayStart: dayStart,
+ Month: creditsMonth,
+ PlanId: planId,
+ }
+
+ res, apiErr := api.Client.GetCreditsSummary(req)
+ term.StopSpinner()
+
+ if apiErr != nil {
+ term.OutputErrorAndExit("Error getting credits summary: %v", apiErr)
+ }
+
+ builder := strings.Builder{}
+
+ balance := res.Balance
+ balanceStr := formatSpend(balance)
+
+ spendLbl := "💸 Spent"
+ if creditsSession {
+ spendLbl += " This Session"
+ } else if creditsToday {
+ spendLbl += " Today"
+ } else if creditsMonth {
+ spendLbl += " This Billing Month"
+ spendLbl += fmt.Sprintf(" (since %s)", res.MonthStart.Format("Jan 2"))
+ } else if creditsCurrentPlan {
+ spendLbl += fmt.Sprintf(" On Plan 📋 %s", currentPlanName)
+ }
+
+ var spendStr string
+ if res.TotalSpend.IsZero() {
+ spendStr = "$0.00"
+ } else {
+ spendStr = formatSpend(res.TotalSpend)
+ }
+
+ table := tablewriter.NewWriter(&builder)
+ table.SetAutoWrapText(false)
+ table.SetHeader([]string{"💰 Current Balance", spendLbl, "🪙 Cache Savings"})
+ table.Append([]string{balanceStr, spendStr, formatSpend(res.CacheSavings)})
+ table.Render()
+ fmt.Fprintln(&builder)
+
+ amountByStr := map[string]float64{}
+
+ if len(res.ByPlanId) > 0 {
+ if !creditsCurrentPlan {
+ table := tablewriter.NewWriter(&builder)
+ table.SetAutoWrapText(false)
+ table.SetHeader([]string{"📋 Plan", "💸 Spent"})
+
+ rows := [][]string{}
+
+ for id, spend := range res.ByPlanId {
+ name := res.PlanNamesById[id]
+ spendStr := formatSpend(spend)
+ rows = append(rows, []string{name, spendStr})
+ amountByStr[spendStr] = spend.InexactFloat64()
+ }
+ sort.Slice(rows, func(i, j int) bool {
+ return amountByStr[rows[i][1]] > amountByStr[rows[j][1]]
+ })
+ for _, row := range rows {
+ table.Append(row)
+ }
+
+ table.Render()
+ fmt.Fprintln(&builder)
+ }
+ }
+
+ if len(res.ByPurpose) > 0 {
+ table = tablewriter.NewWriter(&builder)
+ table.SetAutoWrapText(false)
+ table.SetHeader([]string{"⚡️ Purpose", "💸 Spent"})
+
+ rows := [][]string{}
+ for name, spend := range res.ByPurpose {
+ spendStr := formatSpend(spend)
+ rows = append(rows, []string{name, spendStr})
+ amountByStr[spendStr] = spend.InexactFloat64()
+ }
+ sort.Slice(rows, func(i, j int) bool {
+ return amountByStr[rows[i][1]] > amountByStr[rows[j][1]]
+ })
+ for _, row := range rows {
+ table.Append(row)
+ }
+
+ table.Render()
+ fmt.Fprintln(&builder)
+ }
+
+ if len(res.ByModelName) > 0 {
+ table = tablewriter.NewWriter(&builder)
+ table.SetAutoWrapText(false)
+ table.SetHeader([]string{"🤖 Model", "💸 Spent"})
+
+ rows := [][]string{}
+ for name, spend := range res.ByModelName {
+ spendStr := formatSpend(spend)
+ rows = append(rows, []string{name, spendStr})
+ amountByStr[spendStr] = spend.InexactFloat64()
+ }
+ sort.Slice(rows, func(i, j int) bool {
+ return amountByStr[rows[i][1]] > amountByStr[rows[j][1]]
+ })
+ for _, row := range rows {
+ table.Append(row)
+ }
+ table.Render()
+ fmt.Fprintln(&builder)
+ }
+
+ term.PageOutput(builder.String())
+
+ term.PrintCmds("", "usage", "billing")
+}
+
+func showLog(cmd *cobra.Command, args []string) {
+ auth.MustResolveAuthWithOrg()
+
+ if !(creditsSession || creditsToday || creditsMonth || creditsCurrentPlan) {
+ if os.Getenv("PLANDEX_REPL_SESSION_ID") != "" {
+ creditsSession = true
+ } else {
+ creditsToday = true
+ }
+ }
+
+ term.StartSpinner("")
+
+ var transactionType shared.CreditsTransactionType
+
+ if logCreditsDebitsOnly {
+ transactionType = shared.CreditsTransactionTypeDebit
+ } else if logCreditsCreditsOnly {
+ transactionType = shared.CreditsTransactionTypeCredit
+ }
+
+ var sessionId string
+ if creditsSession {
+ sessionId = os.Getenv("PLANDEX_REPL_SESSION_ID")
+ if sessionId == "" {
+ term.OutputErrorAndExit("Session ID is not set. The --session flag should be used in the Plandex REPL.")
+ }
+ }
+
+ var dayStart *time.Time
+ if creditsToday {
+ now := time.Now()
+ midnight := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
+ dayStart = &midnight
+ }
+
+ var planId string
+ var planName string
+ if creditsCurrentPlan {
+ lib.MustResolveProject()
+ planId = lib.CurrentPlanId
+
+ plan, err := api.Client.GetPlan(planId)
+ if err != nil {
+ term.OutputErrorAndExit("Error getting plan: %v", err)
+ return
+ }
+ planName = plan.Name
+ }
+
+ req := shared.CreditsLogRequest{
+ TransactionType: transactionType,
+ SessionId: sessionId,
+ DayStart: dayStart,
+ Month: creditsMonth,
+ PlanId: planId,
+ }
+
+ res, apiErr := api.Client.GetCreditsTransactions(logCreditsPageSize, logCreditsPage, req)
+ term.StopSpinner()
+
+ if apiErr != nil {
+ term.OutputErrorAndExit("Error getting credits transactions: %v", apiErr)
+ return
+ }
+
+ transactions := res.Transactions
+
+ if len(transactions) == 0 {
+ lbl := "🤷‍♂️ No usage"
+ if sessionId != "" {
+ lbl = "🤷‍♂️ No usage so far this session"
+ } else if creditsToday {
+ tz, _ := time.Now().Zone()
+ lbl = fmt.Sprintf("🤷‍♂️ No usage so far today (since midnight %s)", tz)
+ } else if creditsMonth {
+ lbl = fmt.Sprintf("🤷‍♂️ No usage so far this billing month (since %s)", res.MonthStart.Format("Jan 2"))
+ } else if creditsCurrentPlan {
+ lbl = "🤷‍♂️ No usage so far for current plan 👉 " + planName
+ }
+ fmt.Println(lbl)
+ return
+ }
+
+ tableString := &strings.Builder{}
+ table := tablewriter.NewWriter(tableString)
+ table.SetAutoWrapText(false)
+ table.SetHeader([]string{"Amount", "Balance", "Transaction"})
+
+ for _, transaction := range transactions {
+ var sign string
+ var c color.Attribute
+
+ desc := transaction.CreatedAt.Local().Format("2006-01-02 15:04:05.000 EST") + "\n"
+
+ if transaction.TransactionType == "debit" {
+ sign = "-"
+ c = term.ColorHiRed
+
+ if transaction.DebitPlanId != nil {
+ planName := res.PlanNamesById[*transaction.DebitPlanId]
+ desc += fmt.Sprintf("Plan → %s\n", planName)
+ }
+
+ surchargePct := transaction.DebitSurcharge.Div(*transaction.DebitBaseAmount)
+
+ inputPrice := transaction.DebitModelInputPricePerToken.Mul(decimal.NewFromInt(1000000)).Mul(surchargePct.Add(decimal.NewFromInt(1))).StringFixed(4)
+ outputPrice := transaction.DebitModelOutputPricePerToken.Mul(decimal.NewFromInt(1000000)).Mul(surchargePct.Add(decimal.NewFromInt(1))).StringFixed(4)
+
+ var cacheDiscountStr string
+ var cacheDiscountPct float64
+ if transaction.DebitCacheDiscount != nil {
+ cacheDiscountStr = transaction.DebitCacheDiscount.StringFixed(4)
+ totalAmount := transaction.DebitBaseAmount.Add(*transaction.DebitCacheDiscount)
+ cacheDiscountPct = transaction.DebitCacheDiscount.Div(totalAmount).Mul(decimal.NewFromInt(100)).InexactFloat64()
+ }
+
+ for i := 0; i < 2; i++ {
+ inputPrice = strings.TrimSuffix(inputPrice, "0")
+ outputPrice = strings.TrimSuffix(outputPrice, "0")
+ cacheDiscountStr = strings.TrimSuffix(cacheDiscountStr, "0")
+ }
+
+ desc += fmt.Sprintf("⚡️ %s\n", *transaction.DebitPurpose)
+ desc += fmt.Sprintf("🧠 %s\n", transaction.ModelString())
+ desc += fmt.Sprintf("💳 Price → $%s input / $%s output per 1M\n", inputPrice, outputPrice)
+ desc += fmt.Sprintf("🪙 Used → %d input / %d output\n", *transaction.DebitInputTokens, *transaction.DebitOutputTokens)
+
+ if cacheDiscountStr != "" {
+ desc += fmt.Sprintf("🎯 Cache discount → $%s (%d%%)\n", cacheDiscountStr, int(cacheDiscountPct))
+ }
+
+ } else {
+ sign = "+"
+ c = term.ColorHiGreen
+
+ switch *transaction.CreditType {
+ case shared.CreditTypeGrant:
+ desc += "Monthly subscription payment"
+ case shared.CreditTypeTrial:
+ desc += "Started trial"
+ case shared.CreditTypePurchase:
+ desc += "Purchased credits"
+ case shared.CreditTypeSwitch:
+ desc += "Switched to Integrated Models mode"
+ }
+
+ desc += "\n"
+ }
+
+ amountStr := transaction.Amount.StringFixed(6)
+ for i := 0; i < 4; i++ {
+ amountStr = strings.TrimSuffix(amountStr, "0")
+ }
+
+ balanceStr := transaction.EndBalance.StringFixed(4)
+ for i := 0; i < 2; i++ {
+ balanceStr = strings.TrimSuffix(balanceStr, "0")
+ }
+
+ table.Append([]string{
+ color.New(c).Sprint(sign + "$" + amountStr),
+ "$" + balanceStr,
+
+ desc,
+ })
+ }
+
+ table.Render()
+
+ var output string
+ var pageLine string
+
+ if res.NumPages > 1 {
+ pageLine = fmt.Sprintf("Page size %d. Showing page %d of %d", logCreditsPageSize, logCreditsPage, res.NumPages)
+ if res.NumPagesMax {
+ pageLine = "+"
+ }
+ output = pageLine + "\n\n" + tableString.String()
+ } else {
+ output = tableString.String()
+ }
+
+ term.PageOutput(output)
+
+ var inputFn func()
+ inputFn = func() {
+ fmt.Println("\n" + pageLine)
+
+ prompts := []string{}
+
+ if res.NumPages > 1 && logCreditsPage < res.NumPages {
+ prompts = append(prompts, "Press 'n' for next page")
+ }
+
+ if logCreditsPage > 1 {
+ prompts = append(prompts, "Press 'p' for previous page")
+ }
+
+ prompts = append(prompts, "Type any number and press enter to jump to a page")
+
+ prompts = append(prompts, "Press 'q' to quit")
+
+ color.New(term.ColorHiMagenta, color.Bold).Println(strings.Join(prompts, "\n"))
+ color.New(term.ColorHiMagenta, color.Bold).Print("> ")
+
+ char, _, err := term.GetUserKeyInput()
+
+ if err != nil {
+ term.OutputErrorAndExit("Failed to get user input: %v", err)
+ }
+
+ // Check if the input is a digit
+ if unicode.IsDigit(char) {
+ var numberInput strings.Builder
+ numberInput.WriteRune(char)
+
+ fmt.Print(string(char)) // Show the initial digit
+
+ for {
+ char, key, err := term.GetUserKeyInput()
+ if err != nil {
+ term.OutputErrorAndExit("Failed to get user input: %v", err)
+ }
+
+ // If Enter is pressed, commit the input
+ if key == keyboard.KeyEnter {
+ pageNumber, err := strconv.Atoi(numberInput.String())
+ if err != nil {
+ fmt.Println("Invalid page number.")
+ return
+ }
+
+ // Check if the page number is valid
+ if pageNumber >= 1 && (pageNumber <= res.NumPages || res.NumPagesMax) {
+ logCreditsPage = pageNumber
+ showLog(cmd, args) // Re-run the log command with the new page
+ } else {
+ fmt.Println()
+ fmt.Println("Invalid page number.")
+ inputFn()
+ }
+ return
+ }
+
+ // If another digit is pressed, add it to the input
+ if unicode.IsDigit(char) {
+ numberInput.WriteRune(char)
+ fmt.Print(string(char)) // Show the digit
+ } else if key == keyboard.KeyBackspace || key == keyboard.KeyBackspace2 {
+ // Handle backspace
+ if numberInput.Len() > 0 {
+ // Remove the last rune
+ input := numberInput.String()
+ numberInput.Reset()
+ numberInput.WriteString(input[:len(input)-1])
+ fmt.Print("\b \b") // Erase the digit
+ }
+
+ } else {
+ // Handle invalid input while typing a number
+ fmt.Println()
+ fmt.Println("\nInvalid input. Please enter a valid page number.")
+ inputFn()
+ return
+ }
+ }
+ }
+
+ // Handle non-digit hotkeys
+ fmt.Print(string(char))
+ switch char {
+ case 'n':
+ if logCreditsPage < res.NumPages || res.NumPagesMax {
+ logCreditsPage++
+ showLog(cmd, args)
+ } else {
+ fmt.Println()
+ fmt.Println("Already on last page.")
+ inputFn()
+ }
+ case 'p':
+ if logCreditsPage > 1 {
+ logCreditsPage--
+ showLog(cmd, args)
+ } else {
+ fmt.Println()
+ fmt.Println("Already on first page.")
+ inputFn()
+ }
+ case 'q':
+ fmt.Println()
+ return
+ default:
+ fmt.Println()
+ fmt.Println("Invalid input.")
+ inputFn()
+ }
+
+ }
+
+ if res.NumPages > 1 {
+ inputFn()
+ }
+}
diff --git a/app/cli/term/help.go b/app/cli/term/help.go
index bc28aa5e..c721ad4e 100644
--- a/app/cli/term/help.go
+++ b/app/cli/term/help.go
@@ -128,8 +128,13 @@ var CliCommands = []CmdConfig{
{"revoke", "", "revoke an invite or remove a user from your org", true},
{"users", "", "list users and pending invites in your org", true},
- {"credits", "", "show Plandex Cloud credits balance", true},
- {"usage", "", "show Plandex Cloud credits transaction log", true},
+ {"usage", "", "show Plandex Cloud current balance and usage report", true},
+ {"usage --today", "", "show Plandex Cloud usage for the day so far", true},
+ {"usage --month", "", "show Plandex Cloud usage for the current billing month", true},
+ {"usage --plan", "", "show Plandex Cloud usage for the current plan", true},
+
+ {"usage --log", "", "show Plandex Cloud transaction log", true},
+
{"billing", "", "show Plandex Cloud billing settings", true},
}
@@ -320,7 +325,7 @@ func PrintHelpAllCommands() {
fmt.Fprintln(builder)
color.New(color.Bold, color.BgCyan, color.FgHiWhite).Fprintln(builder, " Cloud ")
- printCmds(builder, " ", []color.Attribute{color.Bold, ColorHiCyan}, "credits", "usage", "billing")
+ printCmds(builder, " ", []color.Attribute{color.Bold, ColorHiCyan}, "usage", "usage --today", "usage --month", "usage --plan", "usage --log", "billing")
fmt.Fprintln(builder)
color.New(color.Bold, color.BgCyan, color.FgHiWhite).Fprintln(builder, " New Plan Shortcuts ")