sprag-cli 3.83.0 → 3.85.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/bin/cli.js +2 -0
- package/docs/TEAM.ko.md +22 -3
- package/docs/TEAM.md +22 -3
- package/package.json +1 -1
- package/src/codex/cache-policy.js +6 -3
- package/src/codex/doc2md-ledger.js +23 -0
- package/src/codex/ledger.js +21 -2
- package/src/codex/parser.js +99 -12
- package/src/commands/codex.js +2 -0
- package/src/commands/route-scan.js +1 -1
- package/src/commands/team.js +20 -0
- package/src/commands/upgrade.js +137 -1
- package/src/cost.js +31 -7
- package/src/cowork-sessions.js +91 -0
- package/src/cowork-sync.js +2 -10
- package/src/gateway-auth.js +33 -0
- package/src/gateway-prices.js +54 -2
- package/src/gateway-spend.js +137 -0
- package/src/litellm-models.js +2 -3
- package/src/org-upgrade.js +179 -0
- package/src/parser.js +16 -8
- package/src/route-scan.js +17 -8
- package/src/session-cache.js +10 -7
- package/src/team-ratchet.js +2 -2
- package/src/team-sync.js +274 -39
- package/src/transcript-lines.js +66 -0
- package/src/update-notice.js +10 -2
package/bin/cli.js
CHANGED
|
@@ -476,10 +476,12 @@ async function main() {
|
|
|
476
476
|
// got here, then confirm the new version.
|
|
477
477
|
// sprag upgrade # install the latest release
|
|
478
478
|
// sprag upgrade --print # just show the command, run nothing
|
|
479
|
+
// sprag upgrade --org-policy # non-interactive, started by the session-start hook
|
|
479
480
|
if (args[0] === 'upgrade') {
|
|
480
481
|
return (await import('../src/commands/upgrade.js')).run({
|
|
481
482
|
hasFlag,
|
|
482
483
|
version: PKG_VERSION,
|
|
484
|
+
agent,
|
|
483
485
|
});
|
|
484
486
|
}
|
|
485
487
|
|
package/docs/TEAM.ko.md
CHANGED
|
@@ -10,10 +10,20 @@ Sprag 은 기본적으로 로컬에서만 동작합니다. 팀 기능은 켜야
|
|
|
10
10
|
|
|
11
11
|
| 항목 | 내용 |
|
|
12
12
|
|---|---|
|
|
13
|
-
| 지출(USD) | 로컬 세션 로그로 계산한
|
|
13
|
+
| 지출(USD) | 로컬 세션 로그로 계산한 금액이며 Claude 데스크톱 앱의 Cowork 세션을 포함합니다 |
|
|
14
14
|
| 절감(USD) | 라우팅 원장과 doc2md 원장에서 가져온 금액 |
|
|
15
|
-
| 위임 실행 횟수 | 그날 위임한 실행의 수 |
|
|
15
|
+
| 위임 실행 횟수 | 그날 위임한 Claude와 Codex 실행의 수 |
|
|
16
16
|
| 모델 계열 비중 | 위임 실행 중 모델 계열별 비율 |
|
|
17
|
+
| 모델 계열별 지출(USD) | 그날 지출을 모델 계열(`opus`, `sonnet`, `haiku`, `fable` 등)별로 나눈 금액입니다. 콘솔에서 사람마다 어느 모델에 돈을 쓰는지 보여 주는 데 쓰며, 3.84.0부터 보냅니다 |
|
|
18
|
+
| Claude 지출(USD) | Claude Code와 Claude 데스크톱 앱 Cowork의 로컬 지출입니다. 메인 세션과 서브에이전트 실행을 합친 금액이며 지출(USD)과 같은 값입니다. 3.84.0부터 보냅니다 |
|
|
19
|
+
| Codex 지출(USD) | Codex 롤아웃 사용량 기록으로 계산한 로컬 지출이며 압축된 롤아웃(`.jsonl.zst`)과 게이트웨이의 장문맥 구간 가격을 반영합니다. 가격을 모르면 비어 있습니다. 3.84.0부터 보냅니다 |
|
|
20
|
+
| 게이트웨이 지출(USD) | LiteLLM 게이트웨이를 쓸 때 게이트웨이가 집계한 본인의 하루 지출입니다. 게이트웨이가 없거나 호출이 실패하면 비어 있습니다. 3.84.0부터 보냅니다 |
|
|
21
|
+
| 게이트웨이 사용자 해시 | 게이트웨이 주소와 게이트웨이 사용자 ID를 합쳐 해시한 값의 앞 16자리(16진수)입니다. 한 사람이 컴퓨터 두 대를 써도 한 번만 세는 데 쓰며, 사용자 ID를 모르면 되돌릴 수 없습니다. 3.84.0부터 보냅니다 |
|
|
22
|
+
| 총지출(USD) | 게이트웨이 금액을 알면 그 값이고, 모르면 Claude 지출과 Codex 지출의 합입니다. 3.84.0부터 보냅니다 |
|
|
23
|
+
| 위임 비용(USD) | Sprag 모델 피팅 룰이 위임한 실행에 실제로 든 비용입니다. Claude와 Codex를 합칩니다. 3.84.0부터 보냅니다 |
|
|
24
|
+
| Codex 위임 실행 횟수와 비용 | 위임 실행과 그 비용 가운데 Codex가 차지한 몫입니다. 3.84.0부터 보냅니다 |
|
|
25
|
+
| 서브에이전트 비용(USD) | 룰과 상관없이 모든 서브에이전트 실행과 Codex 하위 세션에 든 비용입니다. 보조 수치입니다. 3.84.0부터 보냅니다 |
|
|
26
|
+
| 가격 미상 건수 | 가격을 몰라 계산에서 뺀 세션이나 실행의 수입니다. 3.84.0부터 보냅니다 |
|
|
17
27
|
| Sprag 버전 | 설치된 버전 |
|
|
18
28
|
| 에이전트 | `claude` 또는 `codex` |
|
|
19
29
|
| 표시 이름 | 참여할 때 정한 이름이며, 기본값은 컴퓨터마다 한 번 만드는 `member-3f9a2c71` 같은 무작위 구성원 ID |
|
|
@@ -26,7 +36,7 @@ Sprag 은 기본적으로 로컬에서만 동작합니다. 팀 기능은 켜야
|
|
|
26
36
|
|
|
27
37
|
팀에 참여한 동안 statusline 에 `team` 칩이 나타나 멤버 ID 와 가상 사무실(Sprag 타운)에서 받은 동물을 보여 줍니다. 예를 들면 `member-1e500474 🦊 여우 12명 중 3위` 처럼 조직에서 순위에 오른 사람 가운데 몇 위인지도 함께 보여 줍니다. 동물은 5분마다 도는 전체 동기화가 서버에서 받아 `team.json` 에 저장한 순위로 정합니다. 서버가 아직 이 기능을 지원하지 않거나 마지막으로 받은 지 하루가 넘었다면 멤버 ID 만 표시합니다. 칩을 그릴 때는 로컬 파일만 읽습니다. IntelliJ 터미널은 글꼴에 동물 이모지가 없어 narrow 모드로 그리므로, 이때와 text 모드에서는 `member-1e500474 여우 12명 중 3위` 처럼 이모지 없이 이름만 보여 줍니다. 버전 칩 바로 앞에 놓이며, `--segments team` 으로 이 칩만 따로 볼 수 있습니다.
|
|
28
38
|
|
|
29
|
-
목적지는 `https://hiycfjwswtkixyoqkznm.supabase.co/rest/v1/rpc/*` 입니다(Supabase, ap-northeast-2 리전). 호출하는 RPC 는 `team_join`, `ledger_upsert`, `team_rules_get`, `team_rule_propose`, `team_leave`, `prompt_chunk_put`(엔터프라이즈 프롬프트 수집일 때만), `member_set_sync`(업로드 스위치 상태 호출, "업로드 스위치" 참고), `member_set_info`(OS 이름과 버전, `arch` 인자는 항상 빈 값), `member_set_name`(`sprag team name` 을 실행할 때만), `member_standing`(statusline 칩에 쓸 본인의 사무실 동물과 순위만 받고 다른 사람의 수치는 받지 않음) 입니다.
|
|
39
|
+
목적지는 `https://hiycfjwswtkixyoqkznm.supabase.co/rest/v1/rpc/*` 입니다(Supabase, ap-northeast-2 리전). 호출하는 RPC 는 `team_join`, `ledger_upsert`, `team_rules_get`, `team_rule_propose`, `team_leave`, `prompt_chunk_put`(엔터프라이즈 프롬프트 수집일 때만), `member_set_sync`(업로드 스위치 상태 호출, "업로드 스위치" 참고), `member_set_info`(OS 이름과 버전, `arch` 인자는 항상 빈 값), `member_set_name`(`sprag team name` 을 실행할 때만), `member_standing`(statusline 칩에 쓸 본인의 사무실 동물과 순위만 받고 다른 사람의 수치는 받지 않음) 입니다. LiteLLM 게이트웨이를 설정했다면 하루 동기화마다 게이트웨이의 `GET /user/info` 와 `GET /global/spend/logs` 도 본인 키로 호출해 본인의 하루 게이트웨이 지출을 읽습니다. 그 밖의 것은 읽지 않으며 키는 저장하지 않습니다. 비용을 계산하려고 `~/Library/Application Support/Claude-3p/local-agent-mode-sessions` 아래의 Claude 데스크톱 앱 Cowork 기록을 로컬에서 읽습니다. 밖으로 나가는 것은 하루 합계뿐이며 작업 이름과 프롬프트는 보내지 않습니다. `sprag team status --show-payload` 를 실행하면 보내는 행을 그대로 볼 수 있습니다.
|
|
30
40
|
|
|
31
41
|
## CLI에서 팀 만들기
|
|
32
42
|
|
|
@@ -122,6 +132,14 @@ Sprag 은 룰을 `~/.claude/ratchet-team.md`(Codex 는 `<CODEX_HOME>/ratchet-tea
|
|
|
122
132
|
|
|
123
133
|
관리하는 조직 안에 팀을 만들려면 `sprag team create --org <조직 ID>` 를 씁니다. 조직은 Sprag만 개설하므로 `--org` 없이 실행하면 서버가 거절합니다. 명령은 조직 이름과 사용 중인 좌석 수를 함께 출력하고, `sprag team status` 는 조직 이름을 보여 줍니다.
|
|
124
134
|
|
|
135
|
+
## 조직 최소 버전
|
|
136
|
+
|
|
137
|
+
Sprag 운영자는 ops 콘솔(sprag.io/ops/)에서 조직마다 최소 Sprag 버전을 정할 수 있습니다. 오너와 어드민은 바꿀 수 없습니다. 컴퓨터는 이 값을 팀 룰과 함께 약 한 시간마다 받아 옵니다.
|
|
138
|
+
|
|
139
|
+
그 조직의 컴퓨터가 더 낮은 버전이면 다음 세션을 시작할 때 묻지 않고 백그라운드에서 스스로 업그레이드합니다. Sprag 이 질문 없이 패키지를 설치하는 유일한 경우이며, 그 밖의 업그레이드는 여전히 사용자의 동의를 기다립니다. 모델에게는 업그레이드가 시작되었고 새 버전이 다음 세션부터 적용된다는 사실만 전달합니다. 설치 출력은 사용자 데이터 디렉터리의 `org-upgrade.log` 에 쌓이고, 성공했는지는 다음 세션에서 알려 줍니다. `sprag team status` 에서 최소 버전, 이 컴퓨터의 실행 버전, 마지막 결과를 볼 수 있습니다.
|
|
140
|
+
|
|
141
|
+
필요한 버전이 아직 게시되지 않았거나 전역 설치 위치에 관리자 권한이 필요해 실패하면, 최대 한 시간 뒤에 다시 시도하고 세션을 시작할 때 `sprag upgrade` 를 직접 실행하라고 안내합니다. git 체크아웃에서 실행한 사본은 스스로 업그레이드하지 않습니다.
|
|
142
|
+
|
|
125
143
|
## 업로드 스위치
|
|
126
144
|
|
|
127
145
|
`SPRAG_NO_TEAM_SYNC=1`(옛 이름 `CTS_NO_TEAM_SYNC` 도 계속 읽습니다)을 지정하면 모든 사용량 업로드가 멈춥니다. 참여한 컴퓨터는 스위치가 켜진 것을 처음 봤을 때와 다시 꺼졌을 때, 상태만 담은 호출 `member_set_sync` 를 한 번씩 보냅니다. 사용량 데이터는 들어 있지 않습니다. 다시 꺼진 뒤에는 바로 업로드합니다. 이 호출 덕분에 대시보드가 멈춘 컴퓨터와 연락이 끊긴 컴퓨터를 구분합니다. 멈춘 컴퓨터는 오너나 어드민이 내보내기 전까지 좌석을 유지합니다.
|
|
@@ -182,6 +200,7 @@ Free, 프로(좌석당 월 $5), 엔터프라이즈(좌석당 월 $10, 프롬프
|
|
|
182
200
|
|---|---|
|
|
183
201
|
| `<사용자 데이터 디렉터리>/team.json` | 참여 상태와 멤버 키(권한 0600) |
|
|
184
202
|
| `<사용자 데이터 디렉터리>/team-rules.json` | 마지막 동기화 때 받은 조직·팀 룰 |
|
|
203
|
+
| `<사용자 데이터 디렉터리>/org-upgrade.json`, `org-upgrade.log` | 조직 최소 버전 업그레이드의 상태와 설치 출력 |
|
|
185
204
|
| `<사용자 데이터 디렉터리>/prompts-offsets.json` | 프롬프트 업로더가 기록 파일마다 어디까지 읽었는지 적은 파일이며, 프롬프트 수집이 켜진 동안만 있습니다 |
|
|
186
205
|
| `~/.claude/ratchet-team.md` | Claude Code 용 승인된 조직·팀 룰이며 `~/.claude/CLAUDE.md` 에서 import 합니다 |
|
|
187
206
|
| `<CODEX_HOME>/ratchet-team.md` | Codex 용 같은 룰 |
|
package/docs/TEAM.md
CHANGED
|
@@ -10,10 +10,20 @@ After you join, Sprag uploads one row per local calendar day:
|
|
|
10
10
|
|
|
11
11
|
| Field | Meaning |
|
|
12
12
|
|---|---|
|
|
13
|
-
| Spend (USD) | priced from your local session logs |
|
|
13
|
+
| Spend (USD) | priced from your local session logs, including Claude desktop Cowork sessions |
|
|
14
14
|
| Savings (USD) | from the routing and doc2md ledgers |
|
|
15
|
-
| Delegated runs | how many runs were delegated that day |
|
|
15
|
+
| Delegated runs | how many Claude and Codex runs were delegated that day |
|
|
16
16
|
| Model-family share | the share of those runs that went to each model family |
|
|
17
|
+
| Spend by model family (USD) | the day's spend split by model family (`opus`, `sonnet`, `haiku`, `fable`, ...), so the console can show which models each person spends on; sent from 3.84.0 |
|
|
18
|
+
| Claude spend (USD) | Claude Code and Claude desktop Cowork local spend, main sessions plus subagent runs; the same figure as Spend (USD); sent from 3.84.0 |
|
|
19
|
+
| Codex spend (USD) | Codex local spend priced from the Codex rollout usage records, including compressed rollouts (`.jsonl.zst`) and the gateway's long-context tier prices, null when no price is known; sent from 3.84.0 |
|
|
20
|
+
| Gateway spend (USD) | the gateway's own daily spend for you when a LiteLLM gateway is configured, null when there is none or the call failed; sent from 3.84.0 |
|
|
21
|
+
| Gateway user hash | the first 16 hex characters of a hash of the gateway URL and your gateway user id, so one person with two machines is counted once; not reversible without the id; sent from 3.84.0 |
|
|
22
|
+
| Total spend (USD) | the gateway figure when known, otherwise Claude plus Codex; sent from 3.84.0 |
|
|
23
|
+
| Delegation cost (USD) | what the runs delegated by Sprag's model-fitting rules actually cost, Claude and Codex together; sent from 3.84.0 |
|
|
24
|
+
| Codex delegated runs and cost | the Codex share of the delegated runs and of their cost; sent from 3.84.0 |
|
|
25
|
+
| Subagent cost (USD) | the cost of every subagent run and Codex child session, rules or not; a secondary figure; sent from 3.84.0 |
|
|
26
|
+
| Unpriced parts | how many sessions or runs were left out because no price was known; sent from 3.84.0 |
|
|
17
27
|
| Sprag version | the installed version |
|
|
18
28
|
| Agent | `claude` or `codex` |
|
|
19
29
|
| Display name | the name you chose at join; the default is a random member ID such as `member-3f9a2c71`, created once per machine |
|
|
@@ -26,7 +36,7 @@ The daily aggregate upload runs at most once every 5 minutes after the last succ
|
|
|
26
36
|
|
|
27
37
|
While this machine is joined, the statusline shows a `team` chip with your member id and your animal from the virtual office (Sprag Town), for example `member-1e500474 🦊 Fox #3 of 12`, with your overall rank among the ranked people of the organization. The animal comes from the standing the full sync fetches every 5 minutes and stores in `team.json`; if the server does not offer it yet, or the last fetch is more than a day old, only the member id is shown. Rendering the chip reads local files only. It sits just before the version chip, and `--segments team` shows it on its own. IntelliJ's terminal font has no animal emoji, so there (narrow mode) and in text mode the chip drops the emoji and keeps the name: `member-1e500474 Fox #3 of 12`.
|
|
28
38
|
|
|
29
|
-
Destination: `https://hiycfjwswtkixyoqkznm.supabase.co/rest/v1/rpc/*` (Supabase, region ap-northeast-2). The calls are the RPCs `team_join`, `ledger_upsert`, `team_rules_get`, `team_rule_propose`, `team_leave`, `prompt_chunk_put` (Enterprise prompt capture only), `member_set_sync` (the upload-switch status call, see "The upload switch") `member_set_info` (OS name and version; the `arch` argument is always empty), `member_set_name` (only when you run `sprag team name`) and `member_standing` (your own office animal and rank for the statusline chip; it returns nobody else's figures); `sprag team create` also calls `team_create` with your sign-in session.
|
|
39
|
+
Destination: `https://hiycfjwswtkixyoqkznm.supabase.co/rest/v1/rpc/*` (Supabase, region ap-northeast-2). The calls are the RPCs `team_join`, `ledger_upsert`, `team_rules_get`, `team_rule_propose`, `team_leave`, `prompt_chunk_put` (Enterprise prompt capture only), `member_set_sync` (the upload-switch status call, see "The upload switch") `member_set_info` (OS name and version; the `arch` argument is always empty), `member_set_name` (only when you run `sprag team name`) and `member_standing` (your own office animal and rank for the statusline chip; it returns nobody else's figures). When a LiteLLM gateway is configured, each daily sync also calls the gateway's `GET /user/info` and `GET /global/spend/logs` with your own key to read the gateway's daily spend for you; nothing else is read and the key is never stored. Claude desktop Cowork transcripts under `~/Library/Application Support/Claude-3p/local-agent-mode-sessions` are read locally to price them; only the daily sums leave the machine, and task names and prompts are not sent. `sprag team status --show-payload` prints the exact rows. `sprag team create` also calls `team_create` with your sign-in session.
|
|
30
40
|
|
|
31
41
|
## Create a team from the CLI
|
|
32
42
|
|
|
@@ -123,6 +133,14 @@ A machine holds one seat per organization. When it joins again, with `sprag team
|
|
|
123
133
|
|
|
124
134
|
Create a team inside an organization you administer from the CLI with `sprag team create --org <org-id>`; without `--org` the server refuses, because only Sprag opens organizations. The command prints the organization name and how many seats are used. `sprag team status` shows the organization name.
|
|
125
135
|
|
|
136
|
+
## Organization minimum version
|
|
137
|
+
|
|
138
|
+
The Sprag operator can set a minimum Sprag version for an organization in the ops console (sprag.io/ops/); owners and admins cannot. The machines pick it up with the team rules, about once an hour.
|
|
139
|
+
|
|
140
|
+
A machine in that organization that runs an older version upgrades itself at the next session start, in the background and without asking. This is the one case where Sprag installs a package without a question; every other upgrade still waits for your consent. The model is only told that the upgrade started and that the new version applies from the next session. The install output goes to `org-upgrade.log` in the user data directory, and the next session reports whether it worked. `sprag team status` shows the minimum, the version this machine runs and the last result.
|
|
141
|
+
|
|
142
|
+
If the upgrade fails, for example because the required version is not published yet or the global install location needs administrator rights, Sprag tries again after an hour at most, and the session start tells you to run `sprag upgrade` yourself. A copy that runs from a git checkout never upgrades itself.
|
|
143
|
+
|
|
126
144
|
## The upload switch
|
|
127
145
|
|
|
128
146
|
`SPRAG_NO_TEAM_SYNC=1` (the old name `CTS_NO_TEAM_SYNC` is still read) stops every usage upload. A joined machine sends one status-only call, `member_set_sync`, with no usage data, the first time it sees the switch on, and one more when it is off again. After that it uploads immediately. That call is how the dashboard can tell a paused machine from a silent one. A paused machine keeps its seat until an owner or admin removes it.
|
|
@@ -183,6 +201,7 @@ Owners and admins of an Enterprise organization get a Prompts tab on sprag.io/te
|
|
|
183
201
|
|---|---|
|
|
184
202
|
| `<user data dir>/team.json` | Membership state and the member key (mode 0600) |
|
|
185
203
|
| `<user data dir>/team-rules.json` | Organization and team rules pulled at the last sync |
|
|
204
|
+
| `<user data dir>/org-upgrade.json`, `org-upgrade.log` | State and install output of the organization minimum-version upgrade |
|
|
186
205
|
| `<user data dir>/prompts-offsets.json` | Where the prompt uploader stopped in each transcript; exists only while prompt capture is on |
|
|
187
206
|
| `~/.claude/ratchet-team.md` | Approved organization and team rules for Claude Code, imported from `~/.claude/CLAUDE.md` |
|
|
188
207
|
| `<CODEX_HOME>/ratchet-team.md` | The same rules for Codex |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sprag-cli",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.85.0",
|
|
4
4
|
"description": "Model-delegation router for Claude Code and Codex: lookups, checks and test runs go to cheaper models, documents go in as compact Markdown, and a live statusline shows spend and savings.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -10,7 +10,10 @@ import { codexCachePolicy } from './cache.js';
|
|
|
10
10
|
import { PRICE_MAX_AGE_MS, gatewayPrices } from '../gateway-prices.js';
|
|
11
11
|
import { OPENAI_LIST_PRICES, OPENAI_PRICES_CHECKED_AT } from '../openai-prices.js';
|
|
12
12
|
|
|
13
|
-
export { PRICE_MAX_AGE_MS, rate, deploymentPrice, gatewayPrices, codexRunCost } from '../gateway-prices.js';
|
|
13
|
+
export { PRICE_MAX_AGE_MS, rate, deploymentPrice, gatewayPrices, codexRunCost, priceForPrompt, codexRequestCost } from '../gateway-prices.js';
|
|
14
|
+
|
|
15
|
+
// 2 adds long-context tiers to each price; a schema-1 table has none, so it is refreshed once.
|
|
16
|
+
export const CODEX_PRICES_SCHEMA = 2;
|
|
14
17
|
|
|
15
18
|
export const CACHE_POLICY_MAX_AGE_MS = 300000;
|
|
16
19
|
const OPENAI_POLICY = 'https://developers.openai.com/api/docs/guides/prompt-caching#cache-lifetime';
|
|
@@ -124,7 +127,7 @@ export function readCodexPrices({ provider, now = Date.now(), ...opts } = {}) {
|
|
|
124
127
|
const snapshot = JSON.parse(readFileSync(cacheFile(provider, opts), 'utf8'));
|
|
125
128
|
if (!Number.isFinite(snapshot?.checkedAt) || snapshot.checkedAt > now || now - snapshot.checkedAt > PRICE_MAX_AGE_MS) return null;
|
|
126
129
|
if (!snapshot.prices || typeof snapshot.prices !== 'object') return null;
|
|
127
|
-
return { checkedAt: snapshot.checkedAt, provider: provider.name, base: provider.base, prices: snapshot.prices };
|
|
130
|
+
return { checkedAt: snapshot.checkedAt, provider: provider.name, base: provider.base, prices: snapshot.prices, pricesSchema: snapshot.pricesSchema ?? 1 };
|
|
128
131
|
} catch { return null; }
|
|
129
132
|
}
|
|
130
133
|
|
|
@@ -149,7 +152,7 @@ async function writeGatewaySnapshot(provider, { fetchImpl = fetch, execute, ...o
|
|
|
149
152
|
const now = opts.now ?? Date.now();
|
|
150
153
|
let prices = null;
|
|
151
154
|
try { prices = gatewayPrices(payload); } catch { /* Prices are optional; the policy stands alone. */ }
|
|
152
|
-
const snapshot = { checkedAt: now, models: gatewayCachePolicies(payload), prices };
|
|
155
|
+
const snapshot = { checkedAt: now, models: gatewayCachePolicies(payload), prices, pricesSchema: CODEX_PRICES_SCHEMA };
|
|
153
156
|
const file = cacheFile(provider, opts);
|
|
154
157
|
// Persist only policy and price fields, never raw model/info (which can contain secrets).
|
|
155
158
|
mkdirSync(join(opts.dir || userDataDir(), 'codex-cache-policy'), { recursive: true, mode: 0o700 });
|
|
@@ -58,6 +58,29 @@ export function recordCodexDocument(source, result, opts = {}) {
|
|
|
58
58
|
} catch { /* Accounting must not prevent document conversion. */ }
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
+
/**
|
|
62
|
+
* One `{ ts, usd }` per recorded document, reset marks NOT applied (the
|
|
63
|
+
* caller decides which mark governs): the team upload sums these by local
|
|
64
|
+
* day beside the Claude doc2md ledger. `usd` is null for an unpriced record.
|
|
65
|
+
*/
|
|
66
|
+
export function codexDocumentEvents(opts = {}) {
|
|
67
|
+
const out = [];
|
|
68
|
+
try {
|
|
69
|
+
const dir = ledgerDir(opts);
|
|
70
|
+
for (const file of readdirSync(dir).filter((name) => /^[a-f0-9]{64}\.json$/.test(name))) {
|
|
71
|
+
try {
|
|
72
|
+
const event = JSON.parse(readFileSync(join(dir, file), 'utf8'));
|
|
73
|
+
if (![1, 2].includes(event?.version) || !['pdf', 'pptx', 'xlsx', 'xls', 'docx', 'fig'].includes(event.ext)) continue;
|
|
74
|
+
const ts = event.version === 2 ? event.at : statSync(join(dir, file)).mtimeMs;
|
|
75
|
+
const s = event.saving;
|
|
76
|
+
const usd = event.version === 2 && s?.method === 'office-xml-vs-markdown-bytes/4' && Number.isFinite(s.usd) ? s.usd : null;
|
|
77
|
+
out.push({ ts, usd });
|
|
78
|
+
} catch { /* Ignore only the damaged record. */ }
|
|
79
|
+
}
|
|
80
|
+
} catch { /* No Codex document history yet. */ }
|
|
81
|
+
return out;
|
|
82
|
+
}
|
|
83
|
+
|
|
61
84
|
// Legacy records use mtime; new records retain their first priced observation.
|
|
62
85
|
export function codexDocumentTotals(opts = {}) {
|
|
63
86
|
const since = readResetMarks(opts?.dir ?? userDataDir())['codex-docs'];
|
package/src/codex/ledger.js
CHANGED
|
@@ -252,7 +252,8 @@ export async function refreshCodexLedger({ dir = userDataDir(), home, now = Date
|
|
|
252
252
|
const bindMap = new Map(readCodexBindings({ dir }).filter((b) => byId.has(b.id)).map((b) => [b.childSessionId, b.id]));
|
|
253
253
|
const closedAt = closedCodexRouteTimes({ dir });
|
|
254
254
|
const oldest = Math.min(...pending.map((r) => r.at));
|
|
255
|
-
const files = await discoverCodexSessionFiles({ home, days: Math.max(1, (now - oldest) / 86400000 + 1) });
|
|
255
|
+
const files = await discoverCodexSessionFiles({ home, days: Math.max(1, (now - oldest) / 86400000 + 1), compressed: true });
|
|
256
|
+
// Child cost stays an aggregate at base rates: the long-context tier is not applied (children are rarely above 272K).
|
|
256
257
|
let changed = false;
|
|
257
258
|
const seen = new Set();
|
|
258
259
|
for (const f of files.slice().reverse()) {
|
|
@@ -285,13 +286,17 @@ export async function refreshCodexLedger({ dir = userDataDir(), home, now = Date
|
|
|
285
286
|
const actual = rates && run.usageKnown ? codexRunCost(run.tokens, rates.to) : null;
|
|
286
287
|
const counterfactual = rates && run.usageKnown ? codexRunCost(run.tokens, rates.from) : null;
|
|
287
288
|
const usd = actual === null || counterfactual === null ? null : roundUsd(run.aborted ? -actual : counterfactual - actual);
|
|
289
|
+
// `cost` is what the child itself cost on the model it ran on, recorded
|
|
290
|
+
// beside the saving (an interrupted child spent it too), so the team
|
|
291
|
+
// upload can report delegation cost rather than only the saving.
|
|
292
|
+
const cost = actual === null ? null : roundUsd(actual);
|
|
288
293
|
const event = { ts: run.endedAt ?? route.at, parentSessionId: route.parentSessionId || run.parentThreadId || null,
|
|
289
294
|
childSessionId: run.sessionId, source: route.source, category: route.category ?? null, scope: route.scope ?? null,
|
|
290
295
|
...(route.source === 'shared' ? { tier: route.tier, sharedSignature: route.sharedSignature } : {}),
|
|
291
296
|
...(route.source === 'implementation' ? { tier: route.tier } : {}),
|
|
292
297
|
from: route.from, to, provider,
|
|
293
298
|
...(route.targetRoot !== undefined ? { targetRoot: route.targetRoot } : {}),
|
|
294
|
-
...(route.ruleCreatedAt !== undefined ? { ruleCreatedAt: route.ruleCreatedAt } : {}), tokens: run.tokens, calls: run.calls, toolErrors: run.toolErrors, usd, rates: usd === null ? null : rates,
|
|
299
|
+
...(route.ruleCreatedAt !== undefined ? { ruleCreatedAt: route.ruleCreatedAt } : {}), tokens: run.tokens, calls: run.calls, toolErrors: run.toolErrors, usd, cost, rates: usd === null ? null : rates,
|
|
295
300
|
priceCheckedAt: rates?.checkedAt ?? null, priceSource, complete: run.complete, ...(run.aborted ? { aborted: true } : {}) };
|
|
296
301
|
// A transient price outage must not erase a completed, unchanged priced run.
|
|
297
302
|
if (usd === null && sameRun && previous.complete && Number.isFinite(previous.usd) &&
|
|
@@ -302,6 +307,20 @@ export async function refreshCodexLedger({ dir = userDataDir(), home, now = Date
|
|
|
302
307
|
return ledger;
|
|
303
308
|
}
|
|
304
309
|
|
|
310
|
+
/**
|
|
311
|
+
* What a ledger event's child run cost, in USD: the recorded `cost`, or, for
|
|
312
|
+
* events written before the field existed, the same figure recomputed from
|
|
313
|
+
* the tokens and the rate they were priced at. null when neither is known.
|
|
314
|
+
*/
|
|
315
|
+
export function codexEventCost(e) {
|
|
316
|
+
if (Number.isFinite(e?.cost)) return e.cost;
|
|
317
|
+
if (e?.tokens && e.rates?.to) {
|
|
318
|
+
const usd = codexRunCost(e.tokens, e.rates.to);
|
|
319
|
+
return Number.isFinite(usd) ? roundUsd(usd) : null;
|
|
320
|
+
}
|
|
321
|
+
return null;
|
|
322
|
+
}
|
|
323
|
+
|
|
305
324
|
/**
|
|
306
325
|
* Signed totals over priced runs; unpriced runs are counted, never summed as zero.
|
|
307
326
|
* Runs before the `codex-routing` reset mark are left out of every figure,
|
package/src/codex/parser.js
CHANGED
|
@@ -328,23 +328,84 @@ export async function parseCodexTurns(filePath, { cutoffMs = -Infinity } = {}) {
|
|
|
328
328
|
return session;
|
|
329
329
|
}
|
|
330
330
|
|
|
331
|
-
/**
|
|
332
|
-
|
|
331
|
+
/**
|
|
332
|
+
* Rollout JSONL is a best-effort local format, not a stable Codex API.
|
|
333
|
+
*
|
|
334
|
+
* Usage comes from two record kinds. Current rollouts write a top-level
|
|
335
|
+
* `token_usage_record` per response (`payload.usage`, a `response_id`, the
|
|
336
|
+
* turn's model in `turn_context`); older ones only carry the cumulative
|
|
337
|
+
* `event_msg/token_count` snapshot, whose `total_token_usage.input_tokens` is
|
|
338
|
+
* 0 in many current files. A file with any usage record is summed from the
|
|
339
|
+
* records (duplicates by `response_id` dropped); only a file without them
|
|
340
|
+
* falls back to the snapshot deltas. Either way `totals.cacheCreation` holds
|
|
341
|
+
* the cache writes and `modelTotals` splits the totals by the model each
|
|
342
|
+
* request ran on, so a session that switched models is priced per model.
|
|
343
|
+
*/
|
|
344
|
+
export async function parseCodexSessionFile(filePath, { cutoffMs = -Infinity, keepRequests = false } = {}) {
|
|
333
345
|
const session = {
|
|
334
346
|
agent: 'codex', sessionId: null, filePath, projectDir: '', model: 'unknown',
|
|
335
347
|
startTime: null, endTime: null, requestCount: 0, totals: emptyTotals(),
|
|
336
348
|
maxContextPerRequest: 0, reasoningOutputTokens: 0, contextWindow: null,
|
|
337
349
|
lastContextTokens: null, rateLimits: null, lastActivity: null, effort: null,
|
|
338
|
-
cacheActivity: null,
|
|
350
|
+
cacheActivity: null, modelTotals: null, usageSource: 'token_count',
|
|
351
|
+
};
|
|
352
|
+
// Per-request rows let a caller apply long-context tiers, which depend on each request's own
|
|
353
|
+
// prompt size. Off by default: the Codex panel keeps parsed sessions in memory.
|
|
354
|
+
if (keepRequests) session.requests = [];
|
|
355
|
+
// `prompt` is the request's own prompt size, which picks the tier. `input` can be larger:
|
|
356
|
+
// a snapshot delta may merge several responses, so the token amounts stay what totals sum.
|
|
357
|
+
const addRequest = (ts, model, u, prompt = u.input) => {
|
|
358
|
+
if (!session.requests) return;
|
|
359
|
+
const cached = Math.min(u.input, u.cached);
|
|
360
|
+
session.requests.push({ ts, model, prompt, input: u.input, cached, cacheWrite: Math.min(Math.max(0, u.input - cached), u.cacheWrite), output: u.output });
|
|
339
361
|
};
|
|
340
362
|
const copied = forkedCopyFilter();
|
|
341
363
|
let previous = null;
|
|
364
|
+
// usage records: per-response rows, keyed by response id to drop repeats
|
|
365
|
+
const records = [];
|
|
366
|
+
const seenResponses = new Set();
|
|
367
|
+
const turnModel = new Map();
|
|
368
|
+
const turnCumulative = new Map();
|
|
369
|
+
let contextModel = null;
|
|
370
|
+
const addUsage = (totals, u) => {
|
|
371
|
+
const cached = Math.min(u.input, u.cached);
|
|
372
|
+
const written = Math.min(Math.max(0, u.input - cached), u.cacheWrite);
|
|
373
|
+
totals.input += u.input - cached - written;
|
|
374
|
+
totals.cacheRead += cached;
|
|
375
|
+
totals.cacheCreation += written;
|
|
376
|
+
totals.output += u.output;
|
|
377
|
+
};
|
|
342
378
|
for await (const line of transcriptLines(filePath)) {
|
|
343
379
|
let e;
|
|
344
380
|
try { e = JSON.parse(line); } catch { continue; }
|
|
345
381
|
const p = e?.payload;
|
|
346
382
|
if (!p || copied(e)) continue;
|
|
347
383
|
updateSnapshot(session, e);
|
|
384
|
+
if (e.type === 'turn_context' && typeof p.model === 'string') {
|
|
385
|
+
contextModel = p.model;
|
|
386
|
+
if (p.turn_id) turnModel.set(p.turn_id, p.model);
|
|
387
|
+
continue;
|
|
388
|
+
}
|
|
389
|
+
if (e.type === 'token_usage_record') {
|
|
390
|
+
const u = p.usage || p.turn_token_usage;
|
|
391
|
+
if (!Number.isSafeInteger(u?.input_tokens) || !Number.isSafeInteger(u?.output_tokens)) continue;
|
|
392
|
+
if (typeof p.response_id === 'string' && p.response_id) {
|
|
393
|
+
if (seenResponses.has(p.response_id)) continue;
|
|
394
|
+
seenResponses.add(p.response_id);
|
|
395
|
+
}
|
|
396
|
+
let usage = { input: count(u.input_tokens), cached: count(u.cached_input_tokens),
|
|
397
|
+
cacheWrite: count(u.cache_write_input_tokens), output: count(u.output_tokens), reasoning: count(u.reasoning_output_tokens) };
|
|
398
|
+
if (!p.usage && p.turn_id) {
|
|
399
|
+
// turn_token_usage is the turn's running total: only its growth is new.
|
|
400
|
+
const prev = turnCumulative.get(p.turn_id);
|
|
401
|
+
turnCumulative.set(p.turn_id, usage);
|
|
402
|
+
if (prev) usage = Object.fromEntries(Object.keys(usage).map((k) => [k, Math.max(0, usage[k] - prev[k])]));
|
|
403
|
+
}
|
|
404
|
+
const ts = Date.parse(e.timestamp);
|
|
405
|
+
const model = (p.turn_id && turnModel.get(p.turn_id)) || (typeof p.model === 'string' ? p.model : null) || contextModel || session.model;
|
|
406
|
+
records.push({ ts, model, ...usage });
|
|
407
|
+
continue;
|
|
408
|
+
}
|
|
348
409
|
if (e.type !== 'event_msg' || p.type !== 'token_count') continue;
|
|
349
410
|
if (!p.info) continue;
|
|
350
411
|
const info = p.info;
|
|
@@ -371,32 +432,58 @@ export async function parseCodexSessionFile(filePath, { cutoffMs = -Infinity } =
|
|
|
371
432
|
cached: Math.min(delta.input, delta.cached), written: Math.min(delta.input, delta.written) };
|
|
372
433
|
}
|
|
373
434
|
if (!Number.isFinite(ts) || ts < cutoffMs) continue;
|
|
374
|
-
|
|
375
|
-
session.
|
|
376
|
-
|
|
377
|
-
session.totals.
|
|
435
|
+
session.maxContextPerRequest = Math.max(session.maxContextPerRequest, count(info.last_token_usage?.input_tokens));
|
|
436
|
+
if (count(info.model_context_window)) session.contextWindow = info.model_context_window;
|
|
437
|
+
if (records.length) continue; // summed from the usage records below
|
|
438
|
+
addUsage(session.totals, { input: delta.input, cached: delta.cached, cacheWrite: delta.written, output: delta.output });
|
|
439
|
+
const perModel = (session.modelTotals ??= {})[session.model] ??= emptyTotals();
|
|
440
|
+
addUsage(perModel, { input: delta.input, cached: delta.cached, cacheWrite: delta.written, output: delta.output });
|
|
441
|
+
addRequest(ts, session.model, { input: delta.input, cached: delta.cached, cacheWrite: delta.written, output: delta.output },
|
|
442
|
+
count(info.last_token_usage?.input_tokens) || delta.input);
|
|
378
443
|
// Reasoning is a subset of output, just as cached input is a subset of input.
|
|
379
444
|
session.reasoningOutputTokens += Math.min(delta.output, delta.reasoning);
|
|
380
445
|
session.requestCount++;
|
|
381
446
|
session.startTime ??= new Date(ts);
|
|
382
447
|
session.endTime = new Date(ts);
|
|
383
|
-
|
|
384
|
-
|
|
448
|
+
}
|
|
449
|
+
if (records.length) {
|
|
450
|
+
// The snapshot path may have run before the first record appeared; the
|
|
451
|
+
// records are the whole truth for this file, so start over from them.
|
|
452
|
+
Object.assign(session, { totals: emptyTotals(), modelTotals: null, reasoningOutputTokens: 0, requestCount: 0, startTime: null, endTime: null, usageSource: 'token_usage_record' });
|
|
453
|
+
if (session.requests) session.requests = [];
|
|
454
|
+
for (const r of records) {
|
|
455
|
+
if (!Number.isFinite(r.ts) || r.ts < cutoffMs) continue;
|
|
456
|
+
if (!r.input && !r.output) continue;
|
|
457
|
+
addUsage(session.totals, r);
|
|
458
|
+
const perModel = (session.modelTotals ??= {})[r.model || 'unknown'] ??= emptyTotals();
|
|
459
|
+
addUsage(perModel, r);
|
|
460
|
+
addRequest(r.ts, r.model || 'unknown', r);
|
|
461
|
+
session.reasoningOutputTokens += Math.min(r.output, r.reasoning);
|
|
462
|
+
session.requestCount++;
|
|
463
|
+
session.startTime ??= new Date(r.ts);
|
|
464
|
+
session.endTime = new Date(r.ts);
|
|
465
|
+
}
|
|
385
466
|
}
|
|
386
467
|
return session;
|
|
387
468
|
}
|
|
388
469
|
|
|
389
|
-
export async function discoverCodexSessionFiles({ home = codexUserDir(), days = 30, excludeSessionPath } = {}) {
|
|
470
|
+
export async function discoverCodexSessionFiles({ home = codexUserDir(), days = 30, excludeSessionPath, compressed = false } = {}) {
|
|
390
471
|
const cutoff = Date.now() - days * 86400000;
|
|
391
472
|
const files = [];
|
|
392
473
|
const excluded = excludeSessionPath ? resolve(excludeSessionPath) : null;
|
|
474
|
+
// Off by default: src/team-prompts.js reads rollouts by byte offset and the rescan gate in
|
|
475
|
+
// src/codex/route-scan.js sums file sizes, so both must keep seeing only plain files.
|
|
476
|
+
const wanted = (name) => name.endsWith('.jsonl') || (compressed && name.endsWith('.jsonl.zst'));
|
|
393
477
|
async function walk(dir) {
|
|
394
478
|
let entries;
|
|
395
479
|
try { entries = await readdir(dir, { withFileTypes: true }); } catch { return; }
|
|
480
|
+
const names = new Set(entries.map((entry) => entry.name));
|
|
396
481
|
for (const entry of entries) {
|
|
397
482
|
const path = join(dir, entry.name);
|
|
398
483
|
if (entry.isDirectory()) await walk(path);
|
|
399
|
-
else if (entry.isFile() && entry.name
|
|
484
|
+
else if (entry.isFile() && wanted(entry.name) && resolve(path) !== excluded) {
|
|
485
|
+
// The live .jsonl wins over a compressed twin, or the session would count twice.
|
|
486
|
+
if (entry.name.endsWith('.zst') && names.has(entry.name.slice(0, -4))) continue;
|
|
400
487
|
try {
|
|
401
488
|
const s = await stat(path);
|
|
402
489
|
if (s.mtimeMs >= cutoff) files.push({ path, mtime: s.mtimeMs, size: s.size });
|
|
@@ -415,7 +502,7 @@ export async function parseAllCodexSessions(options = {}) {
|
|
|
415
502
|
const results = [];
|
|
416
503
|
for (let i = 0; i < files.length; i += 10) {
|
|
417
504
|
const batch = await Promise.all(files.slice(i, i + 10).map(async ({ path }) => {
|
|
418
|
-
try { return await parseCodexSessionFile(path, { cutoffMs }); } catch { return null; }
|
|
505
|
+
try { return await parseCodexSessionFile(path, { cutoffMs, keepRequests: options.keepRequests }); } catch { return null; }
|
|
419
506
|
}));
|
|
420
507
|
results.push(...batch.filter((s) => s?.requestCount && (!options.projectFilter || s.projectDir.includes(options.projectFilter))));
|
|
421
508
|
}
|
package/src/commands/codex.js
CHANGED
|
@@ -594,6 +594,8 @@ export async function run({ args, version }) {
|
|
|
594
594
|
return;
|
|
595
595
|
}
|
|
596
596
|
if (cmd === 'upgrade') {
|
|
597
|
+
// The organization minimum version: the Codex session-start hook starts this detached.
|
|
598
|
+
if (hasFlag('--org-policy')) return (await import('./upgrade.js')).run({ hasFlag, version, agent: 'codex' });
|
|
597
599
|
const { upgradeInstructions } = await import('../update-notice.js');
|
|
598
600
|
const [command, setup] = upgradeInstructions('codex');
|
|
599
601
|
if (!hasFlag('--print')) throw new Error(`For a Codex-only upgrade, run ${command}, then sprag install --agent codex.`);
|
|
@@ -385,7 +385,7 @@ export async function run({ args, hasFlag, numArg }) {
|
|
|
385
385
|
// statusline's 24h: releases can land several times a day, and a
|
|
386
386
|
// session opened that afternoon should hear about them. It lands in
|
|
387
387
|
// time for the statusline and for the next session, not for this line.
|
|
388
|
-
if (pkgVersion) updateBlock = updateOffer(pkgVersion, { lang });
|
|
388
|
+
if (pkgVersion) updateBlock = updateOffer(pkgVersion, { agent: 'claude', lang });
|
|
389
389
|
} catch (e) { debug('route-scan:update-check', e); /* the offer is optional */ }
|
|
390
390
|
|
|
391
391
|
if (open.length === 0 && reviewRules.length === 0) {
|
package/src/commands/team.js
CHANGED
|
@@ -13,6 +13,7 @@ import { readFileSync } from 'node:fs';
|
|
|
13
13
|
import { userLanguage } from '../config.js';
|
|
14
14
|
import { pendingPrompts } from '../team-prompts.js';
|
|
15
15
|
import { memberId } from '../member-id.js';
|
|
16
|
+
import { orgMinVersion, readOrgUpgrade, orgUpgradeInFlight } from '../org-upgrade.js';
|
|
16
17
|
import {
|
|
17
18
|
loadTeamState, deviceInfo, isJoined, joinTeam, leaveTeam, syncTeam, autoJoin, aggregateDaily, rpc,
|
|
18
19
|
teamRulesCachePath, teamSyncDisabled, requestSignInCode, verifySignInCode, createTeam, isSeatLimitError, isOrgExpiredError,
|
|
@@ -54,6 +55,10 @@ const T = {
|
|
|
54
55
|
lastSync: (t, n) => `Last sync: ${t} (${n} rows)`,
|
|
55
56
|
neverSynced: 'Last sync: never',
|
|
56
57
|
lastError: 'Last error',
|
|
58
|
+
orgMin: (min, cur) => `Organization minimum version: v${min} (this machine runs v${cur})`,
|
|
59
|
+
orgUpgradeRunning: (t) => `Organization upgrade to v${t} is running in the background (log: org-upgrade.log)`,
|
|
60
|
+
orgUpgradeOk: (t, when) => `Last organization upgrade: v${t} installed (${when})`,
|
|
61
|
+
orgUpgradeFailed: (t, when, e) => `Last organization upgrade: v${t} failed (${when}): ${e}. Run sprag upgrade yourself.`,
|
|
57
62
|
on: 'on', off: 'off',
|
|
58
63
|
lastPrompts: (t, n) => `Last prompt upload: ${t} (${n} prompts)`,
|
|
59
64
|
noPrompts: 'Last prompt upload: never',
|
|
@@ -124,6 +129,10 @@ const T = {
|
|
|
124
129
|
lastSync: (t, n) => `마지막 동기화: ${t} (${n}행)`,
|
|
125
130
|
neverSynced: '마지막 동기화: 아직 없음',
|
|
126
131
|
lastError: '마지막 오류',
|
|
132
|
+
orgMin: (min, cur) => `조직 최소 버전: v${min} (이 컴퓨터는 v${cur} 실행 중)`,
|
|
133
|
+
orgUpgradeRunning: (t) => `조직 정책에 따라 v${t} 로 백그라운드 업그레이드를 진행 중입니다 (로그: org-upgrade.log)`,
|
|
134
|
+
orgUpgradeOk: (t, when) => `마지막 조직 업그레이드: v${t} 설치 완료 (${when})`,
|
|
135
|
+
orgUpgradeFailed: (t, when, e) => `마지막 조직 업그레이드: v${t} 설치 실패 (${when}): ${e}. sprag upgrade 를 직접 실행하십시오.`,
|
|
127
136
|
on: '켜짐', off: '꺼짐',
|
|
128
137
|
lastPrompts: (t, n) => `마지막 프롬프트 업로드: ${t} (${n}건)`,
|
|
129
138
|
noPrompts: '마지막 프롬프트 업로드: 아직 없음',
|
|
@@ -316,6 +325,17 @@ export async function run({ args, hasFlag, getArg, version, fetch, interactive,
|
|
|
316
325
|
if (MACHINE_NAME_RE.test(String(st.displayName || ''))) out(` ${m.nameHint}`);
|
|
317
326
|
out(st.lastSyncAt ? m.lastSync(new Date(st.lastSyncAt).toLocaleString(), st.lastSyncRows || 0) : m.neverSynced);
|
|
318
327
|
if (st.lastError) out(isOrgExpiredError(st.lastError) ? m.orgExpired : `${m.lastError}: ${st.lastError}`);
|
|
328
|
+
if (orgMinVersion(st)) out(m.orgMin(orgMinVersion(st), version));
|
|
329
|
+
{
|
|
330
|
+
const up = readOrgUpgrade();
|
|
331
|
+
if (up.target) {
|
|
332
|
+
if (orgUpgradeInFlight(up)) out(m.orgUpgradeRunning(up.target));
|
|
333
|
+
else if (Number.isFinite(up.finishedAt)) {
|
|
334
|
+
const when = new Date(up.finishedAt).toLocaleString();
|
|
335
|
+
out(up.ok ? m.orgUpgradeOk(up.target, when) : m.orgUpgradeFailed(up.target, when, up.error || '-'));
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
319
339
|
if (hasFlag('--show-payload')) {
|
|
320
340
|
out(`device: ${JSON.stringify(st.deviceInfo || deviceInfo())}`);
|
|
321
341
|
out(JSON.stringify(await aggregateDaily(), null, 2));
|