Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ codex-switch account add work --device-auth
# Inspect and switch. Close Codex before switching, then restart it.
codex-switch account list
codex-switch account usage work
codex-switch account wake work
codex-switch use work
codex-switch current

Expand Down Expand Up @@ -122,6 +123,23 @@ shows exact local reset times plus each returned earned-reset grant and expiry.
The authoritative earned-reset count can be present even when the service omits
or caps its detail rows.

To start an idle quota window without switching accounts, explicitly send one
minimal request:

```bash
codex-switch account wake work
# Equivalent, more descriptive spelling:
codex-switch account start-window work
```

The command always targets exactly one saved alias and intentionally consumes a
small amount of that account's Codex allowance. It does not retry the model
request. Codex runs with a fixed short prompt, minimal reasoning, no persisted
session, an empty temporary workspace, a read-only sandbox, and no user config,
rules, plugins, or MCP servers. After the request completes, `codex-switch`
refreshes the usage snapshot so the returned reset time can be inspected. The
service, not `codex-switch`, remains authoritative about when a window starts.

## Commands

```text
Expand All @@ -138,6 +156,7 @@ codex-switch account add <alias>
codex-switch account import-current <alias>
codex-switch account list [--refresh|--cached]
codex-switch account usage [alias] [--all] [--cached]
codex-switch account wake <alias>
codex-switch account show <alias>
codex-switch account rename <old> <new>
codex-switch account reauth <alias>
Expand Down Expand Up @@ -186,6 +205,11 @@ back to the encrypted vault. If the queried profile is active, the same
generation is safely reconciled into `$CODEX_HOME/auth.json`; no account selection
or Codex-owned state changes.

`account wake` has the same credential-isolation behavior, but additionally
creates one ephemeral Codex turn for the selected saved profile and records its
`lastUsedAt` timestamp. It never replaces the selected live account or writes a
session into the shared `CODEX_HOME`.

Initialization may make a one-time, backed-up change to
`$CODEX_HOME/config.toml` to set `cli_auth_credentials_store = "file"`.
`codex-switch` does not rewrite session history or Codex configuration during a
Expand Down
23 changes: 22 additions & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
drift, safely synchronizes known profiles, prepares a journal, performs
compare-before-replace, and records the selected profile.
- `codexusage` runs the official Codex App Server in an isolated temporary
`CODEX_HOME` and reads the stable account, rate-limit, and token-usage methods.
`CODEX_HOME`, optionally sends one minimal ephemeral request, and reads the
stable account, rate-limit, and token-usage methods.
- `accountusage` queries up to four profiles concurrently, reconciles credential
refresh generations, and coordinates with switching through the same lock.
- `usagecache` stores credential-free successful snapshots separately from the
Expand Down Expand Up @@ -97,6 +98,26 @@ backoff using the newest validated credential generation returned by the prior
attempt. Multi-account refreshes are intentionally sequential so independent
App Server processes do not compete for startup or authentication resources.

## Isolated quota-window wake

```text
acquire shared operation lock
-> decrypt and validate exactly one selected profile
-> create a temporary CODEX_HOME and an unrelated empty workspace
-> run one non-interactive, ephemeral Codex turn with a fixed short prompt
-> disable user config and rules; use minimal reasoning and a read-only sandbox
-> do not retry the turn
-> query the account usage through App Server in the same temporary home
-> reconcile any rotated credential generation and cache the new snapshot
-> delete both temporary directories
```

The wake path uses the same identity, generation, and active-file reconciliation
checks as a normal usage query. It does not project the target profile into the
shared `CODEX_HOME` and does not persist a Codex session. A successful turn is
real quota usage; the subsequent snapshot is the evidence available for whether
the service started or advanced a quota window.

## Data locations

`CODEX_HOME` resolution:
Expand Down
6 changes: 6 additions & 0 deletions docs/compatibility.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,12 @@ Usage querying initializes `codex app-server` and calls:
- `account/rateLimits/read`
- `account/usage/read`

`account wake` additionally requires the installed CLI's non-interactive
`codex exec` mode and its `--ephemeral`, `--ignore-user-config`,
`--ignore-rules`, and read-only sandbox options. The wake turn uses the CLI's
default ChatGPT-plan Codex model so it affects the ordinary Codex allowance
rather than selecting a separately metered model family.

When returned by `account/rateLimits/read`, the client also preserves
`rateLimitResetCredits.availableCount` and its optional grant/expiration detail
rows. Older services that omit this optional object remain supported.
Expand Down
4 changes: 4 additions & 0 deletions docs/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ focuses on:
- JSON output is intentionally based on dedicated public view types.
- Usage queries create per-profile temporary homes with mode `0700` and
credential files with mode `0600`, then remove them after the App Server exits.
- Quota-window wake requests use the same temporary credential home plus a
separate empty workspace. They run one fixed prompt with an ephemeral session,
minimal reasoning, ignored user config and rules, a read-only sandbox, and no
automatic retry. Child stdout and diagnostics are never exposed or cached.
- The usage cache contains rate limits, earned-reset counts and metadata,
aggregate token statistics, timestamps, and public account metadata only. It
never contains authentication documents.
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module github.com/SilkageNet/codex-switch

go 1.26.7
go 1.26.10

require (
github.com/minio/selfupdate v0.6.0
Expand Down
24 changes: 17 additions & 7 deletions internal/accountusage/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,14 @@ type QueryRunner interface {
}

type Service struct {
Home codexhome.Home
Paths appconfig.Paths
Vault *vault.Manager
Runner QueryRunner
Home codexhome.Home
Paths appconfig.Paths
Vault *vault.Manager
Runner QueryRunner
QueryTimeout time.Duration
QueryAttempts int
RecordUse bool

queryAttempts int
retryBaseDelay time.Duration
}

Expand Down Expand Up @@ -153,6 +155,10 @@ func (service Service) Refresh(ctx context.Context, profileIDs []string) (map[st
}
if results[profileID].Error == "" {
cache.Profiles[profileID] = results[profileID].Snapshot
if service.RecordUse {
profile.LastUsedAt = time.Now().UTC()
vaultChanged = true
}
}
saved, parseErr := authschema.Parse(profile.Auth)
if parseErr != nil {
Expand Down Expand Up @@ -227,10 +233,14 @@ func (service Service) Refresh(ctx context.Context, profileIDs []string) (map[st
}

func (service Service) queryWithRetry(ctx context.Context, auth json.RawMessage) (codexusage.Snapshot, json.RawMessage, int, error) {
attemptLimit := service.queryAttempts
attemptLimit := service.QueryAttempts
if attemptLimit <= 0 {
attemptLimit = defaultQueryAttempts
}
timeout := service.QueryTimeout
if timeout <= 0 {
timeout = queryTimeout
}
baseDelay := service.retryBaseDelay
if baseDelay <= 0 {
baseDelay = defaultRetryBaseDelay
Expand All @@ -242,7 +252,7 @@ func (service Service) queryWithRetry(ctx context.Context, auth json.RawMessage)
if err := ctx.Err(); err != nil {
return codexusage.Snapshot{}, nil, attempt - 1, err
}
queryContext, cancel := context.WithTimeout(ctx, queryTimeout)
queryContext, cancel := context.WithTimeout(ctx, timeout)
snapshot, updatedAuth, err := service.Runner.Query(queryContext, currentAuth)
cancel()
if len(updatedAuth) > 0 {
Expand Down
18 changes: 18 additions & 0 deletions internal/accountusage/service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ func (runner fakeRunner) Query(context.Context, json.RawMessage) (codexusage.Sna

func TestRefreshCachesUsageAndAdoptsRotatedCredentials(t *testing.T) {
service, manager, profile := testService(t, false)
service.RecordUse = true
updated := authBytes("account-a", "refresh-new", "2026-08-20T01:00:00Z")
lifetime := int64(1234)
service.Runner = fakeRunner{
Expand All @@ -70,12 +71,29 @@ func TestRefreshCachesUsageAndAdoptsRotatedCredentials(t *testing.T) {
if document.Tokens.RefreshToken != "refresh-new" {
t.Fatal("rotated credential was not saved")
}
if saved.LastUsedAt.IsZero() || !saved.LastUsedAt.After(profile.LastUsedAt) {
t.Fatalf("successful wake did not record account use: %#v", saved.LastUsedAt)
}
cache, err := service.Cached()
if err != nil || cache.Profiles[profile.ID].PlanType != "pro" {
t.Fatalf("usage was not cached: %#v, %v", cache, err)
}
}

func TestRefreshCanDisableRetriesForOneShotRequests(t *testing.T) {
service, _, profile := testService(t, false)
runner := &retryRunner{failures: 3, auth: authBytes("account-a", "refresh-new", "2026-08-20T01:00:00Z")}
service.Runner = runner
service.QueryAttempts = 1
results, err := service.Refresh(context.Background(), []string{profile.ID})
if err != nil {
t.Fatal(err)
}
if runner.calls != 1 || results[profile.ID].Attempts != 1 {
t.Fatalf("one-shot refresh retried: calls=%d result=%#v", runner.calls, results[profile.ID])
}
}

func TestRefreshRetriesAndClearsPersistedFailure(t *testing.T) {
service, _, profile := testService(t, false)
runner := &retryRunner{
Expand Down
79 changes: 79 additions & 0 deletions internal/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,11 @@ type usageView struct {
Attempts int `json:"attempts,omitempty"`
}

type wakeView struct {
Account accountView `json:"account"`
RequestSent bool `json:"requestSent"`
}

const usageFreshness = 5 * time.Minute

func NewCommand(version string) *cobra.Command {
Expand Down Expand Up @@ -155,6 +160,7 @@ func newAccountCommand(options *Options) *cobra.Command {
newAccountAddCommand(options, false),
newAccountListCommand(options),
newAccountUsageCommand(options),
newAccountWakeCommand(options),
newAccountShowCommand(options),
newAccountRenameCommand(options),
newAccountRemoveCommand(options),
Expand Down Expand Up @@ -450,6 +456,62 @@ func newAccountUsageCommand(options *Options) *cobra.Command {
return command
}

func newAccountWakeCommand(options *Options) *cobra.Command {
return &cobra.Command{
Use: "wake <alias>",
Aliases: []string{"start-window"},
Short: "Send one minimal Codex request to start an idle usage window",
Args: cobra.ExactArgs(1),
RunE: func(_ *cobra.Command, args []string) error {
runtime, err := options.loadRuntime(false)
if err != nil {
return err
}
data, err := runtime.manager.Load()
if err != nil {
return err
}
profile, err := data.Find(args[0])
if err != nil {
return err
}
results, err := runtime.wakeService(options.Version).Refresh(context.Background(), []string{profile.ID})
if err != nil {
return err
}
result := results[profile.ID]
if result.Error != "" {
return fmt.Errorf("wake request for %q failed: %s", profile.Alias, result.Error)
}
data, err = runtime.manager.Load()
if err != nil {
return err
}
profile, err = data.Find(profile.ID)
if err != nil {
return err
}
observation, err := runtime.switcher().Observe()
if err != nil {
return err
}
cache, err := runtime.usageService(options.Version).Cached()
if err != nil {
return err
}
view := toView(*profile, observation.Managed && observation.ProfileID == profile.ID)
view.Usage = usageFromCache(cache, profile.ID, "", time.Now())
wake := wakeView{Account: view, RequestSent: true}
if options.JSON {
return options.render(wake, "")
}
_, _ = fmt.Fprintf(options.Output, "Sent one minimal Codex request for %q without changing the active account.\n", profile.Alias)
_, _ = fmt.Fprintln(options.Output, formatUsage(view, time.Now()))
return nil
},
}
}

func newAccountShowCommand(options *Options) *cobra.Command {
return &cobra.Command{
Use: "show <alias>",
Expand Down Expand Up @@ -984,6 +1046,23 @@ func (runtime runtimeState) usageService(version string) accountusage.Service {
}
}

func (runtime runtimeState) wakeService(version string) accountusage.Service {
return accountusage.Service{
Home: runtime.home,
Paths: runtime.paths,
Vault: runtime.manager,
QueryTimeout: 90 * time.Second,
QueryAttempts: 1,
RecordUse: true,
Runner: codexusage.Runner{
Binary: runtime.bin,
BinaryError: runtime.binErr,
ClientVersion: version,
Wake: true,
},
}
}

func (options *Options) currentView() (accountView, error) {
runtime, err := options.loadRuntime(false)
if err != nil {
Expand Down
Loading
Loading