sprag-cli 3.97.0 → 3.97.2

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/README.ko.md CHANGED
@@ -43,6 +43,8 @@
43
43
 
44
44
  세션 분석은 로컬에서 실행하므로 추가 모델 호출이나 API 키가 필요하지 않습니다. Codex의 선택 기능인 예산·단가 조회는 기존 인증 정보로 사용자가 설정한 LiteLLM에 접속합니다. CLI는 Node.js 20 이상과 TOML 파서 하나를 사용합니다.
45
45
 
46
+ 무료 CLI는 사용자를 알아볼 수 있는 데이터를 보내지 않고 계정도 필요 없습니다. Pro는 팀에 참여한 컴퓨터만 하루 단위 숫자를 올리고, Enterprise는 어드민이 켠 팀에 한해 가림 처리한 프롬프트를 더합니다. 플랜별 전체 항목과 근거 파일은 [Sprag 이 보내는 데이터](docs/DATA.ko.md)에 있습니다.
47
+
46
48
  ```bash
47
49
  npm i -g sprag-cli # Claude Code용이며, Codex가 설치되어 있으면 Codex도 함께 설정합니다
48
50
  ```
@@ -226,6 +228,7 @@ Codex에는 기본 훅과 `AGENTS.md` 하네스, 범위별 래칫 규칙, 한국
226
228
  |---|---|
227
229
  | [Codex](https://sprag.io/docs/ko/codex/) | 설치, 패널, 기본 훅, 자동 후보, 프리셋, 집계 한계 |
228
230
  | [설치와 기본 설정](https://github.com/rootstudioyaml/sprag/blob/main/docs/INSTALL.ko.md) | 설치 직후 켜지는 기능, 직접 켜야 하는 기능, 끄는 방법 |
231
+ | [Sprag 이 보내는 데이터](https://sprag.io/docs/ko/data/) | 오픈소스, Pro, Enterprise 플랜별로 밖으로 나가는 항목, 볼 수 있는 사람, 끄는 방법 |
229
232
  | [statusline](https://github.com/rootstudioyaml/sprag/blob/main/docs/STATUSLINE.ko.md) | 세그먼트 의미, 경고 칩, 토큰 급증 원인 코드, 업데이트 안내 |
230
233
  | [명령](https://github.com/rootstudioyaml/sprag/blob/main/docs/COMMANDS.ko.md) | 전체 서브커맨드와 CLI 옵션 |
231
234
  | [Harness](https://github.com/rootstudioyaml/sprag/blob/main/docs/HARNESS.ko.md) | 5원칙, 래칫 승격, compact-window 고정, seed 프리셋 |
@@ -303,6 +306,7 @@ Sprag 은 켜지 않으면 로컬에서만 동작합니다. `sprag team join <
303
306
  `SPRAG_NO_TEAM_SYNC=1` 은 팀 관련 통신을 모두 끄고, `sprag team leave` 는 참여를 해제합니다.
304
307
 
305
308
  - [팀 기능 안내](docs/TEAM.ko.md)
309
+ - [플랜별 전송 데이터 안내](docs/DATA.ko.md)
306
310
  - 오너와 어드민용 팀 콘솔: https://sprag.io/team/
307
311
  - 플랜 안내: https://sprag.io/license/
308
312
 
package/README.md CHANGED
@@ -57,6 +57,8 @@ No extra model calls or API key are needed for analysis. Optional Codex gateway
57
57
  budget and price lookups contact your configured LiteLLM endpoint using its
58
58
  existing credentials. The CLI requires Node.js 20+ and one TOML parser dependency.
59
59
 
60
+ The free CLI sends nothing that identifies you and needs no account. Pro uploads daily figures only from computers that joined a team, and Enterprise adds masked prompt capture only for teams an admin switched on. [What Sprag sends](docs/DATA.md) lists every item by plan, with the source file behind it.
61
+
60
62
  ```bash
61
63
  npm i -g sprag-cli # Claude Code, plus Codex when it is installed
62
64
  ```
@@ -280,6 +282,7 @@ Every subcommand, flag and the output-language setting: [command reference](http
280
282
  |---|---|
281
283
  | [Codex](https://sprag.io/docs/codex/) | Installation, panel, native hooks, automatic candidates, presets, and accounting limits |
282
284
  | [Install](https://github.com/rootstudioyaml/sprag/blob/main/docs/INSTALL.md) | What the install turns on, what stays manual, how to turn each part off |
285
+ | [What Sprag sends](https://sprag.io/docs/data/) ([한국어](https://sprag.io/docs/ko/data/)) | Every outbound item by plan (open source, Pro, Enterprise), who can see it, and how to turn it off |
283
286
  | [Statusline](https://github.com/rootstudioyaml/sprag/blob/main/docs/STATUSLINE.md) | Segments, warning chips, spike issue codes, update notifications |
284
287
  | [Commands](https://github.com/rootstudioyaml/sprag/blob/main/docs/COMMANDS.md) | Full CLI surface |
285
288
  | [Harness](https://github.com/rootstudioyaml/sprag/blob/main/docs/HARNESS.md) | The five principles, rule promotion, compact-window pinning, seed presets |
@@ -357,6 +360,7 @@ Sprag stays local unless you opt in. With `sprag team join <token>` (or `SPRAG_T
357
360
  `SPRAG_NO_TEAM_SYNC=1` turns all team traffic off, and `sprag team leave` removes the membership.
358
361
 
359
362
  - [Team layer guide](docs/TEAM.md)
363
+ - [What Sprag sends, by plan](docs/DATA.md)
360
364
  - Team console for owners and admins: https://sprag.io/team/
361
365
  - Plans: https://sprag.io/license/
362
366
 
@@ -0,0 +1,163 @@
1
+ # Sprag 이 보내는 데이터
2
+
3
+ [← README](../README.ko.md) · [English](./DATA.md)
4
+
5
+ 이 문서는 오픈소스 CLI, Pro, Enterprise 를 쓸 때 컴퓨터에서 무엇이 나가는지 플랜별로 정리합니다. 모든 항목은 이 저장소의 코드와 대조할 수 있도록 근거 파일을 함께 적었습니다. 확인 기준은 sprag-cli 3.97 입니다.
6
+
7
+ ## 요약
8
+
9
+ - **오픈소스(무료 CLI)**: 사용자를 알아볼 수 있는 데이터는 Sprag 서버로 가지 않습니다. 계정도 없습니다. 밖으로 나가는 요청은 새 버전 확인과 공개 프리셋 확인 같은 익명 조회뿐이며, 요청 본문에 사용 기록이나 식별자가 없습니다.
10
+ - **Pro**: 팀에 참여한 컴퓨터만 하루에 한 행씩 숫자 집계를 올립니다. 지출, 절감액, 위임 횟수 같은 값입니다. 프롬프트, 코드, 파일 경로, 프로젝트 이름은 올라가지 않습니다.
11
+ - **Enterprise**: Pro 와 같은 집계를 올립니다. 조직 오너나 어드민이 팀별로 프롬프트 수집을 켠 경우에만 사용자가 직접 입력한 프롬프트가 추가로 올라갑니다. 비밀값과 개인정보는 업로드 전에 사용자 컴퓨터에서 가립니다. 켜기 전에 쓴 기록은 올리지 않습니다.
12
+
13
+ 팀 기능은 `sprag team join` 을 실행하거나 조직이 `SPRAG_TEAM_TOKEN` 을 배포해야 켜집니다. 그 전까지는 Pro 나 Enterprise 계약이 있어도 컴퓨터가 집계를 보내지 않습니다.
14
+
15
+ ## 한눈에 보기
16
+
17
+ | 데이터 | 오픈소스 | Pro | Enterprise |
18
+ |---|---|---|---|
19
+ | 프롬프트 본문 | 보내지 않음 | 보내지 않음 | 수집을 켠 팀만, 가림 처리 후 |
20
+ | 어시스턴트 답변, 도구 출력 | 보내지 않음 | 보내지 않음 | 보내지 않음 |
21
+ | 소스 코드, 파일 내용 | 보내지 않음 | 보내지 않음 | 보내지 않음 (프롬프트에 직접 붙여 넣은 텍스트는 그 프롬프트에 포함) |
22
+ | 파일 경로, 프로젝트 전체 경로 | 보내지 않음 | 보내지 않음 | 보내지 않음 |
23
+ | 프로젝트 폴더 이름 | 보내지 않음 | 보내지 않음 | 수집한 프롬프트마다 경로의 마지막 폴더 이름 하나 |
24
+ | API 키, 토큰, 비밀번호 | 보내지 않음 | 보내지 않음 | 보내지 않음 (프롬프트에 섞인 키 모양 값은 업로드 전에 가림) |
25
+ | 호스트 이름, OS 사용자 이름 | 보내지 않음 | 보내지 않음 | 보내지 않음 |
26
+ | 이메일 주소 | 보내지 않음 | 대시보드에 로그인하는 오너와 어드민만 | Pro 와 같음 |
27
+ | 하루 단위 지출, 절감, 위임 횟수 | 보내지 않음 | 보냄 | 보냄 |
28
+ | OS 이름과 버전 | 보내지 않음 | 보냄 | 보냄 |
29
+ | 표시 이름 | 보내지 않음 | 보냄 (기본값은 무작위 ID) | 보냄 (기본값은 무작위 ID) |
30
+ | 위임 룰 요약 (숫자만) | 보내지 않음 | 보냄 | 보냄 |
31
+ | 룰 본문 | 보내지 않음 | `sprag team propose` 를 실행할 때만 | Pro 와 같음 |
32
+ | 익명 버전 확인, 프리셋 확인 | 요청만 | 요청만 | 요청만 |
33
+
34
+ ## 오픈소스 (무료 CLI)
35
+
36
+ Sprag 의 분석은 Claude Code 와 Codex 가 이미 컴퓨터에 남긴 세션 기록을 읽어서 합니다. statusline, route-scan, 절감 원장, doc2md 변환은 모두 로컬 파일만 씁니다. statusline 을 그리는 동안 네트워크를 기다리지도 않습니다. 아래 요청은 분리된 자식 프로세스가 보내고 화면은 캐시된 답만 읽습니다.
37
+
38
+ ### Sprag 이 보내는 익명 요청
39
+
40
+ | 목적지 | 시점 | 보내는 내용 | 끄는 방법 |
41
+ |---|---|---|---|
42
+ | npm 레지스트리의 `sprag-cli/latest` | 하루 한 번 안팎 | 요청만 보냅니다. 레지스트리 인증 토큰도 붙이지 않습니다 | `SPRAG_NO_UPDATE_CHECK=1` |
43
+ | `api.github.com/repos/rootstudioyaml/sprag/releases/tags/<버전>` | 새 버전이 보일 때만 | 요청만 보냅니다. 릴리스 핵심 세 줄을 받아 옵니다 | 위와 같음 |
44
+ | Sprag 프리셋 서버(Supabase)의 `presets_version`, `presets_published` | 최대 24시간에 한 번 | 요청만 보냅니다. 누구에게나 같은 공개 키를 쓰고 구성원 키나 기기 ID 는 붙이지 않습니다 | `SPRAG_NO_PRESET_SYNC=1` |
45
+
46
+ 프리셋 서버의 두 함수는 게시된 프리셋을 읽기만 하는 SQL 조회이며 요청한 쪽에 대해 아무것도 기록하지 않습니다. 받은 프리셋은 CLI 에 들어 있는 공개 키로 서명을 확인한 뒤에만 적용합니다. 다만 인터넷의 모든 요청과 마찬가지로 받는 서버에는 접속한 IP 주소가 보입니다.
47
+
48
+ 근거: `src/update-check.js`, `src/preset-sync.js`, `src/presets-source.js`
49
+
50
+ ### 사용자를 대신해 다른 곳으로 가는 요청
51
+
52
+ 다음 요청은 Sprag 서버로 가지 않습니다. 사용자가 이미 쓰고 있는 서비스에 사용자의 인증 정보로 접속합니다.
53
+
54
+ | 목적지 | 조건 | 내용 | 끄는 방법 |
55
+ |---|---|---|---|
56
+ | `api.anthropic.com/api/oauth/usage` | claude.ai 계정으로 로그인했고 요금제가 Pro 나 Max 가 아닐 때(Team, Enterprise 등). 예산 게이지를 그리는 데 씁니다 | Claude Code 가 저장한 로그인 토큰을 Anthropic 에만 보냅니다. 토큰은 메모리에서만 쓰고 파일이나 로그에 적지 않습니다 | `sprag mode no-oauth-budget` 또는 `SPRAG_OAUTH_BUDGET=0` |
57
+ | 사용자의 LiteLLM 게이트웨이 | `ANTHROPIC_BASE_URL` 이 게이트웨이를 가리킬 때 | 이미 쓰는 게이트웨이 키로 예산과 단가를 조회합니다. 키는 캐시 파일에 적지 않습니다 | `ANTHROPIC_BASE_URL` 해제 또는 예산 세그먼트 제거 |
58
+ | npm, PyPI | `sprag upgrade` 를 수락했거나 doc2md 변환기를 설치할 때 | 일반 패키지 설치입니다 | 설치를 거절합니다 |
59
+ | GitHub 이슈 또는 익명 Google Form | `sprag feedback` 을 직접 실행할 때만 | 입력한 메시지와 Sprag 버전, OS, Node.js 버전 | 명령을 실행하지 않으면 됩니다 |
60
+
61
+ 근거: `src/oauth-budget.js`, `src/litellm-budget.js`, `src/gateway-spend.js`, `src/commands/feedback.js`. 목적지 전체 목록은 [설치 안내의 네트워크 표](./INSTALL.ko.md#네트워크-접근)에 있습니다.
62
+
63
+ ## Pro
64
+
65
+ ### 언제부터 보내나
66
+
67
+ 컴퓨터는 두 경우에만 팀에 참여합니다. 사용자가 `sprag team join <토큰>` 을 실행하면 올라갈 항목 목록을 먼저 보여 주고 확인을 받습니다. 조직이 셸 프로필이나 Claude Code 관리 설정에 `SPRAG_TEAM_TOKEN` 을 넣어 두면 다음 세션에서 참여하고, 첫 세션에 팀 이름과 확인 명령을 한 줄로 알립니다.
68
+
69
+ ### 올라가는 것
70
+
71
+ 참여한 컴퓨터는 로컬 날짜마다 한 행을 올립니다. 업로드는 5분에 한 번 이하이고 한 번에 최근 30일까지 보냅니다.
72
+
73
+ - **금액**: Claude 지출, Codex 지출, 게이트웨이 지출, 총지출, 위임 비용, 서브에이전트 비용, 절감액(모두 USD), 모델 계열별 지출(`opus`, `sonnet` 같은 이름 단위)
74
+ - **횟수**: 위임 실행 횟수, 모델 계열 비중, 가격을 몰라 계산에서 뺀 건수
75
+ - **기기**: OS 이름과 버전(예: macOS 26), Sprag 버전, 에이전트 종류(`claude` 또는 `codex`), 표시 이름, 기기 ID
76
+ - **게이트웨이 사용자 해시**: LiteLLM 게이트웨이를 쓸 때만 보냅니다. 게이트웨이 주소와 사용자 ID 를 합쳐 해시한 값의 앞 16자리이며, 한 사람의 컴퓨터 두 대를 한 번만 세는 데 씁니다
77
+ - **위임 룰 요약**: 카테고리와 티어마다 위임 횟수, 실패율, 절감액, 상한, 시작일 같은 숫자만 담습니다
78
+
79
+ 표시 이름과 기기 ID 의 기본값은 컴퓨터마다 한 번 만드는 `member-3f9a2c71` 같은 무작위 값입니다. 예전에는 OS 로그인 이름을 썼지만 실명이 서버에 올라갈 수 있어 무작위 ID 로 바꿨습니다. 실명을 쓰고 싶으면 `sprag team name "이름"` 으로 직접 정합니다. CPU 아키텍처 칸은 서버 함수의 인자로 남아 있지만 항상 빈 값을 보냅니다.
80
+
81
+ 위임 룰 요약에는 허용 목록을 적용합니다. 원본 룰 파일에는 프로젝트 경로와 프롬프트 발췌가 들어 있어서, 요약은 정해진 키 12개에 숫자와 정해진 단어만 채운 새 객체로 다시 만듭니다. `test/team-rule-stats.test.js` 가 키 목록을 고정하고 경로나 예시 문장이 결과에 남지 않는지 검사합니다.
82
+
83
+ 근거: `src/team-sync.js` 의 `aggregateDaily`, `deviceInfo`, `src/member-id.js`, `src/team-rule-stats.js`
84
+
85
+ ### 받아 오는 것
86
+
87
+ 같은 동기화에서 조직이 승인한 룰과 조직 최소 버전, 대시보드 순위(statusline 의 `team` 칩)를 받아 옵니다. 조직 최소 버전보다 낮은 컴퓨터는 다음 세션에서 스스로 업그레이드합니다. Sprag 이 묻지 않고 패키지를 설치하는 경우는 이것 하나뿐입니다.
88
+
89
+ ### 누가 보나
90
+
91
+ 조직의 오너와 어드민은 sprag.io/team 에서 구성원별 하루 합계를 봅니다. 세션 내용이나 프롬프트는 볼 수 없습니다. Sprag 운영자는 지원과 결제 처리를 위해 운영 콘솔에서 조직 단위 합계와 좌석 상태를 봅니다.
92
+
93
+ ## Enterprise
94
+
95
+ Enterprise 는 Pro 의 집계를 그대로 올리고 프롬프트 수집 기능을 더합니다. 이 기능은 꺼진 상태로 시작합니다. 조직 오너나 어드민이 대시보드에서 팀마다 켜야 하고, 구성원은 `sprag team status` 에서 "프롬프트 수집: 켜짐" 여부를 확인할 수 있습니다.
96
+
97
+ ### 수집하는 것
98
+
99
+ 메인 Claude Code 세션과 Codex 세션에서 사용자가 직접 입력한 프롬프트만 올라갑니다. 프롬프트 하나마다 다음 세 값을 보냅니다.
100
+
101
+ - 입력한 시각
102
+ - 프로젝트 폴더 이름(경로의 마지막 부분 하나이며 전체 경로는 보내지 않습니다)
103
+ - 본문(최대 20,000자)
104
+
105
+ 프롬프트에 직접 붙여 넣은 텍스트는 본문에 포함됩니다. 회사 정책상 민감한 코드나 문서를 프롬프트에 붙여 넣는다면 이 점을 구성원에게 알려 주십시오.
106
+
107
+ ### 보내지 않는 것
108
+
109
+ 어시스턴트 답변, 도구 출력, Claude 가 읽은 파일 내용, 서브에이전트 기록, 슬래시 명령 래퍼, 시스템 알림, 로컬 경로, 백그라운드 작업 알림, 다른 에이전트가 보낸 메시지, `!` 로 실행한 셸 명령과 그 출력은 올라가지 않습니다. 기록 파일 경로도 보내지 않습니다. 파일을 구분할 때는 경로를 SHA-256 으로 해시한 값의 앞 16자리를 씁니다.
110
+
111
+ ### 업로드 전에 가리는 것
112
+
113
+ 가림은 업로드 전에 사용자 컴퓨터에서 처리합니다.
114
+
115
+ | 종류 | 바뀌는 표지 |
116
+ |---|---|
117
+ | API 키와 토큰 (`sk-...`, `sk-ant-...`, `ghp_...`, `github_pat_...`, `AKIA...`, `xox?-...`), `Bearer` 토큰, 개인 키 블록, `KEY=`, `TOKEN=`, `PASSWORD=`, `SECRET=` 꼴의 대입 | `[redacted]` |
118
+ | 이메일 주소 | `[redacted:email]` |
119
+ | 한국 전화번호 | `[redacted:phone]` |
120
+ | 주민등록번호 | `[redacted:rrn]` |
121
+ | 카드번호 | `[redacted:card]` |
122
+
123
+ 패턴은 코드 조각을 망가뜨리지 않는 쪽으로 맞췄습니다. 그래서 모양이 특이한 비밀값은 놓칠 수 있습니다. 비밀값은 프롬프트에 넣지 않는 것이 가장 안전합니다.
124
+
125
+ ### 과거 기록은 올리지 않습니다
126
+
127
+ 컴퓨터가 수집이 켜진 것을 처음 보면 모든 기록 파일의 현재 끝을 시작점으로 표시합니다. 그 뒤에 입력한 프롬프트만 올라가므로 정책이 닿기 전의 대화는 나가지 않습니다. 수집이 꺼지면 시작점 파일을 지우고, 다시 켜면 그 시점의 끝에서 새로 시작합니다. 꺼져 있던 동안 입력한 프롬프트도 나중에 올라가지 않습니다.
128
+
129
+ ### 누가 보나
130
+
131
+ 수집된 프롬프트는 그 조직의 오너와 어드민이 sprag.io/team 의 프롬프트 탭에서 봅니다. Sprag 운영자(슈퍼유저)도 지원과 장애 대응을 위해 운영 콘솔에서 같은 화면을 열 수 있습니다. 서버 함수 `prompt_access_check` 가 이 두 역할과 Enterprise 요금제만 통과시키며, Pro 조직에는 프롬프트 탭이 잠겨 있습니다.
132
+
133
+ 근거: `src/team-prompts.js`
134
+
135
+ ## 서버 보관과 보안
136
+
137
+ - **저장 위치**: Supabase 의 서울 리전(ap-northeast-2)
138
+ - **전송 구간**: Sprag 서버로 가는 요청은 모두 HTTPS 입니다
139
+ - **접근 경로**: 컴퓨터는 테이블에 직접 쓰지 못하고 정해진 서버 함수만 부릅니다. 각 함수는 멤버 키를 확인한 뒤 그 멤버의 행만 다룹니다. 대시보드는 행 단위 접근 제어로 자기 조직의 데이터만 보여 줍니다
140
+ - **멤버 키**: 사용자 데이터 디렉터리의 `team.json` 에 권한 0600 으로 보관합니다
141
+ - **보관 기간**: 조직을 닫은 뒤 30일 안에 조직 데이터를 지웁니다. 오너나 어드민이 제거한 컴퓨터를 "삭제"하면 그 컴퓨터의 사용 기록과 프롬프트가 바로 지워집니다
142
+ - **제3자 제공**: 데이터를 팔지 않습니다. 처리 위탁 업체는 [개인정보처리방침](https://sprag.io/privacy/)에 적었습니다
143
+ - **웹사이트**: sprag.io 에는 광고 쿠키와 분석 스크립트가 없습니다
144
+
145
+ ## 직접 확인하는 방법
146
+
147
+ `sprag team status --show-payload` 는 다음 동기화에서 올라갈 기기 정보, 하루 단위 행, 위임 룰 요약을 그대로 출력합니다. Enterprise 수집이 켜져 있으면 대기 중인 프롬프트 수와 예시 하나의 앞 80자도 보여 줍니다. 네트워크에 접속하지 않고 로컬에서만 계산합니다.
148
+
149
+ 모든 전송을 끄려면 아래 세 줄을 셸 프로필에 넣고 `sprag mode no-oauth-budget` 을 한 번 실행합니다.
150
+
151
+ ```bash
152
+ export SPRAG_NO_UPDATE_CHECK=1 # 버전 확인과 프리셋 확인
153
+ export SPRAG_NO_PRESET_SYNC=1 # 프리셋 확인
154
+ export SPRAG_NO_TEAM_SYNC=1 # 팀 업로드 전부
155
+ ```
156
+
157
+ `SPRAG_NO_TEAM_SYNC=1` 을 켠 컴퓨터는 팀에 참여해 있으면 "업로드를 멈췄다"는 상태 호출을 한 번 보냅니다. 사용량 데이터는 들어 있지 않으며 대시보드가 멈춘 컴퓨터와 연락이 끊긴 컴퓨터를 구분하는 데 씁니다. 팀에서 완전히 나가려면 `sprag team leave` 를 실행합니다.
158
+
159
+ CLI 코드는 Apache-2.0 라이선스로 공개되어 있습니다. 위에 적은 근거 파일을 직접 읽어 확인할 수 있고, 팀 기능의 세부 사항은 [팀 기능 안내](./TEAM.ko.md)에 있습니다.
160
+
161
+ ## 문의
162
+
163
+ 데이터 처리에 관한 질문과 열람, 정정, 삭제 요청은 support@sprag.io 로 보내 주십시오. 보안 취약점은 [SECURITY.md](../SECURITY.md) 의 절차로 알려 주십시오.
package/docs/DATA.md ADDED
@@ -0,0 +1,163 @@
1
+ # What Sprag sends
2
+
3
+ [← README](../README.md) · [한국어](./DATA.ko.md)
4
+
5
+ This page lists, plan by plan, what leaves your computer when you use the open-source CLI, Pro or Enterprise. Each item names the source file it comes from, so you can check it against the code in this repository. Checked against sprag-cli 3.97.
6
+
7
+ ## Summary
8
+
9
+ - **Open source (free CLI)**: nothing that identifies you goes to a Sprag server, and there is no account. The only outbound requests are anonymous lookups, such as checking for a new version and for the published presets. They carry no usage data and no identifier.
10
+ - **Pro**: only computers that joined a team upload, one row of numbers per day: spend, savings, delegation counts and similar figures. Prompts, code, file paths and project names are not sent.
11
+ - **Enterprise**: the same daily numbers as Pro. Prompts a person typed are added only when an organization owner or admin turns prompt capture on for a team. Secrets and personal data are masked on your computer before upload, and nothing written before capture was turned on is sent.
12
+
13
+ The team layer starts only when you run `sprag team join` or your organization deploys `SPRAG_TEAM_TOKEN`. Until then a computer sends no figures, even under a Pro or Enterprise contract.
14
+
15
+ ## At a glance
16
+
17
+ | Data | Open source | Pro | Enterprise |
18
+ |---|---|---|---|
19
+ | Prompt text | not sent | not sent | teams with capture on only, after masking |
20
+ | Assistant replies, tool output | not sent | not sent | not sent |
21
+ | Source code, file contents | not sent | not sent | not sent (text you paste into a prompt is part of that prompt) |
22
+ | File paths, full project paths | not sent | not sent | not sent |
23
+ | Project folder name | not sent | not sent | the last folder name of the path, once per captured prompt |
24
+ | API keys, tokens, passwords | not sent | not sent | not sent (key-shaped values inside a prompt are masked before upload) |
25
+ | Hostname, OS user name | not sent | not sent | not sent |
26
+ | Email address | not sent | owners and admins who sign in to the dashboard | same as Pro |
27
+ | Daily spend, savings, delegation counts | not sent | sent | sent |
28
+ | OS name and version | not sent | sent | sent |
29
+ | Display name | not sent | sent (a random ID by default) | sent (a random ID by default) |
30
+ | Delegation rule summary (numbers only) | not sent | sent | sent |
31
+ | Rule text | not sent | only when you run `sprag team propose` | same as Pro |
32
+ | Anonymous version and preset checks | the request only | the request only | the request only |
33
+
34
+ ## Open source (free CLI)
35
+
36
+ Sprag's analysis reads the session logs Claude Code and Codex already keep on your computer. The statusline, route-scan, the savings ledger and doc2md conversion all work on local files. The statusline never waits on the network: the requests below go out from a detached child process, and the screen reads only the cached answer.
37
+
38
+ ### Anonymous requests Sprag makes
39
+
40
+ | Destination | When | What is sent | Turn off |
41
+ |---|---|---|---|
42
+ | `sprag-cli/latest` on your npm registry | about once a day | the request only, without the registry auth token | `SPRAG_NO_UPDATE_CHECK=1` |
43
+ | `api.github.com/repos/rootstudioyaml/sprag/releases/tags/<version>` | only when a newer version exists | the request only; it fetches three highlights of that release | same switch |
44
+ | `presets_version` and `presets_published` on the Sprag preset server (Supabase) | at most once every 24 hours | the request only, with the public key every install shares; no member key and no device ID | `SPRAG_NO_PRESET_SYNC=1` |
45
+
46
+ The two preset functions are read-only SQL queries over the published presets, and they record nothing about the caller. A fetched preset bundle is applied only after its signature checks out against a public key built into the CLI. As with any request on the internet, the receiving server does see the IP address it came from.
47
+
48
+ Source: `src/update-check.js`, `src/preset-sync.js`, `src/presets-source.js`
49
+
50
+ ### Requests made on your behalf to other services
51
+
52
+ These never reach a Sprag server. They go to a service you already use, with your own credentials.
53
+
54
+ | Destination | Condition | Content | Turn off |
55
+ |---|---|---|---|
56
+ | `api.anthropic.com/api/oauth/usage` | signed in with a claude.ai account on a plan other than Pro or Max (Team, Enterprise and so on), to draw the budget gauge | the sign-in token Claude Code stored, sent to Anthropic only; it is used in memory and never written to a file or log | `sprag mode no-oauth-budget` or `SPRAG_OAUTH_BUDGET=0` |
57
+ | your LiteLLM gateway | `ANTHROPIC_BASE_URL` points at a gateway | budget and price lookups with the gateway key you already use; the key is not written to any cache file | unset `ANTHROPIC_BASE_URL` or drop the budget segment |
58
+ | npm, PyPI | you accept `sprag upgrade` or install the doc2md converter | an ordinary package install | decline the install |
59
+ | a GitHub issue or an anonymous Google Form | only when you run `sprag feedback` | the message you typed, plus Sprag version, OS and Node.js version | do not run the command |
60
+
61
+ Source: `src/oauth-budget.js`, `src/litellm-budget.js`, `src/gateway-spend.js`, `src/commands/feedback.js`. The full list of destinations is in the [network table of the install guide](./INSTALL.md#network-access).
62
+
63
+ ## Pro
64
+
65
+ ### When it starts
66
+
67
+ A computer joins a team in one of two ways. When you run `sprag team join <token>`, Sprag first prints the list of what will be uploaded and asks you to confirm. When your organization puts `SPRAG_TEAM_TOKEN` in a shell profile or in Claude Code's managed settings, the computer joins at the next session and the first session shows a one-line notice naming the team and the commands to inspect or stop it.
68
+
69
+ ### What goes up
70
+
71
+ A joined computer uploads one row per local calendar day, at most once every 5 minutes, covering up to the last 30 days.
72
+
73
+ - **Money**: Claude spend, Codex spend, gateway spend, total spend, delegation cost, subagent cost and savings (all USD), plus spend per model family (names such as `opus` and `sonnet`)
74
+ - **Counts**: delegated runs, the share of each model family, and the number of sessions left out because their price was unknown
75
+ - **Device**: OS name and version (for example macOS 26), Sprag version, agent (`claude` or `codex`), display name and device ID
76
+ - **Gateway user hash**: only with a LiteLLM gateway. The first 16 hex characters of a hash over the gateway address and your gateway user ID, used to count one person's two computers once
77
+ - **Delegation rule summary**: per category and tier, numbers only, such as delegation count, failure rate, savings, budgets and the start date
78
+
79
+ The default display name and device ID are a random value such as `member-3f9a2c71`, made once per computer. Earlier versions used the OS login name, which could put a real name on the server, so it was replaced with the random ID. If you want your name on the dashboard, set it yourself with `sprag team name "Name"`. The CPU architecture field remains an argument of the server function but is always sent empty.
80
+
81
+ The rule summary is built from an allowlist. The local rule file holds project paths and prompt excerpts, so each summary row is a new object whose 12 fixed keys are filled only with numbers and fixed words. `test/team-rule-stats.test.js` pins the key set and checks that no path or example text survives into the output.
82
+
83
+ Source: `aggregateDaily` and `deviceInfo` in `src/team-sync.js`, `src/member-id.js`, `src/team-rule-stats.js`
84
+
85
+ ### What comes down
86
+
87
+ The same sync pulls the rules your organization approved, the organization's minimum Sprag version, and your dashboard standing (the statusline `team` chip). A computer below the minimum version upgrades itself at the next session. That is the only case where Sprag installs a package without asking.
88
+
89
+ ### Who sees it
90
+
91
+ Organization owners and admins see each member's daily totals at sprag.io/team. They cannot see session contents or prompts. Sprag operators see organization-level totals and seat status in the operator console, for support and billing.
92
+
93
+ ## Enterprise
94
+
95
+ Enterprise uploads the same daily numbers as Pro and adds prompt capture. Capture starts switched off. An organization owner or admin turns it on per team in the dashboard, and every member can see whether it is on with `sprag team status` ("Prompt capture: on").
96
+
97
+ ### What is captured
98
+
99
+ Only prompts a person typed in their main Claude Code and Codex sessions. Each prompt carries three values:
100
+
101
+ - the time it was typed
102
+ - the project folder name (the last part of the path only, never the full path)
103
+ - the text (up to 20,000 characters)
104
+
105
+ Text pasted into a prompt is part of that prompt's text. If company policy treats some code or documents as sensitive, let members know before they paste them into a prompt.
106
+
107
+ ### What is never sent
108
+
109
+ Assistant replies, tool output, the contents of files Claude read, subagent transcripts, slash-command wrappers, system reminders, local paths, background-task notifications, messages from other agents, and `!` shell commands with their output. Transcript file paths are not sent either: a file is told apart by the first 16 hex characters of the SHA-256 of its path.
110
+
111
+ ### What is masked before upload
112
+
113
+ Masking happens on your computer, before upload.
114
+
115
+ | Kind | Replaced with |
116
+ |---|---|
117
+ | API keys and tokens (`sk-...`, `sk-ant-...`, `ghp_...`, `github_pat_...`, `AKIA...`, `xox?-...`), `Bearer` tokens, private key blocks, assignments shaped like `KEY=`, `TOKEN=`, `PASSWORD=`, `SECRET=` | `[redacted]` |
118
+ | Email addresses | `[redacted:email]` |
119
+ | Korean phone numbers | `[redacted:phone]` |
120
+ | Korean resident registration numbers | `[redacted:rrn]` |
121
+ | Card numbers | `[redacted:card]` |
122
+
123
+ The patterns are tuned not to mangle code snippets, so an unusually shaped secret can slip through. The safest place for a secret is outside the prompt.
124
+
125
+ ### History is never uploaded
126
+
127
+ The first time a computer sees capture switched on, it marks the current end of every transcript file as the starting point. Only prompts typed after that go up, so conversations from before the policy reached the computer never leave it. Switching capture off deletes the starting-point file, and switching it on again starts from the end of every file at that moment. Prompts typed while capture was off are never uploaded later.
128
+
129
+ ### Who sees it
130
+
131
+ Captured prompts are read by the organization's owners and admins in the Prompts tab at sprag.io/team. Sprag operators (superusers) can open the same view in the operator console for support and incident response. The server function `prompt_access_check` lets only these two roles through, and only on the Enterprise plan; Pro organizations see the tab locked.
132
+
133
+ Source: `src/team-prompts.js`
134
+
135
+ ## Storage and security on the server
136
+
137
+ - **Location**: Supabase, Seoul region (ap-northeast-2)
138
+ - **In transit**: every request to a Sprag server uses HTTPS
139
+ - **Access path**: computers cannot write tables directly; they call fixed server functions, and each function checks the member key and touches only that member's rows. The dashboard uses row-level access control, so each person sees only their own organization's data
140
+ - **Member key**: kept in `team.json` in the user data directory with mode 0600
141
+ - **Retention**: organization data is deleted within 30 days after the organization closes. When an owner or admin deletes a removed computer, that computer's usage history and prompts are erased at once
142
+ - **Third parties**: data is not sold. Processors are listed in the [privacy policy](https://sprag.io/privacy/)
143
+ - **Website**: sprag.io has no advertising cookies and no analytics scripts
144
+
145
+ ## Checking it yourself
146
+
147
+ `sprag team status --show-payload` prints the device info, daily rows and rule summary that the next sync would upload. With Enterprise capture on, it also shows how many prompts are waiting and the first 80 characters of one of them. It computes all of this locally, without touching the network.
148
+
149
+ To turn every request off, put these three lines in your shell profile and run `sprag mode no-oauth-budget` once.
150
+
151
+ ```bash
152
+ export SPRAG_NO_UPDATE_CHECK=1 # version check and preset check
153
+ export SPRAG_NO_PRESET_SYNC=1 # preset check
154
+ export SPRAG_NO_TEAM_SYNC=1 # every team upload
155
+ ```
156
+
157
+ A computer that has joined a team and sees `SPRAG_NO_TEAM_SYNC=1` sends one status call saying uploads are paused. It carries no usage data; the dashboard uses it to tell a paused computer from one that went quiet. To leave the team entirely, run `sprag team leave`.
158
+
159
+ The CLI code is open under the Apache-2.0 license. You can read the source files named above yourself, and the team layer is covered in detail in the [team guide](./TEAM.md).
160
+
161
+ ## Contact
162
+
163
+ Send questions about data handling, and requests to see, correct or delete your data, to support@sprag.io. Report security vulnerabilities through [SECURITY.md](../SECURITY.md).
package/docs/TEAM.ko.md CHANGED
@@ -53,7 +53,7 @@ Sprag 은 기본적으로 로컬에서만 동작합니다. 팀 기능은 켜야
53
53
 
54
54
  팀에 참여한 동안 statusline 에 `team` 칩이 나타나 멤버 ID 와 가상 사무실(Sprag 타운)에서 받은 동물을 보여 줍니다. 예를 들면 `member-1e500474 🦊 여우 12명 중 3위` 처럼 조직에서 순위에 오른 사람 가운데 몇 위인지도 함께 보여 줍니다. 동물은 5분마다 도는 전체 동기화가 서버에서 받아 `team.json` 에 저장한 순위로 정합니다. 서버가 아직 이 기능을 지원하지 않거나 마지막으로 받은 지 하루가 넘었다면 멤버 ID 만 표시합니다. 칩을 그릴 때는 로컬 파일만 읽습니다. IntelliJ 터미널은 글꼴에 동물 이모지가 없어 narrow 모드로 그리므로, 이때와 text 모드에서는 `member-1e500474 여우 12명 중 3위` 처럼 이모지 없이 이름만 보여 줍니다. 버전 칩 바로 앞에 놓이며, `--segments team` 으로 이 칩만 따로 볼 수 있습니다.
55
55
 
56
- 목적지는 `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_rules_report`(위 위임 룰 요약), `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` 를 실행하면 보내는 행을 그대로 볼 수 있습니다.
56
+ 목적지는 `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_rules_report`(위 위임 룰 요약), `member_standing`(statusline 칩에 쓸 본인의 사무실 동물과 순위만 받고 다른 사람의 수치는 받지 않음) 입니다. LiteLLM 게이트웨이를 설정했다면 하루 동기화마다 게이트웨이의 `GET /user/info` 와 `GET /spend/logs/v2` 도 본인 키로 호출해 본인의 하루 게이트웨이 지출을 읽습니다. 요청 시각을 로컬 날짜(한국 PC는 한국시간)로 묶어 합산하고, `/spend/logs/v2` 가 없는 게이트웨이에서는 UTC 날짜로 묶인 `GET /global/spend/logs` 를 대신 씁니다. 그 밖의 것은 읽지 않으며 키는 저장하지 않습니다. 비용을 계산하려고 `~/Library/Application Support/Claude-3p/local-agent-mode-sessions` 아래의 Claude 데스크톱 앱 Cowork 기록을 로컬에서 읽습니다. 밖으로 나가는 것은 하루 합계뿐이며 작업 이름과 프롬프트는 보내지 않습니다. `sprag team status --show-payload` 를 실행하면 보내는 행을 그대로 볼 수 있습니다.
57
57
 
58
58
  ## CLI에서 팀 만들기
59
59
 
package/docs/TEAM.md CHANGED
@@ -53,7 +53,7 @@ The daily aggregate upload runs at most once every 5 minutes after the last succ
53
53
 
54
54
  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`.
55
55
 
56
- 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`), `member_rules_report` (the delegation rule summary above) 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.
56
+ 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`), `member_rules_report` (the delegation rule summary above) 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 /spend/logs/v2` (or `GET /global/spend/logs` on gateways without it) with your own key to read the gateway's daily spend for you, summed by your local day from each request's time; 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.
57
57
 
58
58
  ## Create a team from the CLI
59
59
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sprag-cli",
3
- "version": "3.97.0",
3
+ "version": "3.97.2",
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": {
@@ -34,6 +34,8 @@
34
34
  "docs/CODEX.ko.md",
35
35
  "docs/TEAM.md",
36
36
  "docs/TEAM.ko.md",
37
+ "docs/DATA.md",
38
+ "docs/DATA.ko.md",
37
39
  "LICENSE",
38
40
  "NOTICE"
39
41
  ],
@@ -9,8 +9,11 @@
9
9
  *
10
10
  * GET {base}/key/info the key's user_id (404 on custom-auth deployments)
11
11
  * GET {base}/user/info user_info.user_id as the fallback
12
+ * GET {base}/spend/logs/v2 one row per request with its startTime, paged,
13
+ * for this user since the first local day asked
12
14
  * GET {base}/global/spend/logs rows {date, spend, api_key, user}; the most
13
- * recent 30 days, every user the key may see
15
+ * recent 30 days, every user the key may see;
16
+ * the fallback when v2 is missing or too large
14
17
  *
15
18
  * Only rows whose `user` is this user id are summed: an admin key sees
16
19
  * everyone's rows and summing them all would report the whole company as one
@@ -21,9 +24,11 @@
21
24
  * a file (same rule as litellm-budget.js). Failures are returned as
22
25
  * `{ error }`, never thrown: the upload goes on with local figures.
23
26
  *
24
- * `date` is the gateway's calendar day (UTC on the deployments measured), so
25
- * a day can differ from the local day by up to a few hours of traffic; range
26
- * sums are unaffected.
27
+ * The request rows are summed by the local calendar day, the key every other
28
+ * figure in the daily row uses (Korean time on the machines measured). The
29
+ * daily tables behind /global/spend/logs and /user/daily/activity only keep
30
+ * the UTC date, so they cannot be regrouped: a request at 08:00 KST lands on
31
+ * the previous day there. That fallback result carries `dayBasis: 'utc'`.
27
32
  */
28
33
 
29
34
  import { createHash } from 'node:crypto';
@@ -42,8 +47,12 @@ export function gatewayEnv(env = process.env) {
42
47
 
43
48
  export const GATEWAY_SPEND_TIMEOUT_MS = 15000;
44
49
  export const GATEWAY_SPEND_DAYS = 30;
50
+ export const GATEWAY_LOG_PAGE_SIZE = 1000;
51
+ /** 60 pages of 1,000 requests; past that the UTC daily totals are cheaper. */
52
+ export const GATEWAY_LOG_MAX_PAGES = 60;
45
53
 
46
54
  const DAY_RE = /^\d{4}-\d{2}-\d{2}/;
55
+ const KEY_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
47
56
 
48
57
  /** Local calendar day, same key as team-sync.js and stats.js. */
49
58
  function dayKey(ms) {
@@ -78,6 +87,34 @@ export function sumSpendRows(rows, userId) {
78
87
  return { days, earliest };
79
88
  }
80
89
 
90
+ /**
91
+ * Epoch ms of a spend log's startTime. The column is a timestamp without a
92
+ * zone holding UTC, so a value without an offset is read as UTC.
93
+ */
94
+ export function logStartMs(v) {
95
+ const s = String(v ?? '').trim();
96
+ if (!s) return NaN;
97
+ return Date.parse(/(?:[zZ]|[+-]\d{2}:?\d{2})$/.test(s) ? s : `${s.replace(' ', 'T')}Z`);
98
+ }
99
+
100
+ /** Sum `/spend/logs/v2` request rows for one user by local calendar day. */
101
+ export function sumLogRows(rows, userId) {
102
+ const days = new Map();
103
+ for (const r of rows) {
104
+ if (!r || typeof r !== 'object') continue;
105
+ if (String(r.user ?? '') !== String(userId)) continue;
106
+ const usd = Number(r.spend);
107
+ const ms = logStartMs(r.startTime);
108
+ if (!Number.isFinite(usd) || !Number.isFinite(ms)) continue;
109
+ const day = dayKey(ms);
110
+ days.set(day, (days.get(day) || 0) + usd);
111
+ }
112
+ return days;
113
+ }
114
+
115
+ /** UTC "YYYY-MM-DD HH:MM:SS", the form /spend/logs/v2 reads its window in. */
116
+ const utcStamp = (ms) => new Date(ms).toISOString().slice(0, 19).replace('T', ' ');
117
+
81
118
  /**
82
119
  * The gateway figure for one local day: a number inside the covered range (0
83
120
  * when the gateway has no row for it), null outside it or without a result.
@@ -89,21 +126,48 @@ export function gatewayDayValue(result, day) {
89
126
  }
90
127
 
91
128
  /**
92
- * @returns {Promise<null | { error: string } | { days: Map<string, number>, coveredFrom: string, coveredTo: string, userId: string, userHash: string }>}
129
+ * @param {object} [opts]
130
+ * @param {string} [opts.from] first local day (YYYY-MM-DD) the caller needs;
131
+ * request logs are read from there, never further back than 30 days
132
+ * @returns {Promise<null | { error: string } | { days: Map<string, number>, coveredFrom: string, coveredTo: string, dayBasis: 'local' | 'utc', userId: string, userHash: string }>}
93
133
  * null when no gateway is configured or the user id cannot be learned.
94
134
  */
95
- export async function fetchGatewayDailySpend({ env = process.env, fetchImpl = globalThis.fetch, now = Date.now(), timeoutMs = GATEWAY_SPEND_TIMEOUT_MS } = {}) {
135
+ export async function fetchGatewayDailySpend({ env = process.env, fetchImpl = globalThis.fetch, now = Date.now(), timeoutMs = GATEWAY_SPEND_TIMEOUT_MS, from = null } = {}) {
96
136
  const g = gatewayEnv(env);
97
137
  if (!g) return null;
98
138
  const { base, key } = g;
99
139
  const ctl = new AbortController();
100
140
  const timer = setTimeout(() => ctl.abort(), timeoutMs);
141
+ // The request logs get half the time, so a slow or huge log still leaves
142
+ // room for the daily totals.
143
+ const logCtl = new AbortController();
144
+ const logTimer = setTimeout(() => logCtl.abort(), Math.floor(timeoutMs / 2));
145
+ const stopLogs = () => logCtl.abort();
146
+ ctl.signal.addEventListener('abort', stopLogs);
101
147
  const headers = { accept: 'application/json', authorization: `Bearer ${key}` };
102
- const getJson = async (path) => {
103
- const res = await fetchImpl(`${base}${path}`, { signal: ctl.signal, headers, redirect: 'error' });
104
- if (!res.ok) throw new Error(`LiteLLM ${path} responded ${res.status}`);
148
+ const getJson = async (path, signal = ctl.signal) => {
149
+ const res = await fetchImpl(`${base}${path}`, { signal, headers, redirect: 'error' });
150
+ if (!res.ok) throw new Error(`LiteLLM ${path.split('?')[0]} responded ${res.status}`);
105
151
  return res.json();
106
152
  };
153
+ // Request rows summed by local day, or null when the log is over the page
154
+ // cap. Oldest first, so requests made while paging only add to the end.
155
+ const logDays = async (userId, fromKey) => {
156
+ const m = KEY_RE.exec(fromKey);
157
+ const startMs = new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3])).getTime();
158
+ const days = new Map();
159
+ for (let page = 1; page <= GATEWAY_LOG_MAX_PAGES; page++) {
160
+ const q = new URLSearchParams({
161
+ user_id: userId, start_date: utcStamp(startMs), end_date: utcStamp(now),
162
+ page: String(page), page_size: String(GATEWAY_LOG_PAGE_SIZE), sort_by: 'startTime', sort_order: 'asc',
163
+ });
164
+ const body = await getJson(`/spend/logs/v2?${q}`, logCtl.signal);
165
+ if (!body || !Array.isArray(body.data)) throw new Error('LiteLLM /spend/logs/v2 sent no data array');
166
+ for (const [day, usd] of sumLogRows(body.data, userId)) days.set(day, (days.get(day) || 0) + usd);
167
+ if (body.data.length < GATEWAY_LOG_PAGE_SIZE) return days;
168
+ }
169
+ return null;
170
+ };
107
171
  try {
108
172
  // Same order as pickBudgetSource: the key's own user id first, then the
109
173
  // user record. /key/info is 404 on custom-auth deployments; that is fine.
@@ -119,19 +183,32 @@ export async function fetchGatewayDailySpend({ env = process.env, fetchImpl = gl
119
183
  if (typeof id === 'string' && id) userId = id;
120
184
  }
121
185
  if (!userId) return null;
122
- const rows = await getJson('/global/spend/logs');
123
- const { days, earliest } = sumSpendRows(rows, userId);
124
186
  const coveredTo = dayKey(now);
125
187
  const windowStart = dayKey(now - (GATEWAY_SPEND_DAYS - 1) * 86400000);
188
+ const userHash = gatewayUserHash(base, userId);
189
+ const logFrom = KEY_RE.test(String(from || '')) && from > windowStart && from <= coveredTo ? from : windowStart;
190
+ let local = null;
191
+ try {
192
+ local = await logDays(userId, logFrom);
193
+ } catch (e) {
194
+ // The whole budget is spent: the daily totals would time out as well.
195
+ if (ctl.signal.aborted) throw e;
196
+ debug('gateway-spend:logs-v2', e);
197
+ }
198
+ if (local) return { days: local, coveredFrom: logFrom, coveredTo, dayBasis: 'local', userId, userHash };
199
+ const rows = await getJson('/global/spend/logs');
200
+ const { days, earliest } = sumSpendRows(rows, userId);
126
201
  // The response is the gateway's recent-30-day window. A day inside it with
127
202
  // no row is a day with no spend; the earliest row only widens the window
128
203
  // when the gateway sent more than 30 days.
129
204
  const coveredFrom = earliest && earliest < windowStart ? earliest : windowStart;
130
- return { days, coveredFrom, coveredTo, userId, userHash: gatewayUserHash(base, userId) };
205
+ return { days, coveredFrom, coveredTo, dayBasis: 'utc', userId, userHash };
131
206
  } catch (e) {
132
207
  debug('gateway-spend', e);
133
208
  return { error: e && e.name === 'AbortError' ? 'timeout' : String((e && e.message) || e) };
134
209
  } finally {
135
210
  clearTimeout(timer);
211
+ clearTimeout(logTimer);
212
+ ctl.signal.removeEventListener('abort', stopLogs);
136
213
  }
137
214
  }
package/src/team-sync.js CHANGED
@@ -895,14 +895,15 @@ export async function syncTeam({
895
895
  // price Claude the same way and both see the gateway figure.
896
896
  env = withClaudeSettingsEnv(env);
897
897
  const hasGateway = !!gatewayEnv(env);
898
- let gatewayDaily = null;
899
- if (hasGateway) gatewayDaily = await fetchGatewayDailySpend({ env, fetchImpl: gatewayFetch, now });
900
- const gatewayOk = !!(gatewayDaily && !gatewayDaily.error);
901
898
  // Days the delegation ledger changed after they were uploaded (a rescan
902
899
  // repriced them) go up again from the earliest one.
903
900
  let change = null;
904
901
  try { change = changedSinceForSync(); } catch (e) { debug('team-sync', e); }
905
902
  const win = ledgerWindow(state, now, { gateway: hasGateway, changedSince: change?.since });
903
+ // The gateway's request log is read only from the first day going up.
904
+ let gatewayDaily = null;
905
+ if (hasGateway) gatewayDaily = await fetchGatewayDailySpend({ env, fetchImpl: gatewayFetch, now, from: win.startKey });
906
+ const gatewayOk = !!(gatewayDaily && !gatewayDaily.error);
906
907
  let prices = codexPrices;
907
908
  if (prices === undefined) {
908
909
  const r = await codexPricesForSync({ dir, now, fetchImpl: gatewayFetch, attemptedAt: state.codexPricesAttemptAt });