@avi2dg/subquo 0.0.0-stage → 0.1.0
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.
- package/.bun-version +1 -0
- package/.github/actions/setup/action.yml +21 -0
- package/.github/actions/setup/bun-without-unzip.sh +20 -0
- package/.github/workflows/ci.yml +177 -0
- package/.github/workflows/main.yml +108 -0
- package/.github/workflows/mutation.yml +106 -0
- package/.github/workflows/pr-title.yml +43 -0
- package/.github/workflows/release.yml +34 -0
- package/.jscpd.json +5 -0
- package/.no-mistakes.yaml +3 -0
- package/AGENTS.md +15 -0
- package/CHANGELOG.md +21 -0
- package/CLAUDE.md +2 -0
- package/LICENSE +21 -0
- package/README.md +79 -2
- package/VISION.md +39 -0
- package/bun.lock +909 -0
- package/bunfig.toml +3 -0
- package/checks.config.ts +7 -0
- package/docs/accounts.md +55 -0
- package/docs/design.md +122 -0
- package/docs/shadow-run.md +49 -0
- package/docs/stage-1-findings.md +65 -0
- package/knip.config.ts +3 -0
- package/oxlint.config.ts +3 -0
- package/package.json +47 -4
- package/scripts/release-assets.ts +28 -0
- package/src/accounts.ts +62 -0
- package/src/cli.ts +122 -0
- package/src/codex-credentials.ts +1 -0
- package/src/collect.ts +45 -0
- package/src/collectors.ts +210 -0
- package/src/index.ts +146 -0
- package/src/keychain.ts +25 -0
- package/src/launch.ts +21 -0
- package/src/pi-codex.ts +17 -0
- package/src/renewal.ts +158 -0
- package/src/storage.ts +48 -0
- package/src/usage.ts +400 -0
- package/stryker.conf.mjs +3 -0
- package/templates/adr.md +32 -0
- package/templates/agents.md +9 -0
- package/templates/changelog.md +39 -0
- package/templates/claude.md +2 -0
- package/templates/explanation.md +15 -0
- package/templates/how-to.md +33 -0
- package/templates/readme.md +48 -0
- package/templates/reference.md +15 -0
- package/templates/tutorial.md +31 -0
- package/templates/vision.md +16 -0
- package/tests/e2e/cli.test.ts +193 -0
- package/tests/e2e/npm-package.test.ts +30 -0
- package/tests/e2e/release-assets.test.ts +53 -0
- package/tests/fixtures/snapshots/fresh.json +54 -0
- package/tests/fixtures/snapshots/incomplete.json +66 -0
- package/tests/unit/collect.test.ts +51 -0
- package/tests/unit/collectors.test.ts +401 -0
- package/tests/unit/no-mistakes.test.ts +8 -0
- package/tests/unit/renewal.test.ts +17 -0
- package/tests/unit/snapshot.test.ts +169 -0
- package/tsconfig.json +46 -0
package/bunfig.toml
ADDED
package/checks.config.ts
ADDED
package/docs/accounts.md
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
---
|
|
2
|
+
kind: reference
|
|
3
|
+
---
|
|
4
|
+
# Account list
|
|
5
|
+
|
|
6
|
+
The account list maps each paid subscription to the login Claude Code, Codex, or OpenCode already uses on this machine.
|
|
7
|
+
|
|
8
|
+
## File and fields
|
|
9
|
+
|
|
10
|
+
Keep a separate `~/.config/subquo/accounts.toml` on each machine, with file mode `0600`.
|
|
11
|
+
List each paid account in its own `[[accounts]]` entry, even if two accounts use the same provider.
|
|
12
|
+
Do not put passwords, tokens, API keys, or account emails in this file.
|
|
13
|
+
Do not commit the file or copy logins between machines.
|
|
14
|
+
|
|
15
|
+
| Field | Required value |
|
|
16
|
+
| --- | --- |
|
|
17
|
+
| `id` | A unique, stable local label of 1 to 64 lowercase letters, digits, hyphens, or underscores. Start with a letter or digit. |
|
|
18
|
+
| `provider` | `claude`, `codex`, or `opencode-go`. |
|
|
19
|
+
| `login.store` | `file` or `macos-keychain`. Use `macos-keychain` only for Claude Code on macOS. |
|
|
20
|
+
| `login.path` | For `file`, the absolute path to the provider's login file. |
|
|
21
|
+
| `login.config_dir` | For `macos-keychain`, the absolute path Claude Code uses as its configuration directory for this account. |
|
|
22
|
+
| `login.service` | For `macos-keychain`, the service name of the account's Keychain item, not its value. Use the exact item name, either `Claude Code-credentials` or its `Claude Code-credentials-<hash>` form. |
|
|
23
|
+
|
|
24
|
+
Each `login` table lists only the fields for its store.
|
|
25
|
+
On Linux or Windows Subsystem for Linux, use `file` for Claude Code.
|
|
26
|
+
For a custom Claude Code directory on macOS, match the exact directory spelling in `CLAUDE_CONFIG_DIR`.
|
|
27
|
+
For a Claude Code file, use its existing `.credentials.json` file.
|
|
28
|
+
For a Codex account, use the `auth.json` file in the Codex home folder, `~/.codex` by default, or the one Pi saves in its agent folder, `~/.pi/agent` by default.
|
|
29
|
+
For OpenCode Go, use the existing `opencode/auth.json` under its data directory.
|
|
30
|
+
|
|
31
|
+
## Example
|
|
32
|
+
|
|
33
|
+
Replace the example IDs and locators with your own.
|
|
34
|
+
|
|
35
|
+
```toml
|
|
36
|
+
[[accounts]]
|
|
37
|
+
id = "example-claude-one"
|
|
38
|
+
provider = "claude"
|
|
39
|
+
login = { store = "macos-keychain", config_dir = "/path/to/example/claude-one", service = "Claude Code-credentials" }
|
|
40
|
+
|
|
41
|
+
[[accounts]]
|
|
42
|
+
id = "example-claude-two"
|
|
43
|
+
provider = "claude"
|
|
44
|
+
login = { store = "file", path = "/path/to/example/claude-two/.credentials.json" }
|
|
45
|
+
|
|
46
|
+
[[accounts]]
|
|
47
|
+
id = "example-codex"
|
|
48
|
+
provider = "codex"
|
|
49
|
+
login = { store = "file", path = "/path/to/example/codex/auth.json" }
|
|
50
|
+
|
|
51
|
+
[[accounts]]
|
|
52
|
+
id = "example-opencode"
|
|
53
|
+
provider = "opencode-go"
|
|
54
|
+
login = { store = "file", path = "/path/to/example/opencode/auth.json" }
|
|
55
|
+
```
|
package/docs/design.md
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
---
|
|
2
|
+
kind: explanation
|
|
3
|
+
---
|
|
4
|
+
# The quota snapshot design
|
|
5
|
+
|
|
6
|
+
subquo splits collecting quota from reading it, so a tool that picks an account reads one local file and never waits on a vendor.
|
|
7
|
+
The commands read without another quota reader, so the staged switch can retire those readers later.
|
|
8
|
+
The time limits below are targets, not measurements on a live provider.
|
|
9
|
+
|
|
10
|
+
## Commands
|
|
11
|
+
|
|
12
|
+
`subquo refresh` reads every account the account list names and writes a new snapshot.
|
|
13
|
+
A scheduler the machine already has runs it, every 60 seconds to start.
|
|
14
|
+
It reads accounts side by side under a concurrency cap.
|
|
15
|
+
Each account has a 5 second limit, and the whole refresh has a 10 second limit, so one slow vendor times out alone.
|
|
16
|
+
It replaces the snapshot file whole, so a killed refresh never leaves half a file.
|
|
17
|
+
When another refresh holds the lock, it skips its turn instead of queueing.
|
|
18
|
+
A collector that meets a rate limit gives that account the safe code without a retry in the same pass.
|
|
19
|
+
Each collector sends the account's own saved login only to that vendor's usage address and forgets it after the read.
|
|
20
|
+
|
|
21
|
+
`subquo read --json` prints the last complete snapshot.
|
|
22
|
+
It never contacts the network, waits on a lock or triggers a refresh.
|
|
23
|
+
Its deadline is one second, with 200 milliseconds as the normal target.
|
|
24
|
+
`subquo read` shows the same snapshot as text and checks quota freshness again when it prints.
|
|
25
|
+
|
|
26
|
+
## The account list
|
|
27
|
+
|
|
28
|
+
Each machine keeps a private account list that names every paid account, its provider and where its saved login lives.
|
|
29
|
+
It holds places, never secrets, and it never leaves the machine.
|
|
30
|
+
A named account whose login is missing shows as login needed, and subquo never reads another account's login in its place.
|
|
31
|
+
Two logins of one subscription count once only when the vendor's identity proves it, never from an email, a label or a matching token.
|
|
32
|
+
|
|
33
|
+
## The snapshot
|
|
34
|
+
|
|
35
|
+
The JSON snapshot holds a `version` of `subquo.v1`, a `writtenAt` time, and an array of `accounts`.
|
|
36
|
+
Each account has a unique `id`, a `provider`, and an `observation`.
|
|
37
|
+
An enrolled account that cannot be read stays in the snapshot with its reason.
|
|
38
|
+
|
|
39
|
+
| Observation `status` | What it holds | What a reader may do with it |
|
|
40
|
+
| --- | --- | --- |
|
|
41
|
+
| `fresh` | `observedAt`, `validUntil`, `source`, and at least one window | treat a current reading with known values as evidence for a pick, not as permission |
|
|
42
|
+
| `stale` | `observedAt`, `source`, the last observed windows, and a safe `code` or `null` | show it with `observedAt`, never pick from it |
|
|
43
|
+
| `unavailable` | a safe `code`: `timeout`, `rate_limited`, `auth_required`, or `auth_unverified` | claim no capacity |
|
|
44
|
+
|
|
45
|
+
The two auth codes mean login needed and login unchecked, respectively.
|
|
46
|
+
A stale reading without a failed refresh has a `null` code.
|
|
47
|
+
A window holds `id`, `scope`, `percentLeft`, and `resetsAt`.
|
|
48
|
+
A measured percent is a finite number from 0 to 100.
|
|
49
|
+
An unknown percent or reset is `null`.
|
|
50
|
+
A reset time is never filled in from a login's expiry or a plan's name.
|
|
51
|
+
Times are UTC strings with millisecond precision, such as `2030-01-01T00:00:00.000Z`.
|
|
52
|
+
|
|
53
|
+
A Claude account with a known sign-in expiry within the next seven days has a `loginEndsInDays` field.
|
|
54
|
+
It counts days from `writtenAt`, rounded up.
|
|
55
|
+
A sign-in that ended at or before `writtenAt` has `loginEndsInDays` of `0`, and its quota observation stays as read.
|
|
56
|
+
The collector uses the saved refresh-token expiry, not the shorter access-token expiry.
|
|
57
|
+
A usable expiry is a whole number of epoch milliseconds from 2020-01-01 UTC to the last date JavaScript can hold.
|
|
58
|
+
A value in seconds is never read as a 1970 date.
|
|
59
|
+
If subquo parses the saved login but its refresh-token expiry is missing or unusable, `loginEndsInDays` is `null`.
|
|
60
|
+
If the login is missing or cannot be parsed, or the vendor answers that it needs a new sign-in, the account has no `loginEndsInDays` field.
|
|
61
|
+
Its observation already shows that state.
|
|
62
|
+
A countdown is not proof that the sign-in still works.
|
|
63
|
+
|
|
64
|
+
The deadline is the earlier of 120 seconds after `observedAt` and the first known window reset.
|
|
65
|
+
At the deadline, the reading becomes stale.
|
|
66
|
+
Recheck the reading's age at the time of use, even if the file marks it `fresh`.
|
|
67
|
+
The pick helper rejects unknown percentages and resets.
|
|
68
|
+
After a reset, subquo waits for a new reading rather than assuming the window is full again.
|
|
69
|
+
|
|
70
|
+
The account ID comes from the private account list.
|
|
71
|
+
Window IDs and scopes are labels the reader assigns, not text taken from vendor replies.
|
|
72
|
+
These labels use 1 to 64 lowercase letters, digits, hyphens, or underscores and start with a letter or digit.
|
|
73
|
+
The snapshot codec drops fields not in the schema and returns `InvalidSnapshot` without the input if validation fails.
|
|
74
|
+
See the [fresh sample](../tests/fixtures/snapshots/fresh.json) and the [sample with missing readings](../tests/fixtures/snapshots/incomplete.json).
|
|
75
|
+
|
|
76
|
+
## Headroom is the smallest limit
|
|
77
|
+
|
|
78
|
+
An account's usable headroom is the smallest of the limits that apply to a job, never their sum.
|
|
79
|
+
With 40% left in a five-hour window and 12% left in a weekly window, the headroom is 12%.
|
|
80
|
+
A window that covers only one kind of work, such as code review, does not limit other jobs.
|
|
81
|
+
A limit with an unknown value leaves the headroom unknown.
|
|
82
|
+
A Claude model limit whose model subquo cannot name makes the account read as login unchecked, so the limit is never dropped.
|
|
83
|
+
|
|
84
|
+
## Logins
|
|
85
|
+
|
|
86
|
+
Each vendor's own tool signs in, saves the login and renews it.
|
|
87
|
+
A collector reads only the login named for that account or the usage entry matched to it.
|
|
88
|
+
subquo never writes a login, because two programs rewriting one login at once can sign out a running worker.
|
|
89
|
+
The separate renewal command asks the vendor to renew an expired login only when you confirm that the account is idle.
|
|
90
|
+
An idle account whose short pass expired reads as login unchecked, which is not proof of a sign-out.
|
|
91
|
+
An account whose renewal fails reads as login needed, and only its owner signing in again clears it.
|
|
92
|
+
|
|
93
|
+
## Secrets
|
|
94
|
+
|
|
95
|
+
Output holds only listed fields and safe error codes, never a vendor's response body.
|
|
96
|
+
No token reaches standard output, standard error, the snapshot, diagnostics, process arguments or test files.
|
|
97
|
+
Tests plant fake tokens and check that no success or failure path prints them.
|
|
98
|
+
|
|
99
|
+
## Reused code
|
|
100
|
+
|
|
101
|
+
Other MIT-licensed quota readers already parse these vendors' responses.
|
|
102
|
+
ccstatusline selects a named Claude login and parses its usage replies.
|
|
103
|
+
opencode-quota holds small OpenCode Go and Codex parsing functions.
|
|
104
|
+
CodexBar serves as a cross-check of response shapes and account boundaries.
|
|
105
|
+
subquo copies only small parts, keeps their licence notices and names the source in the commit.
|
|
106
|
+
|
|
107
|
+
## Open questions
|
|
108
|
+
|
|
109
|
+
The design sources leave these open:
|
|
110
|
+
|
|
111
|
+
- How long an ordinary Claude sign-in lives, since Anthropic does not publish the length.
|
|
112
|
+
- Whether the replies to a long-lived Claude token carry usage, which would let subquo read without the ordinary sign-in.
|
|
113
|
+
- Whether macOS asks for permission the first time subquo reads a login from the Keychain.
|
|
114
|
+
- Whether OpenCode Go still issues a pasted key, and which login store an owner's Go account uses.
|
|
115
|
+
- How long the Claude, ChatGPT and OpenCode usage addresses keep their response shapes, since none of them is a published contract.
|
|
116
|
+
- Which refresh interval the vendors' rate limits allow, after measuring them.
|
|
117
|
+
- Whether the repository stays named subquo, since the design reports call the tool subscription-quota.
|
|
118
|
+
|
|
119
|
+
## Related topics
|
|
120
|
+
|
|
121
|
+
- [Vision](../VISION.md)
|
|
122
|
+
- [Run subquo beside your quota tools](shadow-run.md)
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
---
|
|
2
|
+
kind: how-to
|
|
3
|
+
---
|
|
4
|
+
# Run subquo beside your quota tools
|
|
5
|
+
|
|
6
|
+
Run subquo on each machine where the vendors saved logins.
|
|
7
|
+
|
|
8
|
+
## Before you begin
|
|
9
|
+
|
|
10
|
+
- [subquo installed](../README.md#install) on `PATH`.
|
|
11
|
+
- The vendor's own CLI on `PATH` if you need to ask it to renew a login.
|
|
12
|
+
|
|
13
|
+
## Collect and read a snapshot
|
|
14
|
+
|
|
15
|
+
To collect quota for the accounts on this machine:
|
|
16
|
+
|
|
17
|
+
1. Fill in the [private account list](accounts.md) on each machine.
|
|
18
|
+
1. Run `subquo refresh`.
|
|
19
|
+
1. Run `subquo read --json` to see the saved snapshot.
|
|
20
|
+
1. Have your machine's scheduler run `subquo refresh` every 60 seconds.
|
|
21
|
+
|
|
22
|
+
Each collector reads only the login named for that account and sends it only to that vendor's usage address.
|
|
23
|
+
No other quota reader is required on the machine.
|
|
24
|
+
The snapshot lives under `$XDG_STATE_HOME/subquo` when `XDG_STATE_HOME` is an absolute path.
|
|
25
|
+
Otherwise, it lives under `~/.local/state/subquo`.
|
|
26
|
+
Run `subquo read` to see the sign-in countdown as of the time the snapshot was written.
|
|
27
|
+
If the saved Claude login gave no usable refresh-token expiry, the command shows `login end unknown`.
|
|
28
|
+
If the saved Claude sign-in has already ended, the command shows `login has ended` and still lists the quota it read.
|
|
29
|
+
|
|
30
|
+
## Ask a vendor to renew an idle login
|
|
31
|
+
|
|
32
|
+
To ask the vendor's tool to renew a saved login:
|
|
33
|
+
|
|
34
|
+
1. Make sure the account is idle.
|
|
35
|
+
1. Keep other tools from using or renewing the account while the command runs.
|
|
36
|
+
1. Run `subquo refresh --renew-idle <account>` with the account ID from your private list.
|
|
37
|
+
1. If the command reports `renewed`, run `subquo refresh` and read the next snapshot.
|
|
38
|
+
|
|
39
|
+
Do not schedule the renewal command alongside the collection job.
|
|
40
|
+
It starts Claude Code or Codex only with a saved, expired access token.
|
|
41
|
+
OpenCode Go uses a key and has no renewal step.
|
|
42
|
+
If the vendor takes longer than 45 seconds, leave it running so it can finish writing its own login.
|
|
43
|
+
If it reports `auth_required`, use the vendor's sign-in command yourself.
|
|
44
|
+
If it reports `auth_unverified`, check the selected login with the vendor's tool before trying again.
|
|
45
|
+
|
|
46
|
+
## Related topics
|
|
47
|
+
|
|
48
|
+
- [Account list](accounts.md)
|
|
49
|
+
- [The quota snapshot design](design.md)
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
---
|
|
2
|
+
kind: reference
|
|
3
|
+
---
|
|
4
|
+
# Stage 1 findings
|
|
5
|
+
|
|
6
|
+
These checks cover login records for Claude Code, Codex, and OpenCode Go on macOS and WSL.
|
|
7
|
+
|
|
8
|
+
## Login records
|
|
9
|
+
|
|
10
|
+
On each machine, a TOML parser read back four distinct entries from the private account list.
|
|
11
|
+
Both files had mode `0600`.
|
|
12
|
+
The two macOS Claude Code configuration directories mapped to distinct Keychain items.
|
|
13
|
+
On WSL, both Claude Code login files existed, but `claude auth status` reported that only one account was signed in.
|
|
14
|
+
A login locator can exist even when the vendor CLI reports that the account is signed out.
|
|
15
|
+
|
|
16
|
+
The Codex login files contained a `tokens` key, and the OpenCode login files contained an `opencode-go` key.
|
|
17
|
+
Those checks confirm the storage format, not that the provider still accepts the credentials.
|
|
18
|
+
|
|
19
|
+
## Claude Code access-token expiry
|
|
20
|
+
|
|
21
|
+
Both macOS entries had about eight hours between the Keychain item's last modification and the expiry of its current access token.
|
|
22
|
+
The measurements are from 2026-11-20, and all times are UTC.
|
|
23
|
+
|
|
24
|
+
| Sample | Keychain item last modified | Stored access-token expiry | State at 12:36 |
|
|
25
|
+
| --- | --- | --- | --- |
|
|
26
|
+
| Account A | 06:28:34 | 14:28:34 to 14:28:35 | Not expired |
|
|
27
|
+
| Account B | 04:10:06 | 12:10:06 to 12:10:07 | Expired |
|
|
28
|
+
|
|
29
|
+
The start comes from the Keychain item's modification metadata, not a separate token issuance field.
|
|
30
|
+
The end comes from the [read-only `quota-axi auth` check](https://github.com/kunchenguid/quota-axi/blob/1f5875c3f3ebf09b0fa04e124e9f395fcec68b25/src/providers/claude.ts), which compares the stored `expiresAt` field with the current time.
|
|
31
|
+
Each check used the account's own configuration directory.
|
|
32
|
+
A process-local clock bracketed the point at which the check changed from `available` to `expired`.
|
|
33
|
+
The checks also ran with the real clock, and the Keychain item modification times did not change during measurement.
|
|
34
|
+
|
|
35
|
+
The eight-hour intervals describe two access tokens, not the lifetime of either sign-in.
|
|
36
|
+
On macOS, `claude auth status` reported both accounts signed in even though one access token had already expired.
|
|
37
|
+
The overall sign-in lifetime was not measured.
|
|
38
|
+
|
|
39
|
+
## Claude Code refresh-token expiry
|
|
40
|
+
|
|
41
|
+
A later check read one saved Claude Code login by key names and a digit count only.
|
|
42
|
+
Its `claudeAiOauth` block had a `refreshTokenExpiresAt` key.
|
|
43
|
+
The value was a 13-digit integer, which fits epoch milliseconds.
|
|
44
|
+
[clauth issue 75](https://github.com/uwuclxdy/clauth/issues/75) also lists `refreshTokenExpiresAt` among the keys Claude Code writes, with a 13-digit example.
|
|
45
|
+
The same issue names the field as the only input to Claude Code's refresh-token expiry notice.
|
|
46
|
+
It also reports that clauth 0.15.1 drops the key whenever it rewrites a login file.
|
|
47
|
+
|
|
48
|
+
The check covered one login on one machine.
|
|
49
|
+
It does not show that every Claude Code login has the field, or how long a sign-in lives.
|
|
50
|
+
See the [snapshot design](design.md#the-snapshot) for how subquo handles a missing expiry.
|
|
51
|
+
|
|
52
|
+
## Setup-token output
|
|
53
|
+
|
|
54
|
+
`claude setup-token` prints a one-year OAuth token, not subscription quota windows or reset times.
|
|
55
|
+
The [Claude Code command contract](https://code.claude.com/docs/en/authentication#generate-a-long-lived-token) describes this output.
|
|
56
|
+
The check did not mint a new token.
|
|
57
|
+
Anthropic documents that the token can make only model requests.
|
|
58
|
+
The [Messages API response](https://platform.claude.com/docs/en/api/messages) reports token counts for the request, not the subscription's remaining quota.
|
|
59
|
+
|
|
60
|
+
## Renewal
|
|
61
|
+
|
|
62
|
+
No renewal ran.
|
|
63
|
+
The check inspected the scheduler and running processes on both machines before considering a renewal.
|
|
64
|
+
The [`quota-axi` renewal delegate](https://github.com/kunchenguid/quota-axi/blob/1f5875c3f3ebf09b0fa04e124e9f395fcec68b25/src/providers/claude.ts) documents that Claude Code clears the saved session if Anthropic rejects its refresh token.
|
|
65
|
+
An idle account would still face that risk, so the check stopped before starting `claude doctor`.
|
package/knip.config.ts
ADDED
package/oxlint.config.ts
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@avi2dg/subquo",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Subscription quota reader for paid AI coding accounts",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/avi2d/subquo.git"
|
|
9
|
+
},
|
|
10
|
+
"author": {
|
|
11
|
+
"name": "avi2d",
|
|
12
|
+
"email": "avi2dg@gmail.com"
|
|
13
|
+
},
|
|
14
|
+
"type": "module",
|
|
15
|
+
"bin": {
|
|
16
|
+
"subquo": "src/launch.ts"
|
|
17
|
+
},
|
|
18
|
+
"scripts": {
|
|
19
|
+
"subquo": "bun --no-env-file src/cli.ts",
|
|
20
|
+
"build": "checks-effect-scope && checks-changelog",
|
|
21
|
+
"release:assets": "bun --no-env-file scripts/release-assets.ts",
|
|
22
|
+
"lint": "oxlint && checks-lint",
|
|
23
|
+
"typecheck": "tsc --noEmit && effect-tsgo diagnostics --project tsconfig.json --format text --strict",
|
|
24
|
+
"test": "checks-test",
|
|
25
|
+
"test:e2e": "checks-test --tier=e2e",
|
|
26
|
+
"test:fast": "checks-test --changed",
|
|
27
|
+
"test:unit": "checks-test --tier=unit"
|
|
28
|
+
},
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@effect/platform-bun": "4.0.0",
|
|
31
|
+
"effect": "4.0.0"
|
|
32
|
+
},
|
|
33
|
+
"devDependencies": {
|
|
34
|
+
"@avi2dg/checks": "0.118.0",
|
|
35
|
+
"@hughescr/stryker-bun-runner": "1.4.0",
|
|
36
|
+
"@stryker-mutator/core": "10.0.0",
|
|
37
|
+
"@types/bun": "1.4.5"
|
|
38
|
+
},
|
|
39
|
+
"trustedDependencies": [
|
|
40
|
+
"@swc/core"
|
|
41
|
+
],
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public"
|
|
44
|
+
},
|
|
45
|
+
"optionalDependencies": {
|
|
46
|
+
"@avi2dg/subquo-darwin-arm64": "0.1.0",
|
|
47
|
+
"@avi2dg/subquo-linux-x64": "0.1.0"
|
|
48
|
+
}
|
|
49
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { $ } from "bun";
|
|
2
|
+
|
|
3
|
+
const root = Bun.fileURLToPath(new URL("..", import.meta.url));
|
|
4
|
+
const output = (process.argv[2] ?? `${root}release-assets`).replace(/\/+$/, "");
|
|
5
|
+
const name = `subquo-${process.platform}-${process.arch}`;
|
|
6
|
+
const executable = `${output}/${name}`;
|
|
7
|
+
|
|
8
|
+
if (!((process.platform === "linux" && process.arch === "x64") || (process.platform === "darwin" && process.arch === "arm64"))) {
|
|
9
|
+
console.error("Release assets require Linux x64 or macOS arm64");
|
|
10
|
+
process.exitCode = 1;
|
|
11
|
+
} else {
|
|
12
|
+
await $`mkdir -p ${output}`;
|
|
13
|
+
const result = await Bun.build({
|
|
14
|
+
entrypoints: [`${root}src/cli.ts`],
|
|
15
|
+
compile: { outfile: executable, autoloadDotenv: false, autoloadBunfig: false },
|
|
16
|
+
bytecode: true,
|
|
17
|
+
format: "esm",
|
|
18
|
+
});
|
|
19
|
+
if (!result.success) {
|
|
20
|
+
console.error("Could not compile subquo", result.logs);
|
|
21
|
+
process.exitCode = 1;
|
|
22
|
+
} else {
|
|
23
|
+
const digest = new Bun.CryptoHasher("sha256").update(await Bun.file(executable).arrayBuffer()).digest("hex");
|
|
24
|
+
await Bun.write(`${executable}.sha256`, `${digest} ${name}\n`);
|
|
25
|
+
console.log(executable);
|
|
26
|
+
console.log(`${executable}.sha256`);
|
|
27
|
+
}
|
|
28
|
+
}
|
package/src/accounts.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { Effect, FileSystem, Schema } from "effect";
|
|
2
|
+
import { Label } from "./index";
|
|
3
|
+
|
|
4
|
+
const AbsolutePath = Schema.String.check(Schema.isPattern(/^\/[^\0]*[^/\0]$/u));
|
|
5
|
+
const ClaudeFile = Schema.Struct({
|
|
6
|
+
store: Schema.Literal("file"),
|
|
7
|
+
path: AbsolutePath.check(Schema.isPattern(/\/\.credentials\.json$/u)),
|
|
8
|
+
});
|
|
9
|
+
const CodexFile = Schema.Struct({
|
|
10
|
+
store: Schema.Literal("file"),
|
|
11
|
+
path: AbsolutePath.check(Schema.isPattern(/\/auth\.json$/u)),
|
|
12
|
+
});
|
|
13
|
+
const OpenCodeFile = Schema.Struct({
|
|
14
|
+
store: Schema.Literal("file"),
|
|
15
|
+
path: AbsolutePath.check(Schema.isPattern(/\/opencode\/auth\.json$/u)),
|
|
16
|
+
});
|
|
17
|
+
const Keychain = Schema.Struct({
|
|
18
|
+
store: Schema.Literal("macos-keychain"),
|
|
19
|
+
config_dir: AbsolutePath,
|
|
20
|
+
service: Schema.NonEmptyString,
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
export const claudeDefaultKeychainService = "Claude Code-credentials";
|
|
24
|
+
|
|
25
|
+
export function validClaudeKeychainService(login: {
|
|
26
|
+
readonly config_dir: string;
|
|
27
|
+
readonly service: string;
|
|
28
|
+
}): boolean {
|
|
29
|
+
if (login.service === claudeDefaultKeychainService) return true;
|
|
30
|
+
const hash = Bun.CryptoHasher.hash("sha256", login.config_dir.normalize("NFC"), "hex").slice(0, 8);
|
|
31
|
+
return login.service === `${claudeDefaultKeychainService}-${hash}`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const AccountEntry = Schema.Union([
|
|
35
|
+
Schema.Struct({
|
|
36
|
+
id: Label,
|
|
37
|
+
provider: Schema.Literal("claude"),
|
|
38
|
+
login: Schema.Union([ClaudeFile, Keychain]),
|
|
39
|
+
}),
|
|
40
|
+
Schema.Struct({ id: Label, provider: Schema.Literal("codex"), login: CodexFile }),
|
|
41
|
+
Schema.Struct({ id: Label, provider: Schema.Literal("opencode-go"), login: OpenCodeFile }),
|
|
42
|
+
]);
|
|
43
|
+
export type EnrolledAccount = typeof AccountEntry.Type;
|
|
44
|
+
const AccountList = Schema.Struct({ accounts: Schema.Array(AccountEntry) }).check(
|
|
45
|
+
Schema.makeFilter(({ accounts }) => new Set(accounts.map(({ id }) => id)).size === accounts.length),
|
|
46
|
+
);
|
|
47
|
+
|
|
48
|
+
class InvalidAccountList extends Schema.TaggedError<InvalidAccountList>()("InvalidAccountList", {}) {}
|
|
49
|
+
|
|
50
|
+
const invalidAccountList = () => new InvalidAccountList();
|
|
51
|
+
const decodeAccountList = Schema.decodeUnknownEffect(AccountList, { onExcessProperty: "error" });
|
|
52
|
+
|
|
53
|
+
export const loadAccounts = Effect.fnUntraced(function*(path: string) {
|
|
54
|
+
const fs = yield* FileSystem.FileSystem;
|
|
55
|
+
const info = yield* fs.stat(path).pipe(Effect.mapError(invalidAccountList));
|
|
56
|
+
if (info.type !== "File" || (info.mode & 0o777) !== 0o600) {
|
|
57
|
+
return yield* invalidAccountList();
|
|
58
|
+
}
|
|
59
|
+
const toml = yield* fs.readFileString(path).pipe(Effect.mapError(invalidAccountList));
|
|
60
|
+
const parsed = yield* Effect.try({ try: (): unknown => Bun.TOML.parse(toml), catch: invalidAccountList });
|
|
61
|
+
return yield* decodeAccountList(parsed).pipe(Effect.mapError(invalidAccountList));
|
|
62
|
+
});
|
package/src/cli.ts
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
#!/usr/bin/env -S bun --no-env-file
|
|
2
|
+
import { BunRuntime, BunServices } from "@effect/platform-bun";
|
|
3
|
+
import { Clock, Effect, Path, Schema, Stdio, Stream } from "effect";
|
|
4
|
+
import { loadAccounts } from "./accounts";
|
|
5
|
+
import { readAccount } from "./collectors";
|
|
6
|
+
import { collectSnapshot } from "./collect";
|
|
7
|
+
import { type Snapshot, observationAt, serializeSnapshot } from "./index";
|
|
8
|
+
import { renewIdleLogin } from "./renewal";
|
|
9
|
+
import { readSnapshot, withStateLock, writeSnapshot } from "./storage";
|
|
10
|
+
|
|
11
|
+
class CommandFailed extends Schema.TaggedError<CommandFailed>()("CommandFailed", {}) {}
|
|
12
|
+
|
|
13
|
+
const writeLine = Effect.fnUntraced(function*(line: string, output: "stdout" | "stderr") {
|
|
14
|
+
const stdio = yield* Stdio.Stdio;
|
|
15
|
+
yield* Stream.make(`${line}\n`).pipe(Stream.run(stdio[output]()));
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
function loginNotice(days: Snapshot["accounts"][number]["loginEndsInDays"]): string {
|
|
19
|
+
if (days === undefined) return "";
|
|
20
|
+
if (days === null) return ", login end unknown";
|
|
21
|
+
if (days === 0) return ", login has ended";
|
|
22
|
+
return days === 1 ? ", login ends in 1 day" : `, login ends in ${days} days`;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function renderAccount(account: Snapshot["accounts"][number], now: number): string[] {
|
|
26
|
+
const observation = observationAt(account.observation, now);
|
|
27
|
+
const reason = observation.status === "fresh" || observation.code === null ? "" : ` (${observation.code})`;
|
|
28
|
+
const heading = `${account.id}: ${observation.status}${reason}${loginNotice(account.loginEndsInDays)}`;
|
|
29
|
+
if (observation.status === "unavailable") return [heading];
|
|
30
|
+
return [heading, ...observation.windows.map(({ id, percentLeft, resetsAt }) => {
|
|
31
|
+
const percent = percentLeft === null ? "unknown" : `${percentLeft}% left`;
|
|
32
|
+
return ` ${id}: ${percent}, resets at ${resetsAt ?? "an unknown time"}`;
|
|
33
|
+
})];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function renderSnapshot(snapshot: Snapshot, now: number): string {
|
|
37
|
+
return [`Snapshot written at ${snapshot.writtenAt}`, ...snapshot.accounts.flatMap((account) => renderAccount(account, now))].join("\n");
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const statePaths = Effect.fnUntraced(function*(home: string, stateHome: string | undefined) {
|
|
41
|
+
const path = yield* Path.Path;
|
|
42
|
+
const state = stateHome && path.isAbsolute(stateHome) ? stateHome : path.join(home, ".local", "state");
|
|
43
|
+
const directory = path.join(state, "subquo");
|
|
44
|
+
return {
|
|
45
|
+
accounts: path.join(home, ".config", "subquo", "accounts.toml"),
|
|
46
|
+
lock: path.join(directory, "refresh.sqlite"),
|
|
47
|
+
snapshot: path.join(directory, "snapshot.json"),
|
|
48
|
+
renewalLock: path.join(directory, "renewal.sqlite"),
|
|
49
|
+
};
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
const renew = Effect.fnUntraced(function*(
|
|
53
|
+
files: { readonly accounts: string; readonly renewalLock: string },
|
|
54
|
+
id: string | undefined,
|
|
55
|
+
env: { readonly HOME: string; readonly PATH: string | undefined },
|
|
56
|
+
) {
|
|
57
|
+
const { accounts } = yield* loadAccounts(files.accounts).pipe(
|
|
58
|
+
Effect.tapError(() => writeLine("Could not read the subquo account list.", "stderr")),
|
|
59
|
+
);
|
|
60
|
+
const account = accounts.find((entry) => entry.id === id);
|
|
61
|
+
if (account === undefined) {
|
|
62
|
+
yield* writeLine("Not an enrolled subquo account.", "stderr");
|
|
63
|
+
return yield* new CommandFailed();
|
|
64
|
+
}
|
|
65
|
+
const result = yield* withStateLock(files.renewalLock, Effect.gen(function*() {
|
|
66
|
+
yield* Effect.sleep(45_000).pipe(
|
|
67
|
+
Effect.andThen(writeLine("The vendor tool is still running. Let it finish before you retry.", "stderr")),
|
|
68
|
+
Effect.orElseSucceed(() => undefined),
|
|
69
|
+
Effect.interruptible,
|
|
70
|
+
Effect.forkScoped,
|
|
71
|
+
);
|
|
72
|
+
return yield* Effect.uninterruptible(renewIdleLogin(account, env));
|
|
73
|
+
}).pipe(Effect.scoped));
|
|
74
|
+
if (result.status === "busy") {
|
|
75
|
+
yield* writeLine("A renewal is already running.", "stderr");
|
|
76
|
+
return yield* new CommandFailed();
|
|
77
|
+
}
|
|
78
|
+
yield* writeLine(result.value, "stdout");
|
|
79
|
+
if (result.value === "auth_required" || result.value === "auth_unverified") return yield* new CommandFailed();
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
const run = Effect.fnUntraced(function*(home: string, stateHome: string | undefined, executablePath: string | undefined) {
|
|
83
|
+
const stdio = yield* Stdio.Stdio;
|
|
84
|
+
const args = yield* stdio.args;
|
|
85
|
+
const [command, flag, id] = args;
|
|
86
|
+
const path = yield* Path.Path;
|
|
87
|
+
if (!path.isAbsolute(home)) {
|
|
88
|
+
yield* writeLine("An absolute HOME is required.", "stderr");
|
|
89
|
+
return yield* new CommandFailed();
|
|
90
|
+
}
|
|
91
|
+
const files = yield* statePaths(home, stateHome);
|
|
92
|
+
|
|
93
|
+
if (command === "read" && (args.length === 1 || (flag === "--json" && args.length === 2))) {
|
|
94
|
+
const snapshot = yield* readSnapshot(files.snapshot).pipe(
|
|
95
|
+
Effect.tapError(() => writeLine("No readable subquo snapshot.", "stderr")),
|
|
96
|
+
);
|
|
97
|
+
const now = yield* Clock.currentTimeMillis;
|
|
98
|
+
const output = flag === "--json" ? yield* serializeSnapshot(snapshot) : renderSnapshot(snapshot, now);
|
|
99
|
+
return yield* writeLine(output, "stdout");
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
if (command === "refresh" && args.length === 1) {
|
|
103
|
+
return yield* withStateLock(files.lock, Effect.gen(function*() {
|
|
104
|
+
const { accounts } = yield* loadAccounts(files.accounts);
|
|
105
|
+
const snapshot = yield* collectSnapshot(accounts.map((account) => ({
|
|
106
|
+
id: account.id, provider: account.provider, read: readAccount(account),
|
|
107
|
+
})));
|
|
108
|
+
yield* writeSnapshot(files.snapshot, snapshot);
|
|
109
|
+
})).pipe(Effect.tapError(() => writeLine("Could not refresh subquo. Check the account list and state directory.", "stderr")));
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
if (command === "refresh" && flag === "--renew-idle" && args.length === 3) {
|
|
113
|
+
return yield* renew(files, id, { HOME: home, PATH: executablePath });
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
yield* writeLine("Usage: subquo refresh [--renew-idle <account>] | subquo read [--json]", "stderr");
|
|
117
|
+
return yield* new CommandFailed();
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
BunRuntime.runMain(run(Bun.env.HOME ?? "", Bun.env.XDG_STATE_HOME, Bun.env.PATH).pipe(
|
|
121
|
+
Effect.provide(BunServices.layer),
|
|
122
|
+
), { disableErrorReporting: true });
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export type CodexCredentials = { readonly accessToken: string; readonly accountId?: string; readonly expiresAt?: number };
|
package/src/collect.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { Clock, Effect } from "effect";
|
|
2
|
+
import { type Account, type FailureCode, type Snapshot, type Windows, loginWarningAt, measuredObservation } from "./index";
|
|
3
|
+
|
|
4
|
+
export type Reading = { readonly loginExpiresAt?: number | null } & (
|
|
5
|
+
| { readonly observedAt: string; readonly windows: typeof Windows.Type }
|
|
6
|
+
| { readonly code: FailureCode }
|
|
7
|
+
);
|
|
8
|
+
|
|
9
|
+
type Collector<R> = Pick<Account, "id" | "provider"> & { readonly read: Effect.Effect<Reading, never, R> };
|
|
10
|
+
|
|
11
|
+
const accountLimitMs = 5_000;
|
|
12
|
+
const cycleLimitMs = 10_000;
|
|
13
|
+
const maxConcurrentAccounts = 8;
|
|
14
|
+
const timedOut = Effect.succeed<Reading>({ code: "timeout" });
|
|
15
|
+
|
|
16
|
+
export const collectSnapshot = Effect.fnUntraced(function*<R>(collectors: readonly Collector<R>[]) {
|
|
17
|
+
const deadline = (yield* Clock.currentTimeMillis) + cycleLimitMs;
|
|
18
|
+
const readings = yield* Effect.forEach(collectors, ({ id, provider, read }) =>
|
|
19
|
+
Effect.gen(function*() {
|
|
20
|
+
const remaining = deadline - (yield* Clock.currentTimeMillis);
|
|
21
|
+
const reading = remaining <= 0 ? yield* timedOut : yield* read.pipe(
|
|
22
|
+
Effect.catchDefect(() => Effect.succeed<Reading>({ code: "auth_unverified" })),
|
|
23
|
+
Effect.timeoutOrElse({ duration: Math.min(remaining, accountLimitMs), orElse: () => timedOut }),
|
|
24
|
+
);
|
|
25
|
+
return { id, provider, reading };
|
|
26
|
+
}), { concurrency: maxConcurrentAccounts },
|
|
27
|
+
);
|
|
28
|
+
const now = yield* Clock.currentTimeMillis;
|
|
29
|
+
return {
|
|
30
|
+
version: "subquo.v1",
|
|
31
|
+
writtenAt: new Date(now).toISOString(),
|
|
32
|
+
accounts: readings.map(({ id, provider, reading }): Account => {
|
|
33
|
+
const expiry = reading.loginExpiresAt;
|
|
34
|
+
const days = typeof expiry === "number" ? loginWarningAt(expiry, now) : expiry;
|
|
35
|
+
return {
|
|
36
|
+
id,
|
|
37
|
+
provider,
|
|
38
|
+
observation: "code" in reading
|
|
39
|
+
? { status: "unavailable", code: reading.code }
|
|
40
|
+
: measuredObservation(reading.observedAt, reading.windows, now),
|
|
41
|
+
...(days === undefined ? {} : { loginEndsInDays: days }),
|
|
42
|
+
};
|
|
43
|
+
}),
|
|
44
|
+
} satisfies Snapshot;
|
|
45
|
+
});
|