sprag-cli 3.97.0 → 3.97.1
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/docs/TEAM.ko.md +1 -1
- package/docs/TEAM.md +1 -1
- package/package.json +1 -1
- package/src/gateway-spend.js +89 -12
- package/src/team-sync.js +4 -3
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 /
|
|
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.
|
|
3
|
+
"version": "3.97.1",
|
|
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": {
|
package/src/gateway-spend.js
CHANGED
|
@@ -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
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
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
|
-
* @
|
|
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
|
|
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,
|
|
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 });
|