claude-token-saver 3.50.0 → 3.55.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.
Files changed (64) hide show
  1. package/README.ko.md +54 -3
  2. package/README.md +63 -4
  3. package/bin/cli.js +41 -10
  4. package/docs/CODEX.ko.md +184 -0
  5. package/docs/CODEX.md +497 -0
  6. package/package.json +14 -3
  7. package/presets/delegation/bounds.md +29 -0
  8. package/presets/ratchet-rules.json +4 -1
  9. package/src/agent.js +33 -0
  10. package/src/caps-cache.js +6 -2
  11. package/src/codex-brief.js +89 -0
  12. package/src/codex-budget.js +73 -0
  13. package/src/codex-cache-policy.js +203 -0
  14. package/src/codex-cache.js +46 -0
  15. package/src/codex-delegation.js +154 -0
  16. package/src/codex-doc2md-ledger.js +45 -0
  17. package/src/codex-doc2md.js +99 -0
  18. package/src/codex-doctor.js +53 -0
  19. package/src/codex-harness.js +200 -0
  20. package/src/codex-hooks.js +138 -0
  21. package/src/codex-installer.js +79 -0
  22. package/src/codex-ledger.js +143 -0
  23. package/src/codex-panel-launcher.js +48 -0
  24. package/src/codex-panel-runner.js +74 -0
  25. package/src/codex-panel-session.js +35 -0
  26. package/src/codex-panel-setup.js +98 -0
  27. package/src/codex-panel-shell.js +51 -0
  28. package/src/codex-panel-state.js +40 -0
  29. package/src/codex-panel.js +448 -0
  30. package/src/codex-parser.js +397 -0
  31. package/src/codex-route-scan.js +171 -0
  32. package/src/commands/brief.js +13 -2
  33. package/src/commands/codex-delegate.js +59 -0
  34. package/src/commands/codex.js +579 -0
  35. package/src/commands/delegate.js +133 -0
  36. package/src/commands/harness.js +16 -3
  37. package/src/commands/install.js +108 -12
  38. package/src/commands/korean.js +2 -2
  39. package/src/commands/route-scan.js +4 -0
  40. package/src/commands/seed.js +16 -12
  41. package/src/commands/uninstall.js +23 -0
  42. package/src/commands/upgrade.js +13 -0
  43. package/src/compact-window.js +7 -1
  44. package/src/cost.js +34 -0
  45. package/src/delegation-guard.js +278 -0
  46. package/src/doc2md-ledger.cjs +3 -3
  47. package/src/doc2md.cjs +72 -28
  48. package/src/formatters/statusline.js +3 -1
  49. package/src/handoff.js +27 -7
  50. package/src/harness-analyzer.cjs +7 -2
  51. package/src/harness-templates.js +33 -1
  52. package/src/harness.js +51 -17
  53. package/src/hook-manager.js +39 -12
  54. package/src/hook.cjs +34 -2
  55. package/src/installer.js +168 -0
  56. package/src/parser.js +89 -1
  57. package/src/preset-ratchet.js +133 -0
  58. package/src/route-inject.js +71 -4
  59. package/src/route-scan.js +44 -7
  60. package/src/seed-rules.js +88 -39
  61. package/src/session-paths.js +242 -0
  62. package/src/statusline-mode.js +13 -2
  63. package/src/update-check.js +41 -4
  64. package/src/window-labels.js +2 -1
package/README.ko.md CHANGED
@@ -5,7 +5,7 @@
5
5
  <img alt="Sprag" src="https://raw.githubusercontent.com/rootstudioyaml/sprag/main/site/assets/logo/sprag-lockup-light.svg" width="220">
6
6
  </picture>
7
7
 
8
- **AI 코딩 에이전트용 품질 래칫**<br>**같은 실수는 두 번 없습니다**
8
+ **Claude Code와 Codex가 쓰는 토큰을 첫 세션부터 줄입니다**
9
9
 
10
10
  [![npm](https://img.shields.io/npm/v/sprag-cli.svg?label=sprag-cli)](https://www.npmjs.com/package/sprag-cli)
11
11
  [![downloads](https://img.shields.io/npm/dm/sprag-cli.svg)](https://www.npmjs.com/package/sprag-cli)
@@ -15,20 +15,70 @@
15
15
 
16
16
  [sprag.io](https://sprag.io) · [벤치마크](https://github.com/rootstudioyaml/sprag/blob/main/docs/BENCHMARK.md)
17
17
 
18
+ <a href="https://sprag.io/assets/video/sprag-compare-ko.mp4"><img src="https://raw.githubusercontent.com/rootstudioyaml/sprag/main/docs/sprag-compare-ko.gif" width="760" alt="두 터미널에 같은 요청 12건을 넣습니다. sprag 를 적용한 쪽은 조회와 테스트 실행을 저렴한 모델에 넘기고 문서를 Markdown 으로 바꿔 넣어, 하루를 $6.68 대신 $1.83 로 마칩니다."></a>
19
+
20
+ 같은 요청 12건, 두 터미널: sprag 적용 시 **$6.68 → $1.83 (72.6% 절감)**<br>
21
+ <sub>예시 요청을 공개 단가로 계산했습니다. <a href="https://sprag.io/assets/video/sprag-compare-ko.mp4">전체 영상 (41초)</a></sub>
22
+
18
23
  </div>
19
24
 
20
25
  ---
21
26
 
27
+ **일하는 방식은 그대로 두고 토큰만 줄입니다.** 조회와 확인, 테스트 실행은 저렴한 모델에 넘기고, 문서는 가벼운 Markdown으로 바꿔 넣습니다(54만 토큰짜리 발표 자료가 2.3만 토큰이 됩니다). 세션마다 쓴 금액과 아낀 금액은 상태줄에 바로 나타납니다. `npm i -g sprag-cli` 하나로 설정이 끝나며, 프로젝트마다 따로 설정할 것은 없습니다.
28
+
22
29
  **에이전트는 그대로 일하고, 퇴행만 막습니다.** 이름은 스프래그 클러치에서 왔습니다. 앞으로 도는 힘은 그대로 통과시키고, 역회전하는 순간 잠기는 부품입니다.
23
30
 
24
- Sprag 는 Claude Code 가 이미 남기는 세션 기록을 읽습니다. 거기서 찾아낸 것은 이후 모든 세션에 남습니다. 되풀이된 실패는 세션마다 올라오는 규칙이 되고, 저렴한 등급에서 한 번도 틀리지 않은 작업은 그 등급의 서브에이전트로 갑니다. 위임된 실행은 한 건마다 단가 차액을 원장에 적습니다. 캐시와 사용량 한도 문제는 아직 손쓸 수 있을 때 statusline 에 나타납니다.
31
+ Sprag는 Claude Code와 Codex가 남기는 세션 기록을 읽어 반복 실패와 위임 후보를 찾습니다. 사용자가 승인한 규칙은 다음 세션에도 적용하며, 위임 기록과 모델 단가를 확인할 수 있으면 예상 차액을 원장에 적습니다. 캐시와 사용량 한도 문제는 상태줄이나 패널에서 확인할 수 있습니다.
25
32
 
26
- 데이터는 컴퓨터 밖으로 나가지 않습니다. Claude Code 가 이 컴퓨터에 이미 남긴 기록만 읽기 때문입니다. API 키도, 추가 모델 호출도, 런타임 의존성도 없습니다.
33
+ 세션 분석은 로컬에서 실행하므로 추가 모델 호출이나 API 키가 필요하지 않습니다. Codex의 선택 기능인 예산·단가 조회는 기존 인증 정보로 사용자가 설정한 LiteLLM에 접속합니다. CLI는 Node.js 18 이상과 TOML 파서 하나를 사용합니다.
27
34
 
28
35
  ```bash
29
36
  npm i -g sprag-cli # 예전 이름 claude-token-saver 와 같은 패키지입니다
30
37
  ```
31
38
 
39
+ ## Codex
40
+
41
+ Codex 기본 훅과 `AGENTS.md` 하네스, 범위별 래칫 규칙,
42
+ 한국어 검사, 프롬프트의 문서 경로 자동 변환, 로컬 토큰 보고서를 사용할 수 있습니다.
43
+ Codex가 설치되어 있으면 `npm i -g sprag-cli` 하나로 Codex도 설정하고, 추천 룰을 묻지 않고
44
+ 전역으로 등록합니다(단계마다 확인하려면 `sprag install --manual`). Claude Code를 건드리지 않고
45
+ Codex만 쓴다면 다음과 같이 설치하십시오.
46
+
47
+ ```bash
48
+ npm i -g sprag-cli --ignore-scripts
49
+ sprag install --agent codex
50
+ sprag --agent codex --days 7
51
+ sprag panel --agent codex # 별도 터미널에서 실시간 패널 실행
52
+ sprag --statusline --agent codex --text
53
+ sprag doctor --agent codex # 문제가 생겼을 때만
54
+ sprag route-scan --agent codex
55
+ sprag seed --agent codex
56
+ ```
57
+
58
+ 설치 후 Codex의 `/hooks`에서 새 훅을 검토하고 신뢰해야 실행됩니다. Codex가 요구하는
59
+ 절차입니다. 명령의 기본 대상은 여전히 Claude Code이며, `--agent codex`를 붙이면 Codex를 고릅니다. Codex에서도 세션 브리핑, 경고 이력, 인수인계
60
+ 파일을 지원합니다. `sprag delegate on --agent codex`로 모델 위임과 하위 에이전트
61
+ 지침 전달을 켤 수 있습니다. 상태 표시는 Sprag 터미널 상태줄과 패널을 사용하십시오.
62
+ Codex 기본 상태줄은 셸 명령을 실행하지 않습니다. 반복된 단순 작업은 위임 후보로,
63
+ 반복된 도구 실패는 래칫 후보로 제안합니다. 규칙을 등록하려면 사용자의 승인이 필요하며,
64
+ `seed`로 호환되는 기본 규칙을 선택할 수도 있습니다.
65
+ `sprag route-scan savings --agent codex`는 Sprag가 위임한 실행만 집계하고,
66
+ 일치하는 LiteLLM 단가가 있을 때 예상 차액을 계산합니다. 청구 금액을 측정한 값은 아니며,
67
+ 단가를 확인하지 못하면 `n/a`로 표시합니다. Codex 문서 누계는 Claude 추정치와 분리합니다.
68
+ 아래의 기존 절감 수치는 Claude Code 기록이며 Codex 벤치마크가 아닙니다.
69
+ [Codex 지원 범위와 제한](https://sprag.io/docs/ko/codex/)이나
70
+ `sprag capabilities --agent codex`에서 기능별 지원 여부를 확인하십시오.
71
+
72
+ | 기능 | Claude Code | Codex |
73
+ |---|---|---|
74
+ | 세션 지침 | `CLAUDE.md`와 훅 | `AGENTS.md`와 기본 훅 |
75
+ | 실시간 상태 | 기본 상태줄에 명령 등록 | 별도 패널 또는 tmux 구성 |
76
+ | 규칙 후보 | Claude 기록과 모델 등급 프리셋 | Codex 기록과 호환 래칫 프리셋 |
77
+ | 모델 위임 | Haiku·Sonnet 등급 규칙 | 공급자 모델 ID와 범위별 규칙 |
78
+ | 위임 원장 | Claude 실행별 예상 차액 | LiteLLM 단가와 하위 실행별 예상 차액 |
79
+
80
+ 두 연동을 함께 설치할 수 있습니다. `--agent codex`를 붙이지 않으면 기존 Claude 동작을 유지합니다.
81
+
32
82
  ![statusline 예시. 첫 줄은 라우팅 절감액, 둘째 줄은 문서 변환 절감액, 셋째 줄은 진단 칩입니다](https://raw.githubusercontent.com/rootstudioyaml/sprag/main/docs/statusline.png)
33
83
 
34
84
  ## 작동 방식
@@ -166,6 +216,7 @@ LiteLLM 게이트웨이 환경에서는 `sprag profile-map --refresh` 가 게이
166
216
 
167
217
  전체 내역은 [CHANGELOG.md](./CHANGELOG.md) 로 옮겼습니다. 최근 변경은 다음과 같습니다.
168
218
 
219
+ - **v3.54.0**: Codex용 네이티브 훅, `AGENTS.md` 하네스, 세션에 연결된 동반 패널, 문서 변환, 진단과 선택적 위임 기능을 추가했습니다. Codex 사용량은 Claude Code와 분리해 집계합니다. 자세한 내용은 [Codex 가이드](./docs/CODEX.ko.md)에 있습니다.
169
220
  - **v3.39.0**: `feedback` 서브커맨드가 터미널이나 Claude 세션에서 버그 제보·기능 제안을 바로 제출합니다. gh CLI가 있으면 이슈 직접 등록, 없으면 로그인 없는 익명 제출(릴레이가 이슈로 자동 등록), 오프라인이면 로컬 저장. `install`은 기존 statusline이 있으면 조용히 건너뛰지 않고 교체 여부를 묻습니다.
170
221
  - **v3.38.0**: `cohesion on`이 응집성 다섯 원칙을 영어 블록으로 주입합니다. 옵트인이고, korean 지침이 켜져 있으면 중복 주입을 막습니다.
171
222
  - **v3.37.0**: 한국어 지침에 보강 지침(supplement)이 붙습니다. 번역투·상투 패턴·응집성(문장 이어짐) 조항이며, 쓰기 시점 검사에도 번역투 5종이 추가됐습니다. 실파일 255개 실측에서 오탐 1건으로 검증했습니다.
package/README.md CHANGED
@@ -10,7 +10,7 @@
10
10
  <img alt="Sprag" src="https://raw.githubusercontent.com/rootstudioyaml/sprag/main/site/assets/logo/sprag-lockup-light.svg" width="220">
11
11
  </picture>
12
12
 
13
- **A quality ratchet for your coding agent. Forward motion passes, backspin locks.**
13
+ **Cut the tokens Claude Code and Codex spend, from the first session.**
14
14
 
15
15
  [![npm](https://img.shields.io/npm/v/sprag-cli.svg?label=sprag-cli)](https://www.npmjs.com/package/sprag-cli)
16
16
  [![downloads](https://img.shields.io/npm/dm/sprag-cli.svg)](https://www.npmjs.com/package/sprag-cli)
@@ -20,10 +20,21 @@
20
20
 
21
21
  [sprag.io](https://sprag.io) · [Benchmark](https://github.com/rootstudioyaml/sprag/blob/main/docs/BENCHMARK.md)
22
22
 
23
+ <a href="https://sprag.io/assets/video/sprag-compare-en.mp4"><img src="https://raw.githubusercontent.com/rootstudioyaml/sprag/main/docs/sprag-compare-en.gif" width="760" alt="Two terminals receive the same twelve requests. With Sprag, lookups and test runs go to cheaper models and documents go in as Markdown; the day ends at $1.83 against $6.68 without Sprag."></a>
24
+
25
+ Same 12 requests, two terminals: **$6.68 → $1.83 (−72.6%)** with Sprag.<br>
26
+ <sub>Example requests priced at public list rates. <a href="https://sprag.io/assets/video/sprag-compare-en.mp4">Full video (41s)</a></sub>
27
+
23
28
  </div>
24
29
 
25
30
  ---
26
31
 
32
+ **Sprag saves tokens without changing how you work.** Lookups, checks and test
33
+ runs go to a cheaper model, documents reach the context as compact Markdown (a
34
+ 540k-token deck becomes 23k tokens), and the statusline shows what each session
35
+ spent and saved while it runs. `npm i -g sprag-cli` sets it all up; nothing to
36
+ configure per project.
37
+
27
38
  Sprag is named after the sprag clutch: forward motion passes, backspin locks.
28
39
  Your agent keeps working, it just stops regressing.
29
40
 
@@ -33,13 +44,59 @@ a cheaper tier has never got wrong goes to a sub-agent on that tier, and every
33
44
  delegated run writes its own price difference to a ledger. Cache and rate-limit
34
45
  trouble reaches your statusline while you can still act on it.
35
46
 
36
- Nothing leaves your machine, because it reads only the logs Claude Code already
37
- writes there. No API key, no extra model calls, no runtime dependencies.
47
+ Session analysis runs locally on the logs Claude Code and Codex already write.
48
+ No extra model calls or API key are needed for analysis. Optional Codex gateway
49
+ budget and price lookups contact your configured LiteLLM endpoint using its
50
+ existing credentials. The CLI requires Node.js 18+ and one TOML parser dependency.
38
51
 
39
52
  ```bash
40
- npm i -g sprag-cli # the old claude-token-saver package still gets the same releases
53
+ npm i -g sprag-cli # Claude Code, plus Codex when it is installed
41
54
  ```
42
55
 
56
+ ## Codex
57
+
58
+ Native hooks, an `AGENTS.md` harness, scoped ratchet rules, Korean lint,
59
+ document conversion, token reports, and a session-bound companion panel.
60
+ `npm i -g sprag-cli` sets Codex up too when it is installed, with the rule
61
+ presets registered globally and nothing asked (`sprag install --manual` asks at
62
+ each step). For a Codex-only install that leaves Claude Code alone:
63
+
64
+ ```bash
65
+ npm i -g sprag-cli --ignore-scripts
66
+ sprag install --agent codex
67
+ sprag --agent codex --days 7
68
+ sprag panel --agent codex # live companion in a separate terminal
69
+ sprag --statusline --agent codex --text
70
+ sprag doctor --agent codex # troubleshooting only
71
+ sprag route-scan --agent codex
72
+ sprag seed --agent codex
73
+ ```
74
+
75
+ Review and trust the new hooks in Codex's `/hooks` menu; Codex requires that
76
+ step. Commands still default to Claude Code; add `--agent codex` to pick Codex.
77
+ Codex also supports session briefings, warning history, handoffs, and opt-in
78
+ model routing and subagent guidance (`sprag delegate on --agent codex`). The native Codex footer
79
+ does not accept shell commands; Sprag provides a terminal statusline and panel.
80
+ Recurring simple turns become route candidates; repeated tool failures become
81
+ ratchet candidates. Both require your approval before a rule is registered.
82
+ `seed` offers compatible starter rules with separate Codex decisions.
83
+ `sprag route-scan savings --agent codex` records only Sprag-routed child runs
84
+ and estimates their price difference when matching LiteLLM prices are available.
85
+ It is not a billing measurement. Unknown prices remain `n/a`, and Codex document
86
+ counts stay separate from Claude estimates. The historical dollar figures below
87
+ are from Claude Code, not a Codex benchmark. See [Codex support and limits](https://sprag.io/docs/codex/), or run
88
+ `sprag capabilities --agent codex` for the support matrix.
89
+
90
+ | Workflow | Claude Code | Codex |
91
+ |---|---|---|
92
+ | Session instructions | `CLAUDE.md` and hooks | `AGENTS.md` and native hooks |
93
+ | Live telemetry | Native statusline command | Companion panel or tmux layout |
94
+ | Rule candidates | Claude transcripts and tier presets | Codex rollouts and compatible ratchet presets |
95
+ | Model routing | Haiku/Sonnet tier rules | Explicit provider model IDs and scoped rules |
96
+ | Routing ledger | Claude run estimates | Attributed child estimates with LiteLLM prices |
97
+
98
+ Both integrations coexist. Commands without `--agent codex` retain Claude behavior.
99
+
43
100
  ![statusline example: routing savings on row 1, document conversion savings on row 2, diagnostics on row 3](https://raw.githubusercontent.com/rootstudioyaml/sprag/main/docs/statusline.png)
44
101
 
45
102
  ## How it works
@@ -190,6 +247,7 @@ Every subcommand, flag and the output-language setting: [command reference](http
190
247
 
191
248
  | Doc | Covers |
192
249
  |---|---|
250
+ | [Codex](https://sprag.io/docs/codex/) | Installation, panel, native hooks, automatic candidates, presets, and accounting limits |
193
251
  | [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 |
194
252
  | [Statusline](https://github.com/rootstudioyaml/sprag/blob/main/docs/STATUSLINE.md) | Segments, warning chips, spike issue codes, update notifications |
195
253
  | [Commands](https://github.com/rootstudioyaml/sprag/blob/main/docs/COMMANDS.md) | Full CLI surface |
@@ -208,6 +266,7 @@ Behind a LiteLLM gateway, `sprag profile-map --refresh` now reads model aliases
208
266
 
209
267
  The full history moved to [CHANGELOG.md](./CHANGELOG.md) (Korean; version headings and command names are language-neutral). Recent changes:
210
268
 
269
+ - **v3.54.0**: Codex integration adds native hooks, `AGENTS.md` harness rules, a session-bound companion panel, document conversion, diagnostics, and opt-in delegation. Codex usage accounting stays separate from Claude Code. See the [Codex guide](./docs/CODEX.md).
211
270
  - **v3.39.0**: `feedback` subcommand for filing bug reports and feature requests straight from the terminal or a Claude session, via the gh CLI, an anonymous no-login form (auto-filed as a GitHub issue by an Apps Script relay), or a local fallback. `install` now asks before replacing an existing statusline instead of silently skipping.
212
271
  - **v3.38.0**: `cohesion on` turns the language-neutral cohesion rules from the Korean supplement into a standalone English injection (given-before-new, one referent per pronoun, subject consistency, bridging, merging choppy sentences). Opt-in, ~0.5k tokens per session, suppressed while `korean on` already carries them.
213
272
  - **v3.37.0**: Korean guidance grows a conservative supplement (translationese, AI-writing tics, a research-backed cohesion section whose principles apply to English prose too) and the write-time lint gains 5 translationese patterns, validated at 1 false positive across 255 real files.
package/bin/cli.js CHANGED
@@ -10,8 +10,8 @@
10
10
  * npx sprag --format csv # CSV output
11
11
  * npx sprag --project myproj # filter by project
12
12
  * npx sprag route-scan # detect recurring easy work → haiku-delegation candidates
13
- * npx sprag install # set up skill/hooks/statusline; asks about harness + Korean guidance
14
- * npx sprag install --yes # take the defaults without asking (same as --no-input)
13
+ * npx sprag install # set up everything, presets and Codex included, without asking
14
+ * npx sprag install --manual # confirm each optional step
15
15
  * npx sprag --install-hook # install PostToolUse hook
16
16
  * npx sprag --uninstall-hook # remove hook
17
17
  * npx claude-token-saver --hook-run # internal: called by hook
@@ -52,13 +52,18 @@ import {
52
52
  sessionMetrics,
53
53
  diagnoseSession,
54
54
  } from '../src/stats.js';
55
- import { estimateCost } from '../src/cost.js';
55
+ import { estimateCostAcross } from '../src/cost.js';
56
56
  import { chipForIssues } from '../src/advice.js';
57
57
  import { debug } from '../src/debug.js';
58
58
  import { createArgs } from '../src/cli-args.js';
59
59
  import { updateStatus, maybeSpawnUpdateCheck } from '../src/update-check.js';
60
+ import { selectAgent } from '../src/agent.js';
60
61
 
61
- const args = process.argv.slice(2);
62
+ const selection = (() => {
63
+ try { return selectAgent(process.argv.slice(2)); }
64
+ catch (e) { console.error(`Error: ${e.message}`); process.exit(1); }
65
+ })();
66
+ const { args, agent } = selection;
62
67
 
63
68
  const PKG_VERSION = (() => {
64
69
  try {
@@ -90,11 +95,11 @@ function readUpdateChip() {
90
95
  // Subcommands this build knows how to run. Used only by the guard below.
91
96
  const KNOWN_SUBCOMMANDS = new Set([
92
97
  'last', 'brief', 'history', 'handoff', 'install', 'uninstall', 'mode', 'korean', 'cohesion',
93
- 'doc2md', 'harness', 'route-scan', 'compact-window', 'update-check', 'upgrade',
98
+ 'doc2md', 'delegate', 'harness', 'route-scan', 'compact-window', 'update-check', 'upgrade',
94
99
  'seed', 'litellm-budget', 'profile-map', 'feedback',
95
100
  ]);
96
101
 
97
- const USAGE = `sprag — Claude Code token usage, cache health, and model routing
102
+ const USAGE = `sprag — Claude Code and Codex agent harness
98
103
 
99
104
  Usage:
100
105
  sprag default report (last 30 days)
@@ -102,10 +107,24 @@ Usage:
102
107
  sprag --format json JSON output
103
108
  sprag --format csv CSV output
104
109
  sprag --project myproj filter by project
110
+ sprag --agent codex Codex token report (table/json/csv)
111
+ sprag --statusline --agent codex one-shot compact terminal status
112
+ sprag doctor --agent codex diagnose hooks, config, harness, and session logs
113
+ sprag capabilities --agent codex full support matrix and limitations
114
+ sprag panel --agent codex live companion panel in a separate terminal
115
+ sprag panel auto on --agent codex open panel on Codex startup/resume (macOS)
116
+ sprag panel --open --agent codex open/reuse a macOS Terminal panel now
117
+ sprag panel run --agent codex -- run Codex above a compact panel (tmux)
118
+ sprag panel doctor --agent codex check registration, hook execution, and rendering
119
+ --project <path> / --session <id> / --interval 2 / --once / --no-color
120
+ sprag install --agent codex install Codex hooks + AGENTS.md harness
121
+ sprag harness init --agent codex initialize this project's Codex harness
122
+ sprag uninstall --agent codex remove the global Codex integration
123
+ --agent claude|codex (default: claude; accepted before or after subcommands)
105
124
  sprag route-scan detect recurring easy work → delegation candidates
106
125
  sprag profile-map show/refresh the gateway model map (LiteLLM /model/info)
107
- sprag install set up skill/hooks/statusline
108
- sprag install --yes take the defaults without asking
126
+ sprag install set up everything (presets, and Codex when present) without asking
127
+ sprag install --manual confirm each optional step
109
128
  sprag uninstall remove everything install added
110
129
  sprag harness check score the harness setup in CLAUDE.md
111
130
  sprag harness analyze run the harness transcript analysis manually
@@ -124,6 +143,10 @@ Bug reports & feature requests: https://github.com/rootstudioyaml/sprag/issues
124
143
  `;
125
144
 
126
145
  async function main() {
146
+ if (agent === 'codex') {
147
+ if (hasFlag('--version') || hasFlag('-v')) { console.log(PKG_VERSION); return; }
148
+ return (await import('../src/commands/codex.js')).run({ args, version: PKG_VERSION });
149
+ }
127
150
  // Help must never fall through to the default report — that runs a full
128
151
  // 30-day scan, which is the opposite of what someone asking for help wants.
129
152
  if (hasFlag('--help') || hasFlag('-h') || args[0] === 'help') {
@@ -247,6 +270,14 @@ async function main() {
247
270
  return (await import('../src/commands/doc2md.js')).run({ args, hasFlag });
248
271
  }
249
272
 
273
+ // Subcommand: delegate — rewrite Task/Agent delegation prompts so a
274
+ // subagent gets bounds, Korean guidance when the prompt needs it, and paths
275
+ // this session already read, instead of starting from nothing.
276
+ // sprag delegate on | off | --hook
277
+ if (args[0] === 'delegate') {
278
+ return (await import('../src/commands/delegate.js')).run({ args, hasFlag });
279
+ }
280
+
250
281
  // Subcommand: seed — register the bundled starter rules (model-fitting
251
282
  // presets + curated ratchet rules), one answer at a time.
252
283
  // sprag seed | seed accept <id> --global|--project | seed skip <id>
@@ -561,7 +592,7 @@ async function main() {
561
592
  const ttl = ttlBreakdown(sessions);
562
593
  const sum = summary(sessions);
563
594
  const anomalies = detectAnomalies(trend);
564
- const cost = estimateCost(sum, sessions[0]?.model);
595
+ const cost = estimateCostAcross(sessions);
565
596
  const spikeReport = detectSpikes(sessions, { recentHours: 24, multiplier: 3 });
566
597
  const contextWindow = detectContextWindow(sessions, { recentHours: 24 });
567
598
 
@@ -834,7 +865,7 @@ async function main() {
834
865
 
835
866
  main().catch((err) => {
836
867
  // Statusline mode must never spam multi-line errors (called every ~300ms)
837
- const isStatusline = process.argv.includes('--statusline') || process.argv.includes('statusline');
868
+ const isStatusline = agent === 'claude' && (process.argv.includes('--statusline') || process.argv.includes('statusline'));
838
869
  if (isStatusline) {
839
870
  const colorOk = !process.argv.includes('--no-color') && !process.env.NO_COLOR;
840
871
  const red = colorOk ? '\x1b[31m' : '';
@@ -0,0 +1,184 @@
1
+ # Codex 연동
2
+
3
+ [← README](../README.ko.md) · [English](./CODEX.md)
4
+
5
+ Sprag는 Codex의 기본 훅과 `AGENTS.md`를 사용합니다. Claude Code와 함께 설치할 수 있으며,
6
+ 명령에 `--agent codex`를 붙이면 Codex 기록과 설정을 선택합니다. 이 옵션은 전역 기본값을 바꾸지 않습니다.
7
+
8
+ ## 설치
9
+
10
+ ```sh
11
+ npm i -g sprag-cli
12
+ ```
13
+
14
+ Codex가 설치되어 있으면 패키지 설치가 Claude Code 연동, 추천 룰과 함께 Codex도 설정합니다.
15
+ 설치 중에 묻는 것은 없으며, 단계마다 확인하려면 `sprag install --manual`을 쓰십시오.
16
+ Claude Code 설정을 건드리지 않고 Codex만 쓰려면 postinstall을 건너뛰고 Codex 설치를 직접 실행합니다.
17
+
18
+ ```sh
19
+ npm i -g sprag-cli --ignore-scripts
20
+ sprag install --agent codex
21
+ ```
22
+
23
+ `sprag doctor --agent codex`는 문제가 생겼을 때 쓰는 진단 명령입니다. Codex의 `/hooks`에서 등록된 명령을
24
+ 검토하고 신뢰해야 훅이 동작합니다. 설치는 훅을 등록할 뿐 신뢰 설정을 바꾸지 않습니다.
25
+ 관리자 정책이나 `features.hooks = false` 설정이 훅을 막을 수도 있습니다.
26
+
27
+ 설정 위치는 `$CODEX_HOME`이며, 지정하지 않으면 `~/.codex`입니다. 설치는 `hooks.json`과
28
+ 전역 `AGENTS.md`에 Sprag 항목을 추가하고 기존 내용을 보존합니다. 비어 있지 않은
29
+ `AGENTS.override.md`가 있으면 그 파일을 사용하며, 변경 전 사본을 남깁니다.
30
+ Claude 설정이나 `config.toml`은 고치지 않습니다.
31
+
32
+ macOS zsh 환경에서는 설치가 tmux 설치 여부를 먼저 확인합니다. tmux가 없으면 Homebrew로 설치하고,
33
+ `CTS_NO_TMUX=1`을 지정하면 이 단계를 건너뜁니다. 이어서 zsh 연동을 추가해 `codex`를 입력하면 같은
34
+ 터미널 안에 패널이 인라인으로 붙으며, 이때는 별도 창을 여는 훅을 등록하지 않습니다. tmux를 설치할 수
35
+ 없거나 로그인 셸이 zsh가 아니거나 이미 사용자의 `codex` 별칭·함수가 있으면 별도 Terminal 창 방식으로
36
+ 대신 동작합니다. `sprag panel shell remove --agent codex`로 끈 설정은 재설치와 업그레이드에도 그대로
37
+ 유지되며, `--no-panel`은 tmux 설정과 zsh 연동을 모두 건너뜁니다.
38
+ `sprag panel auto off --agent codex`로 끈 설정은 재설치해도 유지합니다.
39
+ 패널 실행 여부는 `sprag panel doctor --agent codex`로 확인하십시오.
40
+
41
+ ## 지원 기능
42
+
43
+ | 기능 | Codex 동작 |
44
+ |---|---|
45
+ | 하네스 | 전역·프로젝트 AGENTS.md에 다섯 원칙을 등록합니다 |
46
+ | 래칫 규칙 | 전역·프로젝트 규칙을 세션 시작과 재개 시 전달합니다 |
47
+ | 반복 실패 탐지 | 최근 명령·패치 실패에서 `ratchet?` 후보를 찾습니다 |
48
+ | 위임 후보 | 프로젝트·공급자·상위 모델별로 반복된 단순 작업을 찾습니다 |
49
+ | seed | 호환되는 래칫 프리셋을 제안하고 응답을 별도 저장합니다 |
50
+ | 문서 변환 | PDF·Office·Figma 문서를 Markdown으로 변환하고 캐시 덮어쓰기를 막습니다 |
51
+ | 한국어 검사 | 파일 쓰기 후 문체 위반을 검사하며 block·warn·off를 지원합니다 |
52
+ | 상태 표시 | 별도 패널, tmux 패널, 일회성 상태줄을 제공합니다 |
53
+ | 브리핑·이력 | 최신 컨텍스트와 사용량 경고를 알리고 세션별로 저장합니다 |
54
+ | 위임 원장 | Sprag가 위임한 하위 실행과 LiteLLM 단가로 예상 차액을 계산합니다 |
55
+
56
+ ## 패널과 보고서
57
+
58
+ ```sh
59
+ sprag panel --agent codex
60
+ sprag panel run --agent codex --
61
+ sprag --statusline --text --agent codex
62
+ sprag --agent codex --days 7 --format json
63
+ sprag brief --agent codex
64
+ sprag history --agent codex --days 7
65
+ sprag handoff --agent codex
66
+ ```
67
+
68
+ 별도 패널은 현재 프로젝트의 최신 기본 세션을 따릅니다. `--session ID`를 붙이면 특정 세션을
69
+ 고정합니다. tmux 패널은 실행마다 별도 연결 파일을 사용하므로 같은 프로젝트의 다른 세션이
70
+ 화면을 차지하지 않습니다. 연결 전에는 대기 상태를 표시합니다. 일부 Codex 버전은 첫 프롬프트를
71
+ 제출한 뒤에 SessionStart 훅을 실행하므로 그때 패널 연결이 이루어집니다.
72
+
73
+ tmux 실행은 `--no-daemon`과 호출별 상태줄 설정을 사용합니다. Codex의 모델·추론 수준과
74
+ 설정 파일은 바꾸지 않으며, `--keep-native-statusline`으로 기존 상태줄을 유지할 수 있습니다.
75
+ 패널은 Codex 기본 상태줄에 셸 명령을 넣는 방식이 아닙니다.
76
+
77
+ 설치는 이제 이 연동을 기본으로 추가합니다. macOS zsh에서 `codex`를 입력할 때 tmux 패널을 함께 열려면
78
+ 다음 명령을 사용하십시오. 기존 별칭이나 함수는 덮어쓰지 않습니다.
79
+
80
+ ```sh
81
+ sprag panel shell install --agent codex
82
+ sprag panel shell remove --agent codex
83
+ ```
84
+
85
+ 사용량은 로컬 `sessions`와 `archived_sessions`의 rollout 기록에서 읽습니다. 중복된 누적 토큰을
86
+ 다시 더하지 않으며, 캐시 입력과 추론 출력도 각각 입력·출력에 이미 포함된 부분으로 처리합니다.
87
+ 기록은 안정된 공개 API가 아니므로 일부가 빠지거나 형식이 바뀌면 값이 불완전할 수 있습니다.
88
+ 사용량 갱신 횟수는 정확한 API 호출 횟수가 아닙니다.
89
+
90
+ ## 위임 후보와 프리셋
91
+
92
+ ```sh
93
+ sprag route-scan --refresh --agent codex
94
+ sprag delegate rules add R1 --project --agent codex
95
+ sprag route-scan dismiss R1 --agent codex
96
+ sprag delegate on --agent codex
97
+ sprag seed --agent codex
98
+ sprag seed accept all --project --agent codex
99
+ sprag seed skip all --agent codex
100
+ sprag seed reset --agent codex
101
+ ```
102
+
103
+ 위임 후보에는 같은 유형의 완료된 단순 작업이 세 번 이상 필요합니다. 중단된 작업과 이미 위임한
104
+ 작업, 오류가 많은 작업, 도중에 사용자가 방향을 바꾼 작업은 제외합니다. 같은 세션의 보관 사본도
105
+ 중복 집계하지 않습니다. 등록 전에는 사용자가 전역과 프로젝트 중 적용 범위를 정해야 합니다.
106
+
107
+ 단가와 실행 근거를 확인할 수 있으면 더 저렴한 모델을 제안합니다. 단가가 없으면 후보를 유지하되
108
+ 등록할 때 `--model ID`를 요구합니다. 모델 사용 가능 여부는 실제 공급자 설정에 달려 있습니다.
109
+ 명시한 모델과 사용자 정의 역할은 유지하며, 사용할 수 없는 하위 에이전트 도구를 만들어 내지 않습니다.
110
+
111
+ SessionStart는 캐시된 후보를 읽고 필요할 때 별도 프로세스에서 갱신합니다. 명시적인 `--refresh`는
112
+ 대기 주기를 건너뜁니다. `seed`는 Claude의 Haiku·Sonnet 프리셋을 가져오지 않으며,
113
+ Codex의 수락·거절 기록도 Claude 기록과 분리합니다.
114
+
115
+ ## 래칫 규칙
116
+
117
+ ```sh
118
+ sprag harness init --project --agent codex
119
+ sprag harness promote "Run the changed module's tests before completion." --project --agent codex
120
+ sprag harness list --project --agent codex
121
+ sprag harness promote 1 --session SESSION_ID --project --agent codex
122
+ sprag harness prune --global --older-than 6 --dry-run --agent codex
123
+ ```
124
+
125
+ 규칙은 `<프로젝트>/.codex/ratchet.md`나 `$CODEX_HOME/ratchet.md`에 저장합니다.
126
+ 반복 실패 탐지는 최근 2 MiB, 도구가 실행된 30턴, 30분 범위를 확인합니다. 검색 결과가 없다는
127
+ 종료 코드 등은 제외합니다. 숫자로 후보를 등록하면 원인과 예방책을 적을 TODO가 생기므로,
128
+ 원인을 확인한 뒤 완전한 조건·행동 규칙으로 다듬어야 합니다. 후보 번호는 세션별 임시 값입니다.
129
+
130
+ ## 문서와 문체
131
+
132
+ ```sh
133
+ sprag doc2md install-converter --agent codex
134
+ sprag doc2md report.pdf --agent codex
135
+ sprag korean on --agent codex
136
+ sprag korean lint warn --agent codex
137
+ sprag cohesion on --agent codex
138
+ ```
139
+
140
+ 문서 변환기는 Claude와 공유하지만 Codex는 별도 Markdown 뷰와 문서 누계를 사용합니다.
141
+ 변환 캐시를 고쳐도 원본에는 반영되지 않습니다. 문서를 수정하려면 원본을 복사하고 형식을
142
+ 지원하는 라이브러리로 복사본을 편집한 뒤 다시 변환하십시오. 텍스트 추출만으로 차트·이미지·배치를
143
+ 검증했다고 말할 수 없습니다. 실패와 잘린 결과는 그대로 보고해야 합니다.
144
+
145
+ 훅은 지원되는 파일 읽기와 단순한 `cat`·`head`·`tail`, 인식 가능한 쓰기 대상을 처리합니다.
146
+ 임의의 추출 스크립트나 복합 셸 명령을 모두 가로채지는 않습니다. `doc2md off`는 Codex의 자동
147
+ 변환과 문서 쓰기 보호를 끕니다. 문체 설정은 공유하지만 기능을 켤 때는 Codex 훅을 먼저 등록합니다.
148
+
149
+ ## 단가와 한계
150
+
151
+ ```sh
152
+ sprag route-scan savings --refresh --agent codex
153
+ sprag cache status --refresh --agent codex
154
+ sprag capabilities --agent codex
155
+ ```
156
+
157
+ 위임 원장은 Sprag가 실행 시 기록한 route ID와 하위 세션 기록이 일치할 때만 집계합니다.
158
+ 하위 실행의 토큰을 고정하고 부모·자식 단가를 각각 적용한 차이이므로, 실제 청구서의 절감액은
159
+ 아닙니다. 손해는 음수로 남기며 단가나 사용량이 없으면 0 대신 미상으로 표시합니다.
160
+
161
+ 단가는 설정된 LiteLLM의 `/model/info`에서 읽습니다. 공급자가 다른 동명 모델을 섞지 않고,
162
+ 같은 별칭 아래 배포 단가가 다르면 계산하지 않습니다. 단가 캐시는 7일 동안 사용하며 이미
163
+ 계산한 실행은 단가 사본을 보존합니다. 직접 OpenAI 연결이나 구독 요금은 추정하지 않습니다.
164
+ 위임 후 `--refresh`로 원장을 갱신할 수 있고, 아직 일치하지 않은 기록은 7일 동안 찾습니다.
165
+
166
+ 캐시 타이머는 확인된 공급자 정책과 기록된 캐시 사용 시각을 보여 줍니다. 정확한 만료 시각이나
167
+ 다음 요청의 적중을 보장하지 않습니다. 패널의 LiteLLM 예산·단가 조회는 기존 인증 정보를
168
+ 사용하며, 원본 세션 내용을 전송하지 않습니다. 일회성 상태줄은 저장된 정보만 읽습니다.
169
+
170
+ ## 제거와 업그레이드
171
+
172
+ ```sh
173
+ sprag uninstall --agent codex
174
+ npm i -g sprag-cli --ignore-scripts
175
+ sprag install --agent codex
176
+ ```
177
+
178
+ 제거는 Codex 훅과 전역 하네스 블록만 대상으로 합니다. 프로젝트 하네스, 래칫 규칙, 백업과
179
+ 공유 상태는 남습니다. 일반 npm 설치는 Claude postinstall을 실행하므로 Codex만 사용한다면
180
+ 업그레이드에도 `--ignore-scripts`를 유지하십시오.
181
+
182
+ 공식 인터페이스는 [Codex 훅](https://developers.openai.com/codex/hooks/)과
183
+ [AGENTS.md 안내](https://developers.openai.com/codex/guides/agents-md/),
184
+ [설정 참조](https://developers.openai.com/codex/config-reference/)에서 확인할 수 있습니다.