sprag-cli 3.84.0 → 3.86.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 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,13 +10,13 @@ Sprag 은 기본적으로 로컬에서만 동작합니다. 팀 기능은 켜야
10
10
 
11
11
  | 항목 | 내용 |
12
12
  |---|---|
13
- | 지출(USD) | 로컬 세션 로그로 계산한 금액 |
13
+ | 지출(USD) | 로컬 세션 로그로 계산한 금액이며 Claude 데스크톱 앱의 Cowork 세션을 포함합니다 |
14
14
  | 절감(USD) | 라우팅 원장과 doc2md 원장에서 가져온 금액 |
15
15
  | 위임 실행 횟수 | 그날 위임한 Claude와 Codex 실행의 수 |
16
16
  | 모델 계열 비중 | 위임 실행 중 모델 계열별 비율 |
17
17
  | 모델 계열별 지출(USD) | 그날 지출을 모델 계열(`opus`, `sonnet`, `haiku`, `fable` 등)별로 나눈 금액입니다. 콘솔에서 사람마다 어느 모델에 돈을 쓰는지 보여 주는 데 쓰며, 3.84.0부터 보냅니다 |
18
- | Claude 지출(USD) | Claude Code 로컬 지출입니다. 메인 세션과 서브에이전트 실행을 합친 금액이며 지출(USD)과 같은 값입니다. 3.84.0부터 보냅니다 |
19
- | Codex 지출(USD) | Codex 롤아웃 사용량 기록으로 계산한 로컬 지출입니다. 가격을 모르면 비어 있습니다. 3.84.0부터 보냅니다 |
18
+ | Claude 지출(USD) | Claude Code와 Claude 데스크톱 앱 Cowork의 로컬 지출입니다. 메인 세션과 서브에이전트 실행을 합친 금액이며 지출(USD)과 같은 값입니다. 3.84.0부터 보냅니다 |
19
+ | Codex 지출(USD) | Codex 롤아웃 사용량 기록으로 계산한 로컬 지출이며 압축된 롤아웃(`.jsonl.zst`)과 게이트웨이의 장문맥 구간 가격을 반영합니다. 가격을 모르면 비어 있습니다. 3.84.0부터 보냅니다 |
20
20
  | 게이트웨이 지출(USD) | LiteLLM 게이트웨이를 쓸 때 게이트웨이가 집계한 본인의 하루 지출입니다. 게이트웨이가 없거나 호출이 실패하면 비어 있습니다. 3.84.0부터 보냅니다 |
21
21
  | 게이트웨이 사용자 해시 | 게이트웨이 주소와 게이트웨이 사용자 ID를 합쳐 해시한 값의 앞 16자리(16진수)입니다. 한 사람이 컴퓨터 두 대를 써도 한 번만 세는 데 쓰며, 사용자 ID를 모르면 되돌릴 수 없습니다. 3.84.0부터 보냅니다 |
22
22
  | 총지출(USD) | 게이트웨이 금액을 알면 그 값이고, 모르면 Claude 지출과 Codex 지출의 합입니다. 3.84.0부터 보냅니다 |
@@ -36,7 +36,7 @@ Sprag 은 기본적으로 로컬에서만 동작합니다. 팀 기능은 켜야
36
36
 
37
37
  팀에 참여한 동안 statusline 에 `team` 칩이 나타나 멤버 ID 와 가상 사무실(Sprag 타운)에서 받은 동물을 보여 줍니다. 예를 들면 `member-1e500474 🦊 여우 12명 중 3위` 처럼 조직에서 순위에 오른 사람 가운데 몇 위인지도 함께 보여 줍니다. 동물은 5분마다 도는 전체 동기화가 서버에서 받아 `team.json` 에 저장한 순위로 정합니다. 서버가 아직 이 기능을 지원하지 않거나 마지막으로 받은 지 하루가 넘었다면 멤버 ID 만 표시합니다. 칩을 그릴 때는 로컬 파일만 읽습니다. IntelliJ 터미널은 글꼴에 동물 이모지가 없어 narrow 모드로 그리므로, 이때와 text 모드에서는 `member-1e500474 여우 12명 중 3위` 처럼 이모지 없이 이름만 보여 줍니다. 버전 칩 바로 앞에 놓이며, `--segments team` 으로 이 칩만 따로 볼 수 있습니다.
38
38
 
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` 도 본인 키로 호출해 본인의 하루 게이트웨이 지출을 읽습니다. 그 밖의 것은 읽지 않으며 키는 저장하지 않습니다. `sprag team status --show-payload` 를 실행하면 보내는 행을 그대로 볼 수 있습니다.
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` 를 실행하면 보내는 행을 그대로 볼 수 있습니다.
40
40
 
41
41
  ## CLI에서 팀 만들기
42
42
 
@@ -132,6 +132,14 @@ Sprag 은 룰을 `~/.claude/ratchet-team.md`(Codex 는 `<CODEX_HOME>/ratchet-tea
132
132
 
133
133
  관리하는 조직 안에 팀을 만들려면 `sprag team create --org <조직 ID>` 를 씁니다. 조직은 Sprag만 개설하므로 `--org` 없이 실행하면 서버가 거절합니다. 명령은 조직 이름과 사용 중인 좌석 수를 함께 출력하고, `sprag team status` 는 조직 이름을 보여 줍니다.
134
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
+
135
143
  ## 업로드 스위치
136
144
 
137
145
  `SPRAG_NO_TEAM_SYNC=1`(옛 이름 `CTS_NO_TEAM_SYNC` 도 계속 읽습니다)을 지정하면 모든 사용량 업로드가 멈춥니다. 참여한 컴퓨터는 스위치가 켜진 것을 처음 봤을 때와 다시 꺼졌을 때, 상태만 담은 호출 `member_set_sync` 를 한 번씩 보냅니다. 사용량 데이터는 들어 있지 않습니다. 다시 꺼진 뒤에는 바로 업로드합니다. 이 호출 덕분에 대시보드가 멈춘 컴퓨터와 연락이 끊긴 컴퓨터를 구분합니다. 멈춘 컴퓨터는 오너나 어드민이 내보내기 전까지 좌석을 유지합니다.
@@ -192,6 +200,7 @@ Free, 프로(좌석당 월 $5), 엔터프라이즈(좌석당 월 $10, 프롬프
192
200
  |---|---|
193
201
  | `<사용자 데이터 디렉터리>/team.json` | 참여 상태와 멤버 키(권한 0600) |
194
202
  | `<사용자 데이터 디렉터리>/team-rules.json` | 마지막 동기화 때 받은 조직·팀 룰 |
203
+ | `<사용자 데이터 디렉터리>/org-upgrade.json`, `org-upgrade.log` | 조직 최소 버전 업그레이드의 상태와 설치 출력 |
195
204
  | `<사용자 데이터 디렉터리>/prompts-offsets.json` | 프롬프트 업로더가 기록 파일마다 어디까지 읽었는지 적은 파일이며, 프롬프트 수집이 켜진 동안만 있습니다 |
196
205
  | `~/.claude/ratchet-team.md` | Claude Code 용 승인된 조직·팀 룰이며 `~/.claude/CLAUDE.md` 에서 import 합니다 |
197
206
  | `<CODEX_HOME>/ratchet-team.md` | Codex 용 같은 룰 |
package/docs/TEAM.md CHANGED
@@ -10,13 +10,13 @@ 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
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
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 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, null when no price is known; 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
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
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
22
  | Total spend (USD) | the gateway figure when known, otherwise Claude plus Codex; sent from 3.84.0 |
@@ -36,7 +36,7 @@ The daily aggregate upload runs at most once every 5 minutes after the last succ
36
36
 
37
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`.
38
38
 
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. `sprag team status --show-payload` prints the exact rows. `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.
40
40
 
41
41
  ## Create a team from the CLI
42
42
 
@@ -133,6 +133,14 @@ A machine holds one seat per organization. When it joins again, with `sprag team
133
133
 
134
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.
135
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
+
136
144
  ## The upload switch
137
145
 
138
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.
@@ -193,6 +201,7 @@ Owners and admins of an Enterprise organization get a Prompts tab on sprag.io/te
193
201
  |---|---|
194
202
  | `<user data dir>/team.json` | Membership state and the member key (mode 0600) |
195
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 |
196
205
  | `<user data dir>/prompts-offsets.json` | Where the prompt uploader stopped in each transcript; exists only while prompt capture is on |
197
206
  | `~/.claude/ratchet-team.md` | Approved organization and team rules for Claude Code, imported from `~/.claude/CLAUDE.md` |
198
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.84.0",
3
+ "version": "3.86.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": {
@@ -116,7 +116,7 @@
116
116
  },
117
117
  {
118
118
  "name": "t1h-worker",
119
- "model": "claude-opus-5-5",
119
+ "model": "opus",
120
120
  "effort": "high",
121
121
  "tier": "T1H",
122
122
  "categories": [
@@ -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 });
@@ -90,9 +90,12 @@ function catalogCodexModels(home) {
90
90
  * the parent, so the hint never names a model the gateway cannot serve. The
91
91
  * cheapest is T2 and the next one up is T1; with a single candidate T1 stays
92
92
  * on the main agent. T1H is the most expensive cheaper model, and only when
93
- * there are at least three candidates, so that it differs from T1. Returns { targets, reason }.
93
+ * there are at least three candidates, so that it differs from T1. Each target
94
+ * carries the reasoning effort the preset agents give its tier, the value the
95
+ * Claude agent files pin. Returns { targets, reason }.
94
96
  */
95
- export function autoCodexSharedTargets({ dir = userDataDir(), home = codexUserDir(), model, provider, now = Date.now() } = {}) {
97
+ export function autoCodexSharedTargets({ dir = userDataDir(), home = codexUserDir(), model, provider, now = Date.now(),
98
+ agents } = {}) {
96
99
  if (!safeId(model) || !safeId(provider)) return { targets: [], reason: 'unknown parent model or provider' };
97
100
  const book = codexPriceBook(provider, readCodexPrices({ now, home, dir }), { home });
98
101
  if (!book) return { targets: [], reason: `no price table for ${provider}` };
@@ -110,10 +113,25 @@ export function autoCodexSharedTargets({ dir = userDataDir(), home = codexUserDi
110
113
  }
111
114
  const picks = cheaper.slice(0, 2).map((x, i) => ({ tier: i === 0 ? 'T2' : 'T1', x }));
112
115
  if (cheaper.length >= 3) picks.push({ tier: 'T1H', x: cheaper.at(-1) });
113
- const targets = picks.map(({ tier, x }) => ({ tier, from: model, model: x.model, provider, auto: true }));
116
+ agents ??= agentDefinitions();
117
+ const targets = picks.map(({ tier, x }) => {
118
+ const effort = tierPresetEffort(tier, agents);
119
+ return { tier, from: model, model: x.model, ...(effort ? { effort } : {}), provider, auto: true };
120
+ });
114
121
  return { targets, reason: null };
115
122
  }
116
123
 
124
+ /**
125
+ * The effort every preset agent of a tier shares, or undefined when they
126
+ * disagree or name none: a mixed tier leaves Codex on the model's default
127
+ * rather than guessing which role the request will run as.
128
+ */
129
+ export function tierPresetEffort(tier, agents = agentDefinitions()) {
130
+ const efforts = new Set(agents.filter((a) => a && a.tier === tier).map((a) => a.effort));
131
+ const [effort] = efforts;
132
+ return efforts.size === 1 && effort && validEffort(effort) ? effort : undefined;
133
+ }
134
+
117
135
  /**
118
136
  * Explicit mappings win per tier. Without one, a tier resolves automatically
119
137
  * unless the user turned that off; resolution runs only for an enabled Codex
@@ -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()) {
@@ -341,7 +341,7 @@ export async function parseCodexTurns(filePath, { cutoffMs = -Infinity } = {}) {
341
341
  * the cache writes and `modelTotals` splits the totals by the model each
342
342
  * request ran on, so a session that switched models is priced per model.
343
343
  */
344
- export async function parseCodexSessionFile(filePath, { cutoffMs = -Infinity } = {}) {
344
+ export async function parseCodexSessionFile(filePath, { cutoffMs = -Infinity, keepRequests = false } = {}) {
345
345
  const session = {
346
346
  agent: 'codex', sessionId: null, filePath, projectDir: '', model: 'unknown',
347
347
  startTime: null, endTime: null, requestCount: 0, totals: emptyTotals(),
@@ -349,6 +349,16 @@ export async function parseCodexSessionFile(filePath, { cutoffMs = -Infinity } =
349
349
  lastContextTokens: null, rateLimits: null, lastActivity: null, effort: null,
350
350
  cacheActivity: null, modelTotals: null, usageSource: 'token_count',
351
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 });
361
+ };
352
362
  const copied = forkedCopyFilter();
353
363
  let previous = null;
354
364
  // usage records: per-response rows, keyed by response id to drop repeats
@@ -428,6 +438,8 @@ export async function parseCodexSessionFile(filePath, { cutoffMs = -Infinity } =
428
438
  addUsage(session.totals, { input: delta.input, cached: delta.cached, cacheWrite: delta.written, output: delta.output });
429
439
  const perModel = (session.modelTotals ??= {})[session.model] ??= emptyTotals();
430
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);
431
443
  // Reasoning is a subset of output, just as cached input is a subset of input.
432
444
  session.reasoningOutputTokens += Math.min(delta.output, delta.reasoning);
433
445
  session.requestCount++;
@@ -438,12 +450,14 @@ export async function parseCodexSessionFile(filePath, { cutoffMs = -Infinity } =
438
450
  // The snapshot path may have run before the first record appeared; the
439
451
  // records are the whole truth for this file, so start over from them.
440
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 = [];
441
454
  for (const r of records) {
442
455
  if (!Number.isFinite(r.ts) || r.ts < cutoffMs) continue;
443
456
  if (!r.input && !r.output) continue;
444
457
  addUsage(session.totals, r);
445
458
  const perModel = (session.modelTotals ??= {})[r.model || 'unknown'] ??= emptyTotals();
446
459
  addUsage(perModel, r);
460
+ addRequest(r.ts, r.model || 'unknown', r);
447
461
  session.reasoningOutputTokens += Math.min(r.output, r.reasoning);
448
462
  session.requestCount++;
449
463
  session.startTime ??= new Date(r.ts);
@@ -453,17 +467,23 @@ export async function parseCodexSessionFile(filePath, { cutoffMs = -Infinity } =
453
467
  return session;
454
468
  }
455
469
 
456
- export async function discoverCodexSessionFiles({ home = codexUserDir(), days = 30, excludeSessionPath } = {}) {
470
+ export async function discoverCodexSessionFiles({ home = codexUserDir(), days = 30, excludeSessionPath, compressed = false } = {}) {
457
471
  const cutoff = Date.now() - days * 86400000;
458
472
  const files = [];
459
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'));
460
477
  async function walk(dir) {
461
478
  let entries;
462
479
  try { entries = await readdir(dir, { withFileTypes: true }); } catch { return; }
480
+ const names = new Set(entries.map((entry) => entry.name));
463
481
  for (const entry of entries) {
464
482
  const path = join(dir, entry.name);
465
483
  if (entry.isDirectory()) await walk(path);
466
- else if (entry.isFile() && entry.name.endsWith('.jsonl') && resolve(path) !== excluded) {
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;
467
487
  try {
468
488
  const s = await stat(path);
469
489
  if (s.mtimeMs >= cutoff) files.push({ path, mtime: s.mtimeMs, size: s.size });
@@ -482,7 +502,7 @@ export async function parseAllCodexSessions(options = {}) {
482
502
  const results = [];
483
503
  for (let i = 0; i < files.length; i += 10) {
484
504
  const batch = await Promise.all(files.slice(i, i + 10).map(async ({ path }) => {
485
- try { return await parseCodexSessionFile(path, { cutoffMs }); } catch { return null; }
505
+ try { return await parseCodexSessionFile(path, { cutoffMs, keepRequests: options.keepRequests }); } catch { return null; }
486
506
  }));
487
507
  results.push(...batch.filter((s) => s?.requestCount && (!options.projectFilter || s.projectDir.includes(options.projectFilter))));
488
508
  }
@@ -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.`);
@@ -171,6 +171,19 @@ async function agentsCommand(action, lang) {
171
171
  const st = da.delegationAgentStatus();
172
172
  console.log(ko ? `delegate agents: ${st.enabled ? 'on' : 'off'}` : `delegate agents: ${st.enabled ? 'on' : 'off'}`);
173
173
  const label = { 'installed-by-sprag': ko ? 'sprag 가 설치함' : 'installed by sprag', 'user-file': ko ? '직접 만든 파일' : 'user file', absent: ko ? '없음' : 'absent' };
174
- for (const a of st.agents) console.log(` ${a.name}: ${a.state} (${label[a.state]})`);
174
+ for (const a of st.agents) {
175
+ let extra = '';
176
+ if (a.drift) {
177
+ const { file, preset } = a.drift;
178
+ const parts = [`effort ${file.effort || '-'}`];
179
+ const ps = [`effort ${preset.effort || '-'}`];
180
+ if (da.modelFamily(file.model) !== da.modelFamily(preset.model)) {
181
+ parts.push(ko ? `모델 ${file.model || '-'}` : `model ${file.model || '-'}`);
182
+ ps.push(ko ? `모델 ${preset.model || '-'}` : `model ${preset.model || '-'}`);
183
+ }
184
+ extra = ko ? ` · ${parts.join(' · ')}, 프리셋 ${ps.join(' · ')}` : ` · ${parts.join(' · ')}, preset ${ps.join(' · ')}`;
185
+ }
186
+ console.log(` ${a.name}: ${a.state} (${label[a.state]}${extra})`);
187
+ }
175
188
  console.log(ko ? '켜기 또는 끄기: sprag delegate agents on|off' : 'Toggle with: sprag delegate agents on|off');
176
189
  }
@@ -376,6 +376,8 @@ export async function run({ args, hasFlag, numArg }) {
376
376
  // where the *asking* happens: the model gets one line telling it a newer
377
377
  // version exists and to ask before installing anything. Cached read only
378
378
  // — the refresh runs detached off the statusline path, never here.
379
+ let driftBlock = null;
380
+ try { driftBlock = (await import('../delegation-agents.js')).takeAgentDriftNotice({ lang }); } catch (e) { debug('route-scan:agent-drift', e); }
379
381
  let updateBlock = null;
380
382
  try {
381
383
  const { updateOffer } = await import('../update-notice.js');
@@ -385,12 +387,13 @@ export async function run({ args, hasFlag, numArg }) {
385
387
  // statusline's 24h: releases can land several times a day, and a
386
388
  // session opened that afternoon should hear about them. It lands in
387
389
  // time for the statusline and for the next session, not for this line.
388
- if (pkgVersion) updateBlock = updateOffer(pkgVersion, { lang });
390
+ if (pkgVersion) updateBlock = updateOffer(pkgVersion, { agent: 'claude', lang });
389
391
  } catch (e) { debug('route-scan:update-check', e); /* the offer is optional */ }
390
392
 
391
393
  if (open.length === 0 && reviewRules.length === 0) {
392
394
  if (teamBlock) console.log(teamBlock);
393
395
  if (updateBlock) console.log(updateBlock);
396
+ if (driftBlock) console.log(driftBlock);
394
397
  if (seedBlock) console.log(seedBlock);
395
398
  if (doc2mdBlock) console.log(doc2mdBlock);
396
399
  if (koreanBlock) console.log(koreanBlock);
@@ -399,6 +402,7 @@ export async function run({ args, hasFlag, numArg }) {
399
402
  }
400
403
  if (teamBlock) console.log(teamBlock);
401
404
  if (updateBlock) console.log(updateBlock);
405
+ if (driftBlock) console.log(driftBlock);
402
406
  if (seedBlock) console.log(seedBlock);
403
407
  if (doc2mdBlock) console.log(doc2mdBlock);
404
408
  // This text is injected straight into the model's context, so it must
@@ -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));
@@ -4,6 +4,9 @@
4
4
  *
5
5
  * sprag upgrade # refresh the check, then install
6
6
  * sprag upgrade --print # show the command, run nothing
7
+ * sprag upgrade --org-policy [--agent codex]
8
+ * # non-interactive: what the session-start hook starts
9
+ * # (detached) when the organization sets a minimum version
7
10
  *
8
11
  * This is the command the model runs after the user says yes to the
9
12
  * session-start offer, so it prints the exact command it is about to execute
@@ -12,6 +15,8 @@
12
15
  */
13
16
 
14
17
  import { spawn } from 'node:child_process';
18
+ import { openSync, closeSync, writeSync, mkdirSync } from 'node:fs';
19
+ import { dirname } from 'node:path';
15
20
 
16
21
  function runCommand(cmd) {
17
22
  return new Promise((resolve) => {
@@ -24,7 +29,138 @@ function runCommand(cmd) {
24
29
  });
25
30
  }
26
31
 
27
- export async function run({ hasFlag, version }) {
32
+ /** Shell command with stdout and stderr appended to the log file; resolves to its exit code. */
33
+ function runLogged(cmd, logFile) {
34
+ return new Promise((resolve) => {
35
+ let fd;
36
+ try {
37
+ mkdirSync(dirname(logFile), { recursive: true });
38
+ fd = openSync(logFile, 'a');
39
+ writeSync(fd, `$ ${cmd}\n`);
40
+ } catch { resolve(1); return; }
41
+ const done = (code) => { try { closeSync(fd); } catch { /* already closed */ } resolve(code); };
42
+ // Same fixed-string shell form as runCommand; nothing here is user input.
43
+ const child = spawn(cmd, { shell: true, stdio: ['ignore', fd, fd], windowsHide: true });
44
+ child.on('close', (code) => done(code === null ? 1 : code));
45
+ child.on('error', () => done(1));
46
+ });
47
+ }
48
+
49
+ /** Whether sprag's Claude Code hooks or statusline are registered in settings.json. */
50
+ async function claudeIntegrationPresent() {
51
+ try {
52
+ const { readSettings, isOurCommand } = await import('../installer.js');
53
+ const { claudeUserDir } = await import('../paths.js');
54
+ const { join } = await import('node:path');
55
+ const read = readSettings(join(claudeUserDir(), 'settings.json'));
56
+ if (read.state !== 'ok') return false;
57
+ const s = read.settings;
58
+ if (isOurCommand(s.statusLine?.command)) return true;
59
+ return Object.values(s.hooks && typeof s.hooks === 'object' ? s.hooks : {}).some((groups) =>
60
+ Array.isArray(groups) && groups.some((g) => Array.isArray(g?.hooks) && g.hooks.some((h) => isOurCommand(h?.command))));
61
+ } catch { return false; }
62
+ }
63
+
64
+ /** Whether sprag's Codex hooks are registered. */
65
+ async function codexIntegrationPresent() {
66
+ try {
67
+ const { codexHookStatus } = await import('../codex/installer.js');
68
+ return codexHookStatus().some((h) => h.registered);
69
+ } catch { return false; }
70
+ }
71
+
72
+ /**
73
+ * The commands an organization-policy upgrade runs for `agent`, in order. The
74
+ * agent's own install comes first; the other agent's integration is refreshed
75
+ * too when it is present, so a machine with both ends up on one version.
76
+ */
77
+ export async function orgUpgradeCommands(agent, { claudePresent = claudeIntegrationPresent, codexPresent = codexIntegrationPresent } = {}) {
78
+ const { upgradeCommand } = await import('../update-check.js');
79
+ const { upgradeInstructions } = await import('../update-notice.js');
80
+ const cmds = agent === 'codex' ? [...upgradeInstructions('codex')] : [upgradeCommand(), 'sprag install'];
81
+ if (agent === 'codex' ? await claudePresent() : await codexPresent()) {
82
+ cmds.push(agent === 'codex' ? 'sprag install' : 'sprag install --agent codex');
83
+ }
84
+ return [...new Set(cmds)];
85
+ }
86
+
87
+ /**
88
+ * `sprag upgrade --org-policy`: the unattended upgrade the session-start hook
89
+ * starts when the organization sets a minimum version. Detached, so nothing
90
+ * goes to a terminal: output is appended to org-upgrade.log and the outcome to
91
+ * org-upgrade.json, which the next session reports. `exec`, `refresh` and
92
+ * `dir` are injectable for tests.
93
+ */
94
+ export async function runOrgPolicy({
95
+ version, agent = 'claude', dir, now = Date.now, exec, refresh, claudePresent, codexPresent,
96
+ } = {}) {
97
+ const { userDataDir } = await import('../paths.js');
98
+ const { readTeamState } = await import('../team-ratchet.js');
99
+ const org = await import('../org-upgrade.js');
100
+ const { isNewer, refreshUpdateState } = await import('../update-check.js');
101
+ const root = dir || userDataDir();
102
+ const logFile = org.orgUpgradeLogPath(root);
103
+ const run = exec || ((cmd) => runLogged(cmd, logFile));
104
+ const refreshState = refresh || refreshUpdateState;
105
+ const log = (line) => { try { writeLogLine(logFile, line); } catch { /* the record still says what happened */ } };
106
+
107
+ const prev = org.readOrgUpgrade(root);
108
+ if (prev.pid && prev.pid !== process.pid && org.orgUpgradeInFlight(prev, { now: now() })) {
109
+ return { ok: false, skipped: 'in-flight' };
110
+ }
111
+ const required = org.orgMinVersion(readTeamState(root));
112
+ const target = required || prev.target || null;
113
+ org.writeOrgUpgrade({
114
+ target, from: version, startedAt: prev.startedAt && !prev.finishedAt ? prev.startedAt : now(), pid: process.pid,
115
+ finishedAt: null, ok: null, error: null, announced: false,
116
+ }, root);
117
+ const finish = (ok, error = null, extra = {}) => {
118
+ org.writeOrgUpgrade({ finishedAt: now(), ok, error, ...extra }, root);
119
+ return { ok, error };
120
+ };
121
+
122
+ if (!required || !isNewer(required, version)) {
123
+ // The requirement went away while this was starting: nothing to report.
124
+ log(`nothing required (minimum ${required || 'unset'}, running ${version})`);
125
+ return finish(false, 'no minimum version is required any more', { announced: true });
126
+ }
127
+ const r = await refreshState(version);
128
+ const latest = r && r.ok ? r.latest : null;
129
+ if (!latest) {
130
+ log(`registry check failed: ${(r && r.error) || 'no answer'}`);
131
+ return finish(false, `could not read the latest version from the registry: ${(r && r.error) || 'no answer'}`);
132
+ }
133
+ if (isNewer(required, latest)) {
134
+ log(`required version ${required} is not published (latest ${latest})`);
135
+ return finish(false, `required version ${required} is not published (latest ${latest})`);
136
+ }
137
+
138
+ for (const cmd of await orgUpgradeCommands(agent, { claudePresent, codexPresent })) {
139
+ const code = await run(cmd);
140
+ if (code !== 0) {
141
+ log(`failed (exit ${code}): ${cmd}`);
142
+ return finish(false, `"${cmd}" exited with code ${code}`);
143
+ }
144
+ }
145
+ // Same as the interactive path: the cached "latest" now describes the new copy.
146
+ try { await refreshState(latest); } catch (e) { log(`state refresh failed: ${e && e.message}`); }
147
+ log(`upgraded ${version} -> ${latest}`);
148
+ return finish(true);
149
+ }
150
+
151
+ function writeLogLine(file, line) {
152
+ mkdirSync(dirname(file), { recursive: true });
153
+ const fd = openSync(file, 'a');
154
+ try { writeSync(fd, `[${new Date().toISOString()}] ${line}\n`); } finally { closeSync(fd); }
155
+ }
156
+
157
+ export async function run({ hasFlag, version, agent = 'claude' }) {
158
+ if (hasFlag('--org-policy')) {
159
+ // Detached, so the exit code is for whoever runs it by hand; the record has the reason.
160
+ const result = await runOrgPolicy({ version, agent });
161
+ if (!result.ok) process.exitCode = 1;
162
+ return;
163
+ }
28
164
  const { updateStatus, refreshUpdateState, upgradeCommand, INSTALLED_UNDER_LEGACY_NAME } =
29
165
  await import('../update-check.js');
30
166
  const { userLanguage } = await import('../config.js');