aiopt 0.2.4 → 0.2.6
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.md +47 -83
- package/dist/cli.js +159 -28
- package/dist/cli.js.map +1 -1
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -4,7 +4,14 @@
|
|
|
4
4
|
[](https://github.com/tkddlr0716-collab/aiopt/actions/workflows/ci.yml)
|
|
5
5
|
[](./LICENSE)
|
|
6
6
|
|
|
7
|
-
**
|
|
7
|
+
AIOpt is a **pre-deploy cost accident guardrail** for LLM changes.
|
|
8
|
+
- baseline = your observed local usage log (`usage.jsonl` / `usage.csv`)
|
|
9
|
+
- candidate = estimated change (model/provider/context/output/retry/traffic deltas)
|
|
10
|
+
- output = deterministic verdict + monthly impact estimate + confidence
|
|
11
|
+
|
|
12
|
+
No server. No upload. No account. No payments inside the CLI.
|
|
13
|
+
|
|
14
|
+
## 3-line quickstart (Guardrail)
|
|
8
15
|
```bash
|
|
9
16
|
npx aiopt install --force
|
|
10
17
|
# baseline: your existing usage log
|
|
@@ -16,21 +23,16 @@ Exit codes:
|
|
|
16
23
|
- `2` WARN (cost accident possible)
|
|
17
24
|
- `3` FAIL (merge-blocking)
|
|
18
25
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
- **Baseline** = your observed usage log (`usage.jsonl` / `usage.csv`)
|
|
25
|
-
- **Candidate** = an estimated change (model/provider/context/output/retry deltas)
|
|
26
|
-
- Output = a deterministic verdict + monthly impact estimate + confidence
|
|
27
|
-
- Designed for CI: fast, local, no network calls (beyond downloading the npm package)
|
|
26
|
+
Common knobs:
|
|
27
|
+
- `--context-mult <n>` (prompt/context grows)
|
|
28
|
+
- `--output-mult <n>` (output grows)
|
|
29
|
+
- `--retries-delta <n>` (more retries/attempts)
|
|
30
|
+
- `--call-mult <n>` (traffic spike / call volume)
|
|
28
31
|
|
|
29
32
|
## CI integration (GitHub Actions)
|
|
30
33
|
You can run `aiopt guard` in CI to catch accidental cost blow-ups before merge.
|
|
31
34
|
|
|
32
35
|
### 1) Non-blocking (report only)
|
|
33
|
-
|
|
34
36
|
```yaml
|
|
35
37
|
- name: AI cost guard (non-blocking)
|
|
36
38
|
run: |
|
|
@@ -38,56 +40,34 @@ You can run `aiopt guard` in CI to catch accidental cost blow-ups before merge.
|
|
|
38
40
|
```
|
|
39
41
|
|
|
40
42
|
### 2) Merge-blocking (fail on high risk)
|
|
41
|
-
|
|
42
43
|
```yaml
|
|
43
44
|
- name: AI cost guard (blocking)
|
|
44
45
|
run: |
|
|
45
46
|
npx aiopt guard --input ./aiopt-output/usage.jsonl --context-mult 1.2
|
|
46
47
|
```
|
|
47
48
|
|
|
48
|
-
|
|
49
|
-
- Keep a small representative baseline log in the repo (or in CI artifacts) for deterministic checks.
|
|
50
|
-
- Use the wrapper (`npx aiopt install --force`) to record baseline locally during dev.
|
|
49
|
+
Tip: print guard output into the GitHub Actions **Step Summary** so you don’t need to scroll logs.
|
|
51
50
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
51
|
+
## Optional: local dashboard
|
|
52
|
+
```bash
|
|
53
|
+
npx aiopt dashboard --port 3010
|
|
54
|
+
```
|
|
55
|
+
- Binds to **127.0.0.1** (local-only)
|
|
56
|
+
- Reads local JSONL/CSV → renders locally
|
|
56
57
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
Pricing/flow: `docs/PRODUCT_PRICING_AND_FLOW.md`
|
|
58
|
+
## Optional: deeper local analysis (`scan`)
|
|
59
|
+
`scan` generates a more detailed local report + patch stubs (still local-only).
|
|
60
60
|
|
|
61
|
-
## What you get
|
|
62
61
|
After `scan`, you will have:
|
|
63
|
-
1) `./aiopt-output/analysis.json`
|
|
64
|
-
2) `./aiopt-output/report.md`
|
|
65
|
-
3) `./aiopt-output/report.json`
|
|
66
|
-
4) `./aiopt-output/patches/*`
|
|
67
|
-
5) `./aiopt-output/cost-policy.json`
|
|
68
|
-
|
|
69
|
-
### Sample `report.txt`
|
|
70
|
-
```
|
|
71
|
-
총비용: $0.23
|
|
72
|
-
절감 가능 금액(Estimated): $0.21
|
|
73
|
-
절감 근거 3줄:
|
|
74
|
-
a) 모델 라우팅 절감(추정): $0.07
|
|
75
|
-
b) 컨텍스트 감축(추정): $0.02 (상위 20% input에 25% 감축 가정)
|
|
76
|
-
c) 재시도/오류 낭비(상한 적용): $0.13
|
|
77
|
-
```
|
|
78
|
-
|
|
79
|
-
### Sample console output
|
|
80
|
-
```
|
|
81
|
-
Top Fix 3:
|
|
82
|
-
1) Retry tuning ($0.01)
|
|
83
|
-
2) Output cap (no issue detected)
|
|
84
|
-
3) Routing rule (no issue detected)
|
|
85
|
-
Report: aiopt-output/report.md
|
|
86
|
-
```
|
|
62
|
+
1) `./aiopt-output/analysis.json`
|
|
63
|
+
2) `./aiopt-output/report.md`
|
|
64
|
+
3) `./aiopt-output/report.json`
|
|
65
|
+
4) `./aiopt-output/patches/*`
|
|
66
|
+
5) `./aiopt-output/cost-policy.json`
|
|
87
67
|
|
|
88
68
|
## Input (default)
|
|
89
69
|
- Default path: `./aiopt-output/usage.jsonl`
|
|
90
|
-
- Change: `npx aiopt
|
|
70
|
+
- Change: `npx aiopt guard --input <path>`
|
|
91
71
|
- Supported: JSONL (1 event per line), CSV
|
|
92
72
|
|
|
93
73
|
AIOpt supports both:
|
|
@@ -104,45 +84,29 @@ For wrapper logs:
|
|
|
104
84
|
Optional:
|
|
105
85
|
- `billed_cost` (aggregated) or `cost_usd` (wrapper)
|
|
106
86
|
|
|
107
|
-
### JSONL example (5 lines)
|
|
108
|
-
```jsonl
|
|
109
|
-
{"ts":"2026-02-07T00:00:01Z","provider":"openai","model":"gpt-5-mini","input_tokens":12000,"output_tokens":1800,"feature_tag":"summarize","retries":0,"status":"ok"}
|
|
110
|
-
{"ts":"2026-02-07T00:00:02Z","provider":"openai","model":"gpt-5.2","input_tokens":35000,"output_tokens":3000,"feature_tag":"coding","retries":1,"status":"ok"}
|
|
111
|
-
{"ts":"2026-02-07T00:00:03Z","provider":"anthropic","model":"claude-sonnet","input_tokens":22000,"output_tokens":2500,"feature_tag":"classify","retries":0,"status":"ok"}
|
|
112
|
-
{"ts":"2026-02-07T00:00:04Z","provider":"gemini","model":"gemini-1.5-flash","input_tokens":9000,"output_tokens":1200,"feature_tag":"translate","retries":0,"status":"ok"}
|
|
113
|
-
{"ts":"2026-02-07T00:00:05Z","provider":"openai","model":"unknown-model-x","input_tokens":8000,"output_tokens":1000,"feature_tag":"summarize","retries":2,"status":"error"}
|
|
114
|
-
```
|
|
115
|
-
|
|
116
|
-
## Outputs
|
|
117
|
-
- `analysis.json`
|
|
118
|
-
- `total_cost`
|
|
119
|
-
- `by_model_top` (top 10)
|
|
120
|
-
- `by_feature_top` (top 10)
|
|
121
|
-
- `unknown_models`
|
|
122
|
-
- `rate_table_version`, `rate_table_date`
|
|
123
|
-
- `report.md`
|
|
124
|
-
- WHAT TO CHANGE (file paths + keys)
|
|
125
|
-
- confidence + assumptions
|
|
126
|
-
- `report.json`
|
|
127
|
-
- summary + warnings + assumptions
|
|
128
|
-
- `patches/*`
|
|
129
|
-
- `policies.updated.*` stubs
|
|
130
|
-
- `cost-policy.json`
|
|
131
|
-
- `version, default_provider, rules, budgets, generated_from`
|
|
132
|
-
|
|
133
87
|
## Rate table
|
|
134
88
|
- `./rates/rate_table.json`
|
|
135
|
-
- Unknown models/providers
|
|
89
|
+
- Unknown models/providers may be marked as `Estimated`.
|
|
136
90
|
- `provider=local` (or `ollama`/`vllm`) is treated as **$0** by default (CPU/GPU cost not included).
|
|
137
91
|
|
|
138
|
-
##
|
|
139
|
-
-
|
|
92
|
+
## Known caveats
|
|
93
|
+
- If your baseline log covers a very short `ts` span, confidence may be degraded (data quality).
|
|
94
|
+
- The local dashboard binds to **127.0.0.1** only.
|
|
95
|
+
- Local providers are assumed **$0** by default (infra cost not included).
|
|
140
96
|
|
|
141
|
-
##
|
|
97
|
+
## License (offline)
|
|
98
|
+
If you have a signed license key:
|
|
142
99
|
```bash
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
node dist/cli.js doctor
|
|
147
|
-
node dist/cli.js scan
|
|
100
|
+
npx aiopt license activate <LICENSE_KEY>
|
|
101
|
+
npx aiopt license status
|
|
102
|
+
npx aiopt license verify
|
|
148
103
|
```
|
|
104
|
+
|
|
105
|
+
## Docs
|
|
106
|
+
- Install-first guide: `aiopt/README.md`
|
|
107
|
+
- Platform support / caveats: `docs/PLATFORM_SUPPORT.md`
|
|
108
|
+
- Pricing/flow (internal): `docs/PRODUCT_PRICING_AND_FLOW.md`
|
|
109
|
+
- Payment/license ops: `docs/PAYMENT.md`
|
|
110
|
+
|
|
111
|
+
## Contact
|
|
112
|
+
- Instagram: **@sangikpp**
|
package/dist/cli.js
CHANGED
|
@@ -415,8 +415,8 @@ var require_package = __commonJS({
|
|
|
415
415
|
"package.json"(exports2, module2) {
|
|
416
416
|
module2.exports = {
|
|
417
417
|
name: "aiopt",
|
|
418
|
-
version: "0.2.
|
|
419
|
-
description: "
|
|
418
|
+
version: "0.2.6",
|
|
419
|
+
description: "Pre-deploy LLM cost accident guardrail (serverless local CLI)",
|
|
420
420
|
bin: {
|
|
421
421
|
aiopt: "dist/cli.js"
|
|
422
422
|
},
|
|
@@ -434,7 +434,8 @@ var require_package = __commonJS({
|
|
|
434
434
|
prepack: "npm run build",
|
|
435
435
|
"test:npx": `npm pack --silent && node -e "const fs=require('fs');const p=fs.readdirSync('.').find(f=>/^aiopt-.*\\.tgz$/.test(f)); if(!p) throw new Error('tgz not found'); console.log('tgz',p);" && npx --yes ./$(ls -1 aiopt-*.tgz | tail -n 1) install --force && npx --yes ./$(ls -1 aiopt-*.tgz | tail -n 1) doctor && npx --yes ./$(ls -1 aiopt-*.tgz | tail -n 1) scan && test -f ./aiopt-output/report.md && echo OK`,
|
|
436
436
|
"test:guard": "npm run build --silent && node scripts/test-guard.js",
|
|
437
|
-
"test:license": "npm run build --silent && node scripts/test-license.js"
|
|
437
|
+
"test:license": "npm run build --silent && node scripts/test-license.js",
|
|
438
|
+
"test:landing": "node scripts/test-landing.js"
|
|
438
439
|
},
|
|
439
440
|
dependencies: {
|
|
440
441
|
commander: "^14.0.0",
|
|
@@ -1103,46 +1104,176 @@ async function startDashboard(cwd, opts) {
|
|
|
1103
1104
|
}
|
|
1104
1105
|
}
|
|
1105
1106
|
const indexHtml = `<!doctype html>
|
|
1106
|
-
<html>
|
|
1107
|
+
<html lang="en">
|
|
1107
1108
|
<head>
|
|
1108
1109
|
<meta charset="utf-8"/>
|
|
1109
1110
|
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
|
1110
1111
|
<title>AIOpt Local Dashboard</title>
|
|
1111
1112
|
<style>
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1113
|
+
:root{
|
|
1114
|
+
--bg:#070b16; --card:#0b1222; --card2:#0e1730; --txt:#e7eaf2; --muted:#a3acc2;
|
|
1115
|
+
--border:rgba(255,255,255,.10);
|
|
1116
|
+
--ok:#34d399; --warn:#fbbf24; --fail:#fb7185;
|
|
1117
|
+
--shadow:0 18px 70px rgba(0,0,0,.35);
|
|
1118
|
+
}
|
|
1119
|
+
*{box-sizing:border-box}
|
|
1120
|
+
body{margin:0; font-family: ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto; background:var(--bg); color:var(--txt)}
|
|
1121
|
+
a{color:#bfffe3; text-decoration:none} a:hover{text-decoration:underline}
|
|
1122
|
+
.wrap{max-width:1100px; margin:0 auto; padding:18px}
|
|
1123
|
+
.top{display:flex; align-items:center; justify-content:space-between; gap:10px; flex-wrap:wrap}
|
|
1124
|
+
.h1{font-size:22px; font-weight:950; letter-spacing:-.02em}
|
|
1125
|
+
.pill{display:inline-flex; align-items:center; gap:8px; padding:7px 10px; border-radius:999px; border:1px solid var(--border);
|
|
1126
|
+
background:rgba(255,255,255,.03); color:var(--muted); font-size:12px; line-height:1}
|
|
1127
|
+
.dot{width:8px;height:8px;border-radius:99px;background:linear-gradient(90deg,#60a5fa,#34d399)}
|
|
1128
|
+
|
|
1129
|
+
.grid{display:grid; grid-template-columns:repeat(12,1fr); gap:12px; margin-top:12px}
|
|
1130
|
+
.card{grid-column: span 12; background:linear-gradient(180deg, rgba(255,255,255,.03), rgba(255,255,255,0)), var(--card);
|
|
1131
|
+
border:1px solid var(--border); border-radius:18px; padding:14px; box-shadow: var(--shadow)}
|
|
1132
|
+
@media(min-width: 920px){
|
|
1133
|
+
.c6{grid-column: span 6}
|
|
1134
|
+
.c4{grid-column: span 4}
|
|
1135
|
+
.c8{grid-column: span 8}
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
.k{padding:2px 6px; border-radius:8px; border:1px solid var(--border); font-family: ui-monospace; font-size:12px; color:#d7def2; background:rgba(255,255,255,.03)}
|
|
1139
|
+
.muted{color:var(--muted)}
|
|
1140
|
+
.row{display:flex; gap:10px; flex-wrap:wrap; align-items:center}
|
|
1141
|
+
|
|
1142
|
+
.badge{display:inline-flex; align-items:center; gap:8px; padding:8px 10px; border-radius:14px; border:1px solid var(--border);
|
|
1143
|
+
background:rgba(255,255,255,.03); font-weight:900}
|
|
1144
|
+
.badge.ok{border-color:rgba(52,211,153,.35)}
|
|
1145
|
+
.badge.warn{border-color:rgba(251,191,36,.35)}
|
|
1146
|
+
.badge.fail{border-color:rgba(251,113,133,.35)}
|
|
1147
|
+
.badge .b{width:10px;height:10px;border-radius:99px}
|
|
1148
|
+
.badge.ok .b{background:var(--ok)}
|
|
1149
|
+
.badge.warn .b{background:var(--warn)}
|
|
1150
|
+
.badge.fail .b{background:var(--fail)}
|
|
1151
|
+
|
|
1152
|
+
pre{margin:0; white-space:pre-wrap; word-break:break-word; background: rgba(3,6,14,.65);
|
|
1153
|
+
border:1px solid rgba(255,255,255,.12);
|
|
1154
|
+
padding:12px; border-radius:14px;
|
|
1155
|
+
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono"; font-size:13px; line-height:1.55}
|
|
1156
|
+
|
|
1157
|
+
.bars{display:flex; flex-direction:column; gap:8px; margin-top:8px}
|
|
1158
|
+
.bar{display:grid; grid-template-columns: 1fr 64px; gap:10px; align-items:center}
|
|
1159
|
+
.track{height:10px; border-radius:999px; background:rgba(255,255,255,.08); overflow:hidden; border:1px solid rgba(255,255,255,.10)}
|
|
1160
|
+
.fill{height:100%; border-radius:999px; background:linear-gradient(90deg,#60a5fa,#34d399)}
|
|
1161
|
+
.label{font-size:13px}
|
|
1162
|
+
.val{font-family: ui-monospace; font-size:12px; color:#d7def2; text-align:right}
|
|
1163
|
+
|
|
1164
|
+
.mini{font-size:12px; color:var(--muted)}
|
|
1117
1165
|
</style>
|
|
1118
1166
|
</head>
|
|
1119
1167
|
<body>
|
|
1120
|
-
<
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
<div class="card">
|
|
1125
|
-
<h2>Last Guard</h2>
|
|
1126
|
-
<div id="guardMeta"></div>
|
|
1127
|
-
<pre id="guard">loading...</pre>
|
|
1128
|
-
<p><a href="/api/guard-last.txt" target="_blank">raw</a></p>
|
|
1168
|
+
<div class="wrap">
|
|
1169
|
+
<div class="top">
|
|
1170
|
+
<div class="h1">AIOpt Local Dashboard</div>
|
|
1171
|
+
<div class="pill"><span class="dot"></span> local-only \xB7 reads <span class="k">./aiopt-output</span></div>
|
|
1129
1172
|
</div>
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
<
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1173
|
+
|
|
1174
|
+
<div class="grid">
|
|
1175
|
+
<div class="card c6">
|
|
1176
|
+
<div class="row" style="justify-content:space-between">
|
|
1177
|
+
<div style="font-weight:950">Guard verdict</div>
|
|
1178
|
+
<div class="mini" id="guardMeta">\u2014</div>
|
|
1179
|
+
</div>
|
|
1180
|
+
<div style="height:8px"></div>
|
|
1181
|
+
<div id="guardBadge" class="badge"><span class="b"></span><span id="guardBadgeText">loading\u2026</span></div>
|
|
1182
|
+
<div style="height:10px"></div>
|
|
1183
|
+
<pre id="guard">loading\u2026</pre>
|
|
1184
|
+
<div style="height:10px"></div>
|
|
1185
|
+
<div class="row">
|
|
1186
|
+
<a href="/api/guard-last.txt" target="_blank">raw txt</a>
|
|
1187
|
+
<span class="muted">\xB7</span>
|
|
1188
|
+
<a href="/api/guard-last.json" target="_blank">raw json</a>
|
|
1189
|
+
</div>
|
|
1190
|
+
</div>
|
|
1191
|
+
|
|
1192
|
+
<div class="card c6">
|
|
1193
|
+
<div class="row" style="justify-content:space-between">
|
|
1194
|
+
<div style="font-weight:950">Scan summary</div>
|
|
1195
|
+
<div class="mini"><a href="/api/report.json" target="_blank">report.json</a> \xB7 <a href="/api/report.md" target="_blank">report.md</a></div>
|
|
1196
|
+
</div>
|
|
1197
|
+
<div style="height:8px"></div>
|
|
1198
|
+
<div class="row">
|
|
1199
|
+
<div class="badge" id="totalCostBadge"><span class="b" style="background:#60a5fa"></span><span id="totalCost">total: \u2014</span></div>
|
|
1200
|
+
<div class="badge" id="savingsBadge"><span class="b" style="background:#a78bfa"></span><span id="savings">savings: \u2014</span></div>
|
|
1201
|
+
</div>
|
|
1202
|
+
|
|
1203
|
+
<div style="height:12px"></div>
|
|
1204
|
+
<div style="font-weight:900">Cost by model</div>
|
|
1205
|
+
<div id="byModel" class="bars"></div>
|
|
1206
|
+
|
|
1207
|
+
<div style="height:12px"></div>
|
|
1208
|
+
<div style="font-weight:900">Cost by feature</div>
|
|
1209
|
+
<div id="byFeature" class="bars"></div>
|
|
1210
|
+
|
|
1211
|
+
<div style="height:10px"></div>
|
|
1212
|
+
<div class="mini" id="scanMeta">\u2014</div>
|
|
1213
|
+
</div>
|
|
1214
|
+
|
|
1215
|
+
<div class="card">
|
|
1216
|
+
<div class="row" style="justify-content:space-between">
|
|
1217
|
+
<div style="font-weight:950">Latest report.md</div>
|
|
1218
|
+
<div class="mini">Tip: run <span class="k">aiopt scan</span> after collecting baseline</div>
|
|
1219
|
+
</div>
|
|
1220
|
+
<div style="height:8px"></div>
|
|
1221
|
+
<pre id="scan">loading\u2026</pre>
|
|
1222
|
+
</div>
|
|
1137
1223
|
</div>
|
|
1138
1224
|
</div>
|
|
1139
1225
|
|
|
1140
1226
|
<script>
|
|
1141
|
-
|
|
1227
|
+
function money(x){
|
|
1228
|
+
if (x === null || x === undefined || Number.isNaN(Number(x))) return '\u2014';
|
|
1229
|
+
return '$' + (Math.round(Number(x)*100)/100);
|
|
1230
|
+
}
|
|
1231
|
+
function renderBars(el, items){
|
|
1232
|
+
el.innerHTML='';
|
|
1233
|
+
if(!items || items.length===0){ el.innerHTML='<div class="mini">(no data)</div>'; return; }
|
|
1234
|
+
const max = Math.max(...items.map(i=>Number(i.cost)||0), 0.000001);
|
|
1235
|
+
for(const it of items.slice(0,8)){
|
|
1236
|
+
const w = Math.max(2, Math.round(((Number(it.cost)||0)/max)*100));
|
|
1237
|
+
const row = document.createElement('div');
|
|
1238
|
+
row.className='bar';
|
|
1239
|
+
row.innerHTML =
|
|
1240
|
+
'<div>'+
|
|
1241
|
+
'<div class="label">'+ String(it.key) +'</div>'+
|
|
1242
|
+
'<div class="track"><div class="fill" style="width:'+ w +'%"></div></div>'+
|
|
1243
|
+
'</div>'+
|
|
1244
|
+
'<div class="val">'+ money(it.cost) +'</div>';
|
|
1245
|
+
el.appendChild(row);
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
async function load(){
|
|
1142
1250
|
const guardTxt = await fetch('/api/guard-last.txt').then(r=>r.ok?r.text():null);
|
|
1143
1251
|
const guardMeta = await fetch('/api/guard-last.json').then(r=>r.ok?r.json():null);
|
|
1144
|
-
|
|
1145
|
-
document.getElementById('
|
|
1252
|
+
|
|
1253
|
+
document.getElementById('guard').textContent = guardTxt || '(no guard-last.txt yet \u2014 run: aiopt guard)';
|
|
1254
|
+
if(guardMeta){
|
|
1255
|
+
document.getElementById('guardMeta').textContent = 'exit=' + guardMeta.exitCode + ' \xB7 ' + guardMeta.ts;
|
|
1256
|
+
const badge = document.getElementById('guardBadge');
|
|
1257
|
+
const t = document.getElementById('guardBadgeText');
|
|
1258
|
+
const code = Number(guardMeta.exitCode);
|
|
1259
|
+
badge.classList.remove('ok','warn','fail');
|
|
1260
|
+
if(code===0){badge.classList.add('ok'); t.textContent='OK (0)';}
|
|
1261
|
+
else if(code===2){badge.classList.add('warn'); t.textContent='WARN (2)';}
|
|
1262
|
+
else {badge.classList.add('fail'); t.textContent='FAIL (3)';}
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
const reportJson = await fetch('/api/report.json').then(r=>r.ok?r.json():null);
|
|
1266
|
+
if(reportJson){
|
|
1267
|
+
const total = reportJson.summary && reportJson.summary.total_cost_usd;
|
|
1268
|
+
const sav = reportJson.summary && reportJson.summary.estimated_savings_usd;
|
|
1269
|
+
document.getElementById('totalCost').textContent = 'total: ' + money(total);
|
|
1270
|
+
document.getElementById('savings').textContent = 'savings: ' + money(sav);
|
|
1271
|
+
renderBars(document.getElementById('byModel'), reportJson.top && reportJson.top.by_model);
|
|
1272
|
+
renderBars(document.getElementById('byFeature'), reportJson.top && reportJson.top.by_feature);
|
|
1273
|
+
document.getElementById('scanMeta').textContent = 'confidence=' + (reportJson.confidence || '\u2014') + ' \xB7 generated_at=' + (reportJson.generated_at || '\u2014');
|
|
1274
|
+
} else {
|
|
1275
|
+
document.getElementById('scanMeta').textContent = '(no report.json yet \u2014 run: aiopt scan)';
|
|
1276
|
+
}
|
|
1146
1277
|
|
|
1147
1278
|
const reportMd = await fetch('/api/report.md').then(r=>r.ok?r.text():null);
|
|
1148
1279
|
document.getElementById('scan').textContent = reportMd || '(no report.md yet \u2014 run: aiopt scan)';
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cost.ts","../src/solutions.ts","../src/scan.ts","../package.json","../src/install.ts","../src/doctor.ts","../src/license.ts","../src/guard.ts","../src/dashboard.ts","../src/cli.ts","../src/io.ts"],"sourcesContent":["import { RateTable, UsageEvent } from './types';\n\nexport type CostResult = {\n cost: number;\n used_rate: {\n kind: 'billed_cost' | 'official' | 'estimated';\n provider: string;\n model: string;\n input_per_m: number;\n output_per_m: number;\n };\n};\n\nexport function getRates(rt: RateTable, provider: string, model: string) {\n const prov = String(provider || '').toLowerCase();\n\n // local/offline LLM: treat cost as 0 (or user can add a provider rate later)\n if (prov === 'local' || prov === 'ollama' || prov === 'vllm') {\n return { kind: 'official' as const, input: 0, output: 0 };\n }\n\n const p = rt.providers[prov];\n if (!p) return null;\n const m = p.models[model];\n if (m) return { kind: 'official' as const, input: m.input, output: m.output };\n return { kind: 'estimated' as const, input: p.default_estimated.input, output: p.default_estimated.output };\n}\n\nexport function costOfEvent(rt: RateTable, ev: UsageEvent): CostResult {\n if (typeof ev.billed_cost === 'number' && Number.isFinite(ev.billed_cost)) {\n return {\n cost: ev.billed_cost,\n used_rate: {\n kind: 'billed_cost',\n provider: ev.provider,\n model: ev.model,\n input_per_m: 0,\n output_per_m: 0\n }\n };\n }\n\n const r = getRates(rt, ev.provider, ev.model);\n if (!r) {\n // Unknown provider: deterministic fallback estimate (kept stable for reproducibility)\n const input_per_m = 1.0;\n const output_per_m = 4.0;\n const cost = (ev.input_tokens / 1e6) * input_per_m + (ev.output_tokens / 1e6) * output_per_m;\n return {\n cost,\n used_rate: { kind: 'estimated', provider: String(ev.provider || '').toLowerCase(), model: ev.model, input_per_m, output_per_m }\n };\n }\n\n const cost = (ev.input_tokens / 1e6) * r.input + (ev.output_tokens / 1e6) * r.output;\n return {\n cost,\n used_rate: {\n kind: r.kind,\n provider: ev.provider,\n model: ev.model,\n input_per_m: r.input,\n output_per_m: r.output\n }\n };\n}\n","import fs from 'fs';\nimport path from 'path';\nimport { AnalysisJson, Savings } from './scan';\n\nexport type Fix = {\n id: string;\n title: string;\n impact_usd: number;\n why: string;\n what_to_change: string[];\n status: 'action' | 'no-issue';\n};\n\nconst EPS = 0.0001;\n\nexport function buildTopFixes(analysis: AnalysisJson, savings: Savings): Fix[] {\n const fixes: Fix[] = [];\n\n // Retry tuning\n fixes.push({\n id: 'fix-retry-tuning',\n title: 'Retry tuning',\n impact_usd: Number(savings.retry_waste || 0),\n status: Number(savings.retry_waste || 0) > EPS ? 'action' : 'no-issue',\n why: `Retry waste is estimated at $${round2(Number(savings.retry_waste || 0))}.`,\n what_to_change: [\n 'aiopt/policies/retry.json: lower max_attempts or adjust backoff_ms',\n 'Ensure idempotency keys are stable per trace_id',\n 'Log error_code to identify retryable classes'\n ]\n });\n\n // Output cap (use context_savings as proxy impact)\n fixes.push({\n id: 'fix-output-cap',\n title: 'Output cap',\n impact_usd: Number(savings.context_savings || 0),\n status: Number(savings.context_savings || 0) > EPS ? 'action' : 'no-issue',\n why: `Context savings estimate: $${round2(Number(savings.context_savings || 0))}. Output caps prevent runaway completions.`,\n what_to_change: [\n 'aiopt/policies/output.json: set max_output_tokens_default',\n 'aiopt/policies/output.json: set per_feature caps (summarize/classify/translate)'\n ]\n });\n\n // Routing\n const topFeature = analysis.by_feature_top?.[0]?.key;\n fixes.push({\n id: 'fix-routing',\n title: 'Routing rule',\n impact_usd: Number(savings.routing_savings || 0),\n status: Number(savings.routing_savings || 0) > EPS ? 'action' : 'no-issue',\n why: `Routing savings estimate: $${round2(Number(savings.routing_savings || 0))}.`,\n what_to_change: [\n 'aiopt/policies/routing.json: route summarize/classify/translate to cheap tier',\n `Consider adding feature_tag_in for top feature: ${topFeature || '(unknown)'}`\n ]\n });\n\n // sort by impact desc, deterministic tie-break\n fixes.sort((a, b) => (b.impact_usd - a.impact_usd) || a.id.localeCompare(b.id));\n return fixes;\n}\n\nfunction round2(n: number) {\n return Math.round(n * 100) / 100;\n}\n\nexport function writePatches(outDir: string, fixes: Fix[]) {\n const patchesDir = path.join(outDir, 'patches');\n fs.mkdirSync(patchesDir, { recursive: true });\n\n const readme = [\n '# AIOpt patches (MVP)',\n '',\n 'This folder contains suggested changes you can apply locally.',\n '',\n '## Top fixes',\n ...fixes.map((f, i) => `${i + 1}. ${f.title} — ${f.why}`),\n '',\n 'Files are stubs (human review required).',\n ''\n ].join('\\n');\n\n fs.writeFileSync(path.join(patchesDir, 'README.md'), readme);\n\n // Minimal stub files to satisfy DoD naming.\n fs.writeFileSync(path.join(patchesDir, 'policies.updated.routing.json'), JSON.stringify({ note: 'apply changes to aiopt/policies/routing.json', fixes: fixes.filter(f => f.id.includes('routing')) }, null, 2));\n fs.writeFileSync(path.join(patchesDir, 'policies.updated.retry.json'), JSON.stringify({ note: 'apply changes to aiopt/policies/retry.json', fixes: fixes.filter(f => f.id.includes('retry')) }, null, 2));\n fs.writeFileSync(path.join(patchesDir, 'policies.updated.output.json'), JSON.stringify({ note: 'apply changes to aiopt/policies/output.json', fixes: fixes.filter(f => f.id.includes('output')) }, null, 2));\n}\n","import fs from 'fs';\nimport path from 'path';\nimport { RateTable, UsageEvent } from './types';\nimport { costOfEvent, getRates } from './cost';\nimport { buildTopFixes, writePatches } from './solutions';\n\nexport type AnalysisJson = {\n total_cost: number;\n by_model_top: Array<{ key: string; cost: number; events: number }>;\n by_feature_top: Array<{ key: string; cost: number; events: number }>;\n unknown_models: Array<{ provider: string; model: string; reason: string }>;\n rate_table_version: string;\n rate_table_date: string;\n};\n\nexport type Savings = {\n estimated_savings_total: number;\n routing_savings: number;\n context_savings: number;\n retry_waste: number;\n notes: [string, string, string];\n};\n\nexport type PolicyJson = {\n version: number;\n default_provider: string;\n rules: Array<any>;\n budgets: { currency: string; notes?: string };\n generated_from: { rate_table_version: string; input: string };\n};\n\nconst ROUTE_TO_CHEAP_FEATURES = new Set(['summarize', 'classify', 'translate']);\n\nfunction topN(map: Map<string, { cost: number; events: number }>, n: number) {\n return [...map.entries()]\n .map(([key, v]) => ({ key, cost: v.cost, events: v.events }))\n .sort((a, b) => b.cost - a.cost)\n .slice(0, n);\n}\n\nexport function analyze(rt: RateTable, events: UsageEvent[]): { analysis: AnalysisJson; savings: Savings; policy: PolicyJson; meta: { mode: 'attempt-log'|'legacy' } } {\n const byModel = new Map<string, { cost: number; events: number }>();\n const byFeature = new Map<string, { cost: number; events: number }>();\n const unknownModels: AnalysisJson['unknown_models'] = [];\n\n const perEventCosts: Array<{ ev: UsageEvent; cost: number }> = [];\n\n // Detect wrapper attempt-log mode: each JSONL line is an attempt (trace_id/attempt present)\n const isAttemptLog = events.some(e => (e.trace_id && String(e.trace_id).length > 0) || (e.attempt !== undefined && Number(e.attempt) > 0));\n\n let baseTotal = 0;\n let total = 0;\n for (const ev of events) {\n const cr = costOfEvent(rt, ev);\n\n baseTotal += cr.cost;\n\n if (isAttemptLog) {\n // Each event line is already one attempt; do NOT multiply by retries.\n total += cr.cost;\n } else {\n // Legacy aggregate mode: one line represents a request with retries count.\n const retries = Math.max(0, Number(ev.retries || 0));\n total += cr.cost * (1 + retries);\n }\n\n perEventCosts.push({ ev, cost: cr.cost });\n\n const mk = `${ev.provider}:${ev.model}`;\n const fk = ev.feature_tag || '(none)';\n\n const mv = byModel.get(mk) || { cost: 0, events: 0 };\n mv.cost += cr.cost; mv.events += 1;\n byModel.set(mk, mv);\n\n const fv = byFeature.get(fk) || { cost: 0, events: 0 };\n fv.cost += cr.cost; fv.events += 1;\n byFeature.set(fk, fv);\n\n const rr = getRates(rt, ev.provider, ev.model);\n if (!rr) {\n unknownModels.push({ provider: ev.provider, model: ev.model, reason: 'unknown provider (estimated)' });\n } else if (rr.kind === 'estimated') {\n unknownModels.push({ provider: ev.provider, model: ev.model, reason: 'unknown model (estimated)' });\n }\n }\n\n // --- Savings simulator (refactor): per-event before/after with caps + no double counting\n type Pot = { routing: number; context: number; retry: number; total: number; waste: number };\n const potByIdx: Pot[] = [];\n\n // Potential routing/context computed per event\n for (const { ev, cost } of perEventCosts) {\n const retries = Math.max(0, Number(ev.retries || 0));\n const attempt = Number(ev.attempt || 1);\n\n const total_i = isAttemptLog ? cost : cost * (1 + retries);\n // Retry waste:\n // - attempt-log mode: attempts >= 2 are retry waste\n // - legacy mode: base_cost * retries\n const waste_i = isAttemptLog ? (attempt >= 2 ? cost : 0) : cost * retries;\n\n let routing_i = 0;\n if (ROUTE_TO_CHEAP_FEATURES.has(String(ev.feature_tag || '').toLowerCase())) {\n const provider = ev.provider;\n const p = rt.providers[provider];\n if (p) {\n const entries = Object.entries(p.models);\n if (entries.length > 0) {\n const cheapest = entries\n .map(([name, r]) => ({ name, score: (r.input + r.output) / 2, r }))\n .sort((a, b) => a.score - b.score)[0];\n const currentRate = getRates(rt, provider, ev.model);\n if (currentRate && currentRate.kind !== 'estimated') {\n const currentCost = (ev.input_tokens / 1e6) * currentRate.input + (ev.output_tokens / 1e6) * currentRate.output;\n const cheapCost = (ev.input_tokens / 1e6) * cheapest.r.input + (ev.output_tokens / 1e6) * cheapest.r.output;\n const diff = (currentCost - cheapCost) * (1 + retries);\n routing_i = Math.max(0, diff);\n }\n }\n }\n }\n\n // context: top 20% rule is applied later by index set\n potByIdx.push({ routing: routing_i, context: 0, retry: waste_i, total: total_i, waste: waste_i });\n }\n\n // context potential assignment (deterministic): top 20% by input_tokens => 25% reduction\n // In attempt-log mode, only apply to attempt==1 to avoid overcounting retries.\n const sortedIdx = [...events.map((e, i) => ({ i, input: Number(e.input_tokens || 0), ok: !isAttemptLog || Number(e.attempt || 1) === 1 }))]\n .filter(x => x.ok)\n .sort((a, b) => b.input - a.input);\n const k = Math.max(1, Math.floor(sortedIdx.length * 0.2));\n const topIdx = new Set(sortedIdx.slice(0, k).map(x => x.i));\n for (let i = 0; i < events.length; i++) {\n if (!topIdx.has(i)) continue;\n const ev = events[i];\n const retries = Math.max(0, Number(ev.retries || 0));\n const r = getRates(rt, ev.provider, ev.model);\n if (!r) continue;\n const saveTokens = (Number(ev.input_tokens || 0)) * 0.25;\n const multiplier = isAttemptLog ? 1 : (1 + retries);\n const diff = (saveTokens / 1e6) * r.input * multiplier;\n potByIdx[i].context = Math.max(0, diff);\n }\n\n // Allocate savings without overlap (routing -> context -> retry), each capped by remaining cost.\n let routingSavings = 0;\n let contextSavings = 0;\n let retryWaste = 0;\n\n for (const p of potByIdx) {\n let remaining = p.total;\n\n const rSave = Math.min(p.routing, remaining);\n remaining -= rSave;\n routingSavings += rSave;\n\n const cSave = Math.min(p.context, remaining);\n remaining -= cSave;\n contextSavings += cSave;\n\n // Retry tuning can only save the waste portion, and cannot exceed remaining.\n const retrySave = Math.min(p.retry, remaining);\n retryWaste += retrySave;\n }\n\n const estimatedSavingsTotal = routingSavings + contextSavings + retryWaste;\n // Global guard\n const guardedSavingsTotal = Math.min(estimatedSavingsTotal, total);\n\n const analysis: AnalysisJson = {\n total_cost: round2(total),\n by_model_top: topN(byModel, 10).map(x => ({ ...x, cost: round2(x.cost) })),\n by_feature_top: topN(byFeature, 10).map(x => ({ ...x, cost: round2(x.cost) })),\n unknown_models: uniqUnknown(unknownModels),\n rate_table_version: rt.version,\n rate_table_date: rt.date\n };\n\n const savings: Savings = {\n estimated_savings_total: round2(guardedSavingsTotal),\n routing_savings: round2(routingSavings),\n context_savings: round2(contextSavings),\n retry_waste: round2(retryWaste),\n notes: [\n `a) 모델 라우팅 절감(추정): $${round2(routingSavings)}`,\n `b) 컨텍스트 감축(추정): $${round2(contextSavings)} (상위 20% input에 25% 감축 가정)` ,\n `c) 재시도/오류 낭비(상한 적용): $${round2(retryWaste)} (retries 기반)`\n ]\n };\n\n const policy: PolicyJson = buildPolicy(rt, events);\n\n return { analysis, savings, policy, meta: { mode: isAttemptLog ? 'attempt-log' : 'legacy' } };\n}\n\nfunction buildPolicy(rt: RateTable, events: UsageEvent[]): PolicyJson {\n // Default provider: most frequent\n const freq = new Map<string, number>();\n for (const ev of events) freq.set(ev.provider, (freq.get(ev.provider) || 0) + 1);\n const defaultProvider = [...freq.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] || 'openai';\n\n // For cheap features: recommend cheapest known model per provider.\n const rules: any[] = [];\n for (const provider of Object.keys(rt.providers)) {\n const p = rt.providers[provider];\n const entries = Object.entries(p.models);\n if (entries.length === 0) continue;\n const cheapest = entries\n .map(([name, r]) => ({ name, score: (r.input + r.output) / 2, r }))\n .sort((a, b) => a.score - b.score)[0];\n\n rules.push({\n match: { provider, feature_tag_in: ['summarize', 'classify', 'translate'] },\n action: { recommend_model: cheapest.name, reason: 'cheap-feature routing' }\n });\n }\n\n // Unknown models: keep (no policy)\n rules.push({ match: { model_unknown: true }, action: { keep: true, reason: 'unknown model -> no policy applied' } });\n\n return {\n version: 1,\n default_provider: defaultProvider,\n rules,\n budgets: { currency: rt.currency, notes: 'MVP: budgets not enforced' },\n generated_from: { rate_table_version: rt.version, input: './aiopt-input/usage.jsonl' }\n };\n}\n\nfunction uniqUnknown(list: AnalysisJson['unknown_models']) {\n const seen = new Set<string>();\n const out: AnalysisJson['unknown_models'] = [];\n for (const x of list) {\n const k = `${x.provider}:${x.model}:${x.reason}`;\n if (seen.has(k)) continue;\n seen.add(k);\n out.push(x);\n }\n return out;\n}\n\nfunction round2(n: number) {\n return Math.round(n * 100) / 100;\n}\n\nexport function writeOutputs(outDir: string, analysis: AnalysisJson, savings: Savings, policy: PolicyJson, meta?: { mode?: 'attempt-log'|'legacy' }) {\n const mode = meta?.mode || 'legacy';\n\n fs.mkdirSync(outDir, { recursive: true });\n\n fs.writeFileSync(path.join(outDir, 'analysis.json'), JSON.stringify(analysis, null, 2));\n\n // report.json is the “one file to parse” summary for downstream tooling.\n const unknownCount = analysis.unknown_models?.length || 0;\n // confidence: downgrade if many unknowns; keep deterministic\n const confidence = unknownCount === 0 ? 'HIGH' : (unknownCount <= 3 ? 'MED' : 'LOW');\n const ratio = analysis.total_cost > 0 ? (savings.estimated_savings_total / analysis.total_cost) : 0;\n const warnings: string[] = [];\n if (ratio >= 0.9) warnings.push('estimated savings >= 90%');\n if (unknownCount > 0) warnings.push('unknown models/providers detected (estimated pricing used)');\n\n const reportJson = {\n version: 3,\n generated_at: new Date().toISOString(),\n confidence,\n warnings,\n assumptions: {\n no_double_counting: 'routing -> context -> retry allocation per-event with remaining-cost caps',\n retry_cost_model: mode === 'attempt-log'\n ? 'attempt-log mode: total_cost is sum of attempt lines; retry_waste is sum of attempts>=2'\n : 'legacy mode: total_cost includes retries as extra attempts (base_cost*(1+retries))',\n context_model: 'top 20% by input_tokens assume 25% input reduction',\n estimated_pricing_note: unknownCount > 0 ? 'some items use estimated rates; treat savings as a band' : 'all items used known rates'\n },\n summary: {\n total_cost_usd: analysis.total_cost,\n estimated_savings_usd: savings.estimated_savings_total,\n routing_savings_usd: savings.routing_savings,\n context_savings_usd: savings.context_savings,\n retry_waste_usd: savings.retry_waste\n },\n top: {\n by_model: analysis.by_model_top,\n by_feature: analysis.by_feature_top\n },\n unknown_models: analysis.unknown_models,\n notes: savings.notes\n };\n fs.writeFileSync(path.join(outDir, 'report.json'), JSON.stringify(reportJson, null, 2));\n\n // report.md: \"what to change\" guidance + confidence/assumptions (T4 DoD)\n const ratioMd = analysis.total_cost > 0 ? (savings.estimated_savings_total / analysis.total_cost) : 0;\n const warningsMd: string[] = [];\n if (ratioMd >= 0.9) warningsMd.push('WARNING: estimated savings >= 90% — check overlap/missing rate table');\n\n const reportMd = [\n '# AIOpt Report',\n '',\n `- Total cost: $${analysis.total_cost}`,\n `- Estimated savings: $${savings.estimated_savings_total} (guarded <= total_cost)`,\n `- Confidence: ${confidence}`,\n unknownCount > 0 ? `- Unknown models: ${unknownCount} (estimated pricing used)` : '- Unknown models: 0',\n ...warningsMd.map(w => `- ${w}`),\n '',\n '## ASSUMPTIONS',\n '- No double-counting: routing → context → retry savings allocated per-event with remaining-cost caps.',\n mode === 'attempt-log'\n ? '- Retry cost model: attempt-log mode (total_cost=sum attempts, retry_waste=sum attempt>=2).'\n : '- Retry cost model: legacy mode (total_cost=base_cost*(1+retries)).',\n '- Context savings: top 20% input_tokens events assume 25% input reduction.',\n '',\n '## WHAT TO CHANGE',\n '1) Retry tuning → edit `aiopt/policies/retry.json`',\n '2) Output cap → edit `aiopt/policies/output.json`',\n '3) Routing rule → edit `aiopt/policies/routing.json`',\n '',\n '## OUTPUTS',\n '- `aiopt-output/analysis.json`',\n '- `aiopt-output/report.json`',\n '- `aiopt-output/patches/*`',\n ''\n ].join('\\n');\n fs.writeFileSync(path.join(outDir, 'report.md'), reportMd);\n\n const reportTxt = [\n `총비용: $${analysis.total_cost}`,\n `절감 가능 금액(Estimated): $${savings.estimated_savings_total}`,\n `절감 근거 3줄:`,\n savings.notes[0],\n savings.notes[1],\n savings.notes[2],\n ''\n ].join('\\n');\n fs.writeFileSync(path.join(outDir, 'report.txt'), reportTxt);\n\n fs.writeFileSync(path.join(outDir, 'cost-policy.json'), JSON.stringify(policy, null, 2));\n\n // patches/*\n const fixes = buildTopFixes(analysis, savings);\n writePatches(outDir, fixes);\n}\n","{\n \"name\": \"aiopt\",\n \"version\": \"0.2.4\",\n \"description\": \"Serverless local CLI MVP for AI API cost analysis & cost-policy generation\",\n \"bin\": {\n \"aiopt\": \"dist/cli.js\"\n },\n \"type\": \"commonjs\",\n \"main\": \"dist/cli.js\",\n \"files\": [\n \"dist\",\n \"rates\",\n \"samples\",\n \"README.md\"\n ],\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"node --enable-source-maps dist/cli.js\",\n \"prepack\": \"npm run build\",\n \"test:npx\": \"npm pack --silent && node -e \\\"const fs=require('fs');const p=fs.readdirSync('.').find(f=>/^aiopt-.*\\\\.tgz$/.test(f)); if(!p) throw new Error('tgz not found'); console.log('tgz',p);\\\" && npx --yes ./$(ls -1 aiopt-*.tgz | tail -n 1) install --force && npx --yes ./$(ls -1 aiopt-*.tgz | tail -n 1) doctor && npx --yes ./$(ls -1 aiopt-*.tgz | tail -n 1) scan && test -f ./aiopt-output/report.md && echo OK\",\n \"test:guard\": \"npm run build --silent && node scripts/test-guard.js\",\n \"test:license\": \"npm run build --silent && node scripts/test-license.js\"\n },\n \"dependencies\": {\n \"commander\": \"^14.0.0\",\n \"csv-parse\": \"^6.1.0\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^24.0.0\",\n \"tsup\": \"^8.5.0\",\n \"typescript\": \"^5.9.2\"\n }\n}\n","import fs from 'fs';\nimport path from 'path';\n\nexport type InstallOptions = {\n force?: boolean;\n seedSample?: boolean;\n};\n\nfunction ensureDir(p: string) {\n fs.mkdirSync(p, { recursive: true });\n}\n\nfunction writeFile(filePath: string, content: string, force?: boolean) {\n if (!force && fs.existsSync(filePath)) return { wrote: false, reason: 'exists' as const };\n ensureDir(path.dirname(filePath));\n fs.writeFileSync(filePath, content);\n return { wrote: true as const };\n}\n\nexport function runInstall(cwd: string, opts: InstallOptions) {\n const force = Boolean(opts.force);\n\n const aioptDir = path.join(cwd, 'aiopt');\n const policiesDir = path.join(aioptDir, 'policies');\n const outDir = path.join(cwd, 'aiopt-output');\n\n ensureDir(aioptDir);\n ensureDir(policiesDir);\n ensureDir(outDir);\n\n const created: Array<{ path: string; status: 'created' | 'skipped' }> = [];\n\n // 1) aiopt/README.md\n const readme = `# AIOpt\n\nAIOpt는 **scan툴이 아니라 설치형 비용 가드레일이다.**\n\n## Quick start\n\\`\\`\\`bash\nnpx aiopt install --force\nnpx aiopt doctor\n# (your app runs, wrapper logs usage)\nnpx aiopt scan\n\\`\\`\\`\n\n- 서버/대시보드/계정/업로드/결제/프록시 없음\n- 로컬 파일 기반(정책 + usage.jsonl)\n- LLM 호출 금지(수학/룰 기반)\n\n## Wrapper usage (Node.js)\n\nAIOpt 설치 후, 앱 코드에서 wrapper를 불러서 사용량 JSONL을 자동 기록할 수 있습니다.\n\n\na) 최소 형태(토큰을 직접 넘김)\n\n\\`\\`\\`js\nconst { guardedCall } = require('./aiopt/aiopt-wrapper.js');\n\nawait guardedCall(process.cwd(), {\n provider: 'openai',\n model: 'gpt-5-mini',\n endpoint: 'responses.create',\n feature_tag: 'summarize',\n prompt_tokens: 1200,\n trace_id: 'my-trace'\n}, async (req) => {\n // req: { provider, model, endpoint, max_output_tokens, prompt_tokens, idempotency_key }\n // 여기서 실제 SDK 호출 후 결과를 반환\n return { status: 'ok', completion_tokens: 200 };\n});\n\\`\\`\\`\n\nb) OpenAI-style 응답(usage 자동 추출)\n\n\\`\\`\\`js\nreturn {\n status: 'ok',\n response: {\n usage: { prompt_tokens: 1200, completion_tokens: 200, total_tokens: 1400 }\n }\n};\n\\`\\`\\`\n`;\n\n const r1 = writeFile(path.join(aioptDir, 'README.md'), readme, force);\n created.push({ path: 'aiopt/README.md', status: r1.wrote ? 'created' : 'skipped' });\n\n // 2) aiopt/aiopt.config.json\n const config = {\n version: 1,\n installed_at: new Date().toISOString(),\n output_dir: './aiopt-output',\n usage_path: './aiopt-output/usage.jsonl',\n policies_dir: './aiopt/policies',\n rate_table: { path: './rates/rate_table.json' }\n };\n const r2 = writeFile(path.join(aioptDir, 'aiopt.config.json'), JSON.stringify(config, null, 2) + '\\n', force);\n created.push({ path: 'aiopt/aiopt.config.json', status: r2.wrote ? 'created' : 'skipped' });\n\n // 3) policies\n const routing = {\n version: 1,\n rules: [\n { match: { feature_tag_in: ['summarize', 'classify', 'translate'] }, action: { tier: 'cheap', reason: 'cheap feature routing' } },\n { match: { feature_tag_in: ['coding', 'reasoning'] }, action: { tier: 'default', reason: 'keep for quality' } }\n ]\n };\n const retry = {\n version: 1,\n max_attempts: 2,\n backoff_ms: [200, 500],\n retry_on_status: ['error', 'timeout'],\n notes: 'MVP deterministic retry tuning'\n };\n const output = {\n version: 1,\n max_output_tokens_default: 1024,\n per_feature: {\n summarize: 512,\n classify: 256,\n translate: 512\n }\n };\n const context = {\n version: 1,\n input_token_soft_cap: 12000,\n reduce_top_percentile: 0.2,\n assumed_reduction_ratio: 0.25\n };\n\n const p1 = writeFile(path.join(policiesDir, 'routing.json'), JSON.stringify(routing, null, 2) + '\\n', force);\n const p2 = writeFile(path.join(policiesDir, 'retry.json'), JSON.stringify(retry, null, 2) + '\\n', force);\n const p3 = writeFile(path.join(policiesDir, 'output.json'), JSON.stringify(output, null, 2) + '\\n', force);\n const p4 = writeFile(path.join(policiesDir, 'context.json'), JSON.stringify(context, null, 2) + '\\n', force);\n\n created.push({ path: 'aiopt/policies/routing.json', status: p1.wrote ? 'created' : 'skipped' });\n created.push({ path: 'aiopt/policies/retry.json', status: p2.wrote ? 'created' : 'skipped' });\n created.push({ path: 'aiopt/policies/output.json', status: p3.wrote ? 'created' : 'skipped' });\n created.push({ path: 'aiopt/policies/context.json', status: p4.wrote ? 'created' : 'skipped' });\n\n // 4) wrapper template (T2: real guardrails wrapper)\n const wrapperPath = path.join(aioptDir, 'aiopt-wrapper.js');\n const wrapper = \n`// AIOpt Wrapper (guardrails) — local-only (CommonJS)\n\nconst fs = require('fs');\n\nconst path = require('path');\n\nconst crypto = require('crypto');\n\nfunction readJson(p){ return JSON.parse(fs.readFileSync(p,'utf8')); }\nfunction ensureDir(p){ fs.mkdirSync(p,{recursive:true}); }\nfunction appendJsonl(filePath,obj){ ensureDir(path.dirname(filePath)); fs.appendFileSync(filePath, JSON.stringify(obj)+'\\\\n'); }\nfunction sleep(ms){ return new Promise(r=>setTimeout(r,ms)); }\n\nfunction loadConfig(cwd){ return readJson(path.join(cwd,'aiopt','aiopt.config.json')); }\nfunction loadPolicies(cwd,cfg){ const dir=path.isAbsolute(cfg.policies_dir)?cfg.policies_dir:path.join(cwd,cfg.policies_dir);\n return {\n retry: readJson(path.join(dir,'retry.json')) ,\n output: readJson(path.join(dir,'output.json'))\n };\n}\nfunction loadRates(cwd,cfg){\n const rp=path.isAbsolute(cfg.rate_table.path)?cfg.rate_table.path:path.join(cwd,cfg.rate_table.path);\n try{ return readJson(rp); }catch(e){\n // Fresh projects may not have a rates/ table yet. Fall back to a safe default.\n return { providers: {} };\n }\n}\n\nfunction costUsd(rt, provider, model, promptTokens, completionTokens){\n const p=rt.providers && rt.providers[provider];\n const r=(p && p.models && p.models[model]) || (p && p.default_estimated) || {input:1.0, output:4.0};\n return (promptTokens/1e6)*r.input + (completionTokens/1e6)*r.output;\n}\n\nfunction pickRoutedModel(rt, provider, featureTag, currentModel){\n const cheap=['summarize','classify','translate'];\n if(!cheap.includes(String(featureTag||'').toLowerCase())) return { model: currentModel, routed_from: null, hit: null };\n const p=rt.providers && rt.providers[provider];\n const entries=p && p.models ? Object.entries(p.models) : [];\n if(!entries.length) return { model: currentModel, routed_from: null, hit: null };\n const cheapest=entries.map(([name,r])=>({name,score:(r.input+r.output)/2})).sort((a,b)=>a.score-b.score)[0];\n if(!cheapest || cheapest.name===currentModel) return { model: currentModel, routed_from: null, hit: null };\n return { model: cheapest.name, routed_from: currentModel, hit: 'routing:cheap-feature' };\n}\n\nfunction outputCap(outputPolicy, featureTag, requested){\n const per=(outputPolicy && outputPolicy.per_feature) || {};\n const cap=per[String(featureTag||'').toLowerCase()] ?? (outputPolicy.max_output_tokens_default || 1024);\n const req=requested ?? cap;\n return Math.min(req, cap);\n}\n\nconst IDEMPOTENCY=new Map();\n\nfunction normalizeResult(out, input){\n // Accept either normalized return or provider raw.\n const o = (out && out.response) ? out.response : out;\n const status = (out && out.status) || o.status || (o.error ? 'error' : 'ok');\n const usage = o.usage || (o.data && o.data.usage) || null;\n\n const prompt_tokens = Number(\n (out && out.prompt_tokens) ??\n (o && o.prompt_tokens) ??\n (usage && usage.prompt_tokens) ??\n input.prompt_tokens ??\n 0\n );\n const completion_tokens = Number(\n (out && out.completion_tokens) ??\n (o && o.completion_tokens) ??\n (usage && usage.completion_tokens) ??\n 0\n );\n const total_tokens = Number(\n (out && out.total_tokens) ??\n (o && o.total_tokens) ??\n (usage && usage.total_tokens) ??\n (prompt_tokens + completion_tokens)\n );\n\n const error_code = status === 'ok' ? null : String((out && out.error_code) || (o && o.error_code) || (o && o.error && (o.error.code || o.error.type)) || status);\n const cost_usd = (out && typeof out.cost_usd === 'number') ? out.cost_usd : null;\n\n return { status, prompt_tokens, completion_tokens, total_tokens, error_code, cost_usd };\n}\n\n/**\n * guardedCall(cwd, input, fn)\n *\n * fn(req) can return either:\n * 1) Normalized shape:\n * { status: 'ok'|'error'|'timeout', prompt_tokens?, completion_tokens?, total_tokens?, cost_usd?, error_code? }\n * 2) Provider raw response (OpenAI-style), e.g.:\n * { status:'ok', response:{ usage:{prompt_tokens, completion_tokens, total_tokens} } }\n * { usage:{prompt_tokens, completion_tokens, total_tokens} }\n *\n * If token fields are missing, AIOpt will fall back to input.prompt_tokens and/or 0.\n */\nasync function guardedCall(cwd, input, fn){\n const cfg=loadConfig(cwd);\n const pol=loadPolicies(cwd,cfg);\n const rt=loadRates(cwd,cfg);\n\n const request_id=crypto.randomUUID();\n const trace_id=input.trace_id || request_id;\n const idem=input.idempotency_key || trace_id;\n if(IDEMPOTENCY.has(idem)) return IDEMPOTENCY.get(idem);\n\n const routed=pickRoutedModel(rt, input.provider, input.feature_tag, input.model);\n const maxOut=outputCap(pol.output, input.feature_tag, input.max_output_tokens);\n const usagePath=path.isAbsolute(cfg.usage_path)?cfg.usage_path:path.join(cwd,cfg.usage_path);\n\n const maxAttempts=Math.max(1, Number(pol.retry.max_attempts||1));\n const backoffs=pol.retry.backoff_ms || [200];\n const retryOn=new Set(pol.retry.retry_on_status || ['error','timeout']);\n\n let last={status:'error', completion_tokens:0, error_code:'unknown'};\n\n for(let attempt=1; attempt<=maxAttempts; attempt++){\n const t0=Date.now();\n const policy_hits=[];\n if(routed.hit) policy_hits.push(routed.hit);\n policy_hits.push('outputcap:'+maxOut);\n try{\n const out=await fn({ provider: input.provider, model: routed.model, endpoint: input.endpoint, max_output_tokens: maxOut, prompt_tokens: input.prompt_tokens, idempotency_key: idem });\n const latency_ms=Date.now()-t0;\n const norm=normalizeResult(out, input);\n const cost_usd=(typeof norm.cost_usd==='number') ? norm.cost_usd : costUsd(rt, input.provider, routed.model, norm.prompt_tokens, norm.completion_tokens);\n const feature_tag = input.feature_tag || input.endpoint || 'unknown';\n appendJsonl(usagePath, { ts:new Date().toISOString(), request_id, trace_id, attempt, status: norm.status, error_code: norm.error_code, provider: input.provider, model: routed.model, endpoint: input.endpoint, prompt_tokens: norm.prompt_tokens, completion_tokens: norm.completion_tokens, total_tokens: norm.total_tokens, cost_usd, latency_ms, meta:{ feature_tag, routed_from: routed.routed_from, policy_hits } });\n last={ status: norm.status, completion_tokens: norm.completion_tokens, error_code: norm.error_code };\n if(norm.status==='ok'){ IDEMPOTENCY.set(idem,out); return out; }\n if(retryOn.has(norm.status) && attempt<maxAttempts){ await sleep(Number(backoffs[Math.min(attempt-1, backoffs.length-1)]||200)); continue; }\n IDEMPOTENCY.set(idem,out); return out;\n }catch(e){\n const latency_ms=Date.now()-t0;\n const out={ status:'error', completion_tokens:0, error_code:String(e && (e.code||e.name) || 'exception') };\n const feature_tag = input.feature_tag || input.endpoint || 'unknown';\n appendJsonl(usagePath, { ts:new Date().toISOString(), request_id, trace_id, attempt, status: out.status, error_code: out.error_code, provider: input.provider, model: routed.model, endpoint: input.endpoint, prompt_tokens:Number(input.prompt_tokens||0), completion_tokens:0, total_tokens:Number(input.prompt_tokens||0), cost_usd:costUsd(rt, input.provider, routed.model, Number(input.prompt_tokens||0), 0), latency_ms, meta:{ feature_tag, routed_from: routed.routed_from, policy_hits:[routed.hit||'routing:none','outputcap:'+maxOut,'error:exception'] } });\n last=out;\n if(attempt<maxAttempts){ await sleep(Number(backoffs[Math.min(attempt-1, backoffs.length-1)]||200)); continue; }\n IDEMPOTENCY.set(idem,out); return out;\n }\n }\n IDEMPOTENCY.set(idem,last);\n return last;\n}\n\nmodule.exports = { guardedCall };\n`;\n;\n const w = writeFile(wrapperPath, wrapper, force);\n created.push({ path: 'aiopt/aiopt-wrapper.js', status: w.wrote ? 'created' : 'skipped' });\n\n // 5) usage.jsonl\n const usagePath = path.join(outDir, 'usage.jsonl');\n if (force || !fs.existsSync(usagePath)) {\n // default: empty file (avoid mixing demo data into real user logs)\n fs.writeFileSync(usagePath, '');\n created.push({ path: 'aiopt-output/usage.jsonl', status: 'created' });\n\n if (opts.seedSample) {\n const sample = {\n ts: new Date().toISOString(),\n request_id: 'sample',\n trace_id: 'sample',\n attempt: 1,\n status: 'ok',\n error_code: null,\n provider: 'openai',\n model: 'gpt-5-mini',\n endpoint: 'demo',\n prompt_tokens: 12,\n completion_tokens: 3,\n total_tokens: 15,\n cost_usd: 0.0,\n latency_ms: 1,\n meta: { feature_tag: 'demo', routed_from: null, policy_hits: ['install-sample'] }\n };\n fs.appendFileSync(usagePath, JSON.stringify(sample) + '\\n');\n }\n } else {\n created.push({ path: 'aiopt-output/usage.jsonl', status: 'skipped' });\n }\n\n return { created };\n}\n","import fs from 'fs';\nimport path from 'path';\n\nfunction canWrite(dir: string) {\n try {\n fs.mkdirSync(dir, { recursive: true });\n const p = path.join(dir, `.aiopt-write-test-${Date.now()}`);\n fs.writeFileSync(p, 'ok');\n fs.unlinkSync(p);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction tailLines(filePath: string, n: number): string[] {\n try {\n const raw = fs.readFileSync(filePath, 'utf8');\n const lines = raw.split(/\\r?\\n/).filter(l => l.trim().length > 0);\n return lines.slice(Math.max(0, lines.length - n));\n } catch {\n return [];\n }\n}\n\nexport type DoctorResult = {\n ok: boolean;\n checks: Array<{ name: string; ok: boolean; detail?: string }>;\n last5: Array<{ status?: string; provider?: string; model?: string; endpoint?: string; attempt?: number }>;\n};\n\nexport function runDoctor(cwd: string): DoctorResult {\n const aioptDir = path.join(cwd, 'aiopt');\n const policiesDir = path.join(aioptDir, 'policies');\n const outDir = path.join(cwd, 'aiopt-output');\n const usagePath = path.join(outDir, 'usage.jsonl');\n\n const checks: DoctorResult['checks'] = [];\n\n checks.push({ name: 'aiopt/ exists', ok: fs.existsSync(aioptDir) });\n checks.push({ name: 'aiopt/policies exists', ok: fs.existsSync(policiesDir) });\n checks.push({ name: 'aiopt-output/ writable', ok: canWrite(outDir) });\n checks.push({ name: 'usage.jsonl exists', ok: fs.existsSync(usagePath), detail: usagePath });\n\n const last5raw = tailLines(usagePath, 5);\n const last5 = last5raw.length === 0 ? [{ status: '(empty usage.jsonl)' }] as any : last5raw.map(l => {\n try {\n const j = JSON.parse(l);\n return {\n status: j.status,\n provider: j.provider,\n model: j.model,\n endpoint: j.endpoint,\n attempt: j.attempt,\n feature_tag: j?.meta?.feature_tag\n };\n } catch {\n return {};\n }\n });\n\n // Feature-tag quality check (sample last 50 lines)\n const last50 = tailLines(usagePath, 50);\n let missing = 0;\n let total50 = 0;\n for (const l of last50) {\n total50++;\n try {\n const j = JSON.parse(l);\n const ft = j?.meta?.feature_tag;\n if (!ft || String(ft).trim() === '') missing++;\n } catch {\n missing++;\n }\n }\n if (total50 > 0 && missing > 0) {\n checks.push({ name: 'feature_tag quality (last50)', ok: false, detail: `${missing}/${total50} missing meta.feature_tag` });\n } else {\n checks.push({ name: 'feature_tag quality (last50)', ok: true, detail: 'meta.feature_tag present' });\n }\n\n const ok = checks.every(c => c.ok);\n return { ok, checks, last5 };\n}\n\n","import crypto from 'crypto';\nimport fs from 'fs';\nimport path from 'path';\n\nexport type LicensePayload = {\n sub: string; // customer id/email/etc\n plan: 'pro' | 'team' | 'trial' | string;\n iat: number; // issued at (unix seconds)\n exp: number; // expires at (unix seconds)\n features?: Record<string, boolean>;\n};\n\nexport type LicenseFile = {\n key: string;\n payload: LicensePayload;\n verified: boolean;\n verified_at: string;\n};\n\n// NOTE: Public key only. No servers.\n// Replace this with your own RSA public key in PEM (SPKI) format.\nexport const DEFAULT_PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz1LLE/pXIx5TloDa0LAf\njg9NSIW6STWhsAFP2ZzXgpWoQ3cCmW6xcB/4QNEmPpGlfMWhyRfkxsdKuhnjUMTg\n8MpMAcbjjF8JrGS9iLnW4yrLm7jzsOcndjkGO7pH+32GopZk98dVzmIRPok2Je76\n3MQRaxLi0jWytaCmacEB4R7HyuquOQlHPg0vD9NOEwrC/+br2GdQbD1lKPyLeLv3\nRidwAs8Iw2xx5g8G+BsVSM/HRC3jQT5GynfnuDsvMHCvGLRct/76ajiR71/NFZEP\nZ7liILNnZzCTlKGGZfZmG70t+zkg8HKdpRuWy8rZ0DPWyQg5MKm6TZOMV6dC0Rpg\nDwIDAQAB\n-----END PUBLIC KEY-----`;\n\nfunction b64urlDecodeToBuffer(s: string): Buffer {\n const padLen = (4 - (s.length % 4)) % 4;\n const padded = s.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat(padLen);\n return Buffer.from(padded, 'base64');\n}\n\nfunction safeJsonParse(buf: Buffer): any {\n const txt = buf.toString('utf8');\n return JSON.parse(txt);\n}\n\nexport function parseLicenseKey(key: string): { payload: LicensePayload; signature: Buffer; payloadB64Url: string } {\n const parts = String(key).trim().split('.');\n if (parts.length !== 2) throw new Error('invalid license key format: expected <payloadB64Url>.<sigB64Url>');\n const [payloadB64Url, sigB64Url] = parts;\n const payloadBuf = b64urlDecodeToBuffer(payloadB64Url);\n const sigBuf = b64urlDecodeToBuffer(sigB64Url);\n const payload = safeJsonParse(payloadBuf) as LicensePayload;\n return { payload, signature: sigBuf, payloadB64Url };\n}\n\nexport function verifyLicenseKey(key: string, publicKeyPem: string): { ok: boolean; reason?: string; payload?: LicensePayload } {\n let parsed: { payload: LicensePayload; signature: Buffer; payloadB64Url: string };\n try {\n parsed = parseLicenseKey(key);\n } catch (e: any) {\n return { ok: false, reason: e?.message || 'parse error' };\n }\n\n const now = Math.floor(Date.now() / 1000);\n if (typeof parsed.payload?.exp !== 'number' || parsed.payload.exp < now) {\n return { ok: false, reason: 'expired', payload: parsed.payload };\n }\n\n try {\n const verifier = crypto.createVerify('RSA-SHA256');\n verifier.update(parsed.payloadB64Url);\n verifier.end();\n const ok = verifier.verify(publicKeyPem, parsed.signature);\n if (!ok) return { ok: false, reason: 'bad signature', payload: parsed.payload };\n return { ok: true, payload: parsed.payload };\n } catch (e: any) {\n return { ok: false, reason: e?.message || 'verify error', payload: parsed.payload };\n }\n}\n\nexport function defaultLicensePath(cwd: string): string {\n return path.join(cwd, 'aiopt', 'license.json');\n}\n\nexport function writeLicenseFile(p: string, key: string, payload: LicensePayload, verified: boolean) {\n const out: LicenseFile = {\n key,\n payload,\n verified,\n verified_at: new Date().toISOString()\n };\n fs.mkdirSync(path.dirname(p), { recursive: true });\n fs.writeFileSync(p, JSON.stringify(out, null, 2));\n}\n\nexport function readLicenseFile(p: string): LicenseFile {\n return JSON.parse(fs.readFileSync(p, 'utf8')) as LicenseFile;\n}\n","import { RateTable, UsageEvent } from './types';\nimport { analyze } from './scan';\nimport { costOfEvent } from './cost';\n\nexport type GuardInput = {\n baselineEvents: UsageEvent[];\n candidate: {\n provider?: string;\n model?: string;\n contextMultiplier?: number; // multiplies input_tokens\n outputMultiplier?: number; // multiplies output_tokens\n retriesDelta?: number; // adds to retries\n callMultiplier?: number; // multiplies call volume\n };\n};\n\nexport type GuardResult = {\n exitCode: 0 | 2 | 3;\n message: string;\n};\n\nfunction accidentRiskFromMonthly(monthly: number): 'Low' | 'Medium' | 'High' {\n if (!Number.isFinite(monthly)) return 'Medium';\n if (monthly >= 100) return 'High';\n if (monthly >= 10) return 'Medium';\n return 'Low';\n}\n\nfunction round2(n: number) {\n return Math.round(n * 100) / 100;\n}\n\nfunction monthEstimate(delta: number, events: UsageEvent[]) {\n // Convert observed delta (over the sample window) into a monthly estimate.\n // Prefer timestamp-derived window length for determinism; fall back to 1 day.\n let days = 1;\n try {\n const times = events\n .map(e => Date.parse(e.ts))\n .filter(t => Number.isFinite(t))\n .sort((a, b) => a - b);\n if (times.length >= 2) {\n const spanMs = Math.max(0, times[times.length - 1] - times[0]);\n const spanDays = spanMs / (1000 * 60 * 60 * 24);\n // If logs cover <1 day (or identical timestamps), treat as 1 day.\n days = Math.max(1, spanDays);\n }\n } catch {\n days = 1;\n }\n return (delta * 30) / days;\n}\n\nfunction applyCandidate(events: UsageEvent[], cand: GuardInput['candidate']): UsageEvent[] {\n const ctxM = cand.contextMultiplier ?? 1;\n const outM = cand.outputMultiplier ?? 1;\n const rDelta = cand.retriesDelta ?? 0;\n\n return events.map(ev => ({\n ...ev,\n provider: cand.provider ? String(cand.provider).toLowerCase() : ev.provider,\n model: cand.model ? String(cand.model) : ev.model,\n input_tokens: Math.max(0, Math.round((ev.input_tokens || 0) * ctxM)),\n output_tokens: Math.max(0, Math.round((ev.output_tokens || 0) * outM)),\n retries: Math.max(0, Math.round((ev.retries || 0) + rDelta)),\n // clear billed_cost so pricing recalculates for new model/provider\n billed_cost: undefined\n }));\n}\n\nfunction confidenceFromChange(cand: GuardInput['candidate']): { level: 'High'|'Medium'|'Low'; reasons: string[] } {\n const reasons: string[] = [];\n\n if (cand.retriesDelta && cand.retriesDelta !== 0) reasons.push('retries change');\n if (cand.model) reasons.push('model change');\n if (cand.provider) reasons.push('provider change');\n if (cand.contextMultiplier && cand.contextMultiplier !== 1) reasons.push('context length change');\n if (cand.outputMultiplier && cand.outputMultiplier !== 1) reasons.push('output length change');\n\n // Spec rule:\n // High: retries/failed/dup calls (we only model retries here)\n // Medium: model/provider change\n // Low: context trimming / prompt structure\n if (cand.retriesDelta && cand.retriesDelta !== 0) return { level: 'High', reasons };\n if (cand.model || cand.provider) return { level: 'Medium', reasons };\n if ((cand.contextMultiplier && cand.contextMultiplier !== 1) || (cand.outputMultiplier && cand.outputMultiplier !== 1)) {\n return { level: 'Low', reasons };\n }\n return { level: 'Medium', reasons: reasons.length ? reasons : ['unknown change'] };\n}\n\nfunction assessDataQuality(baselineEvents: UsageEvent[], base: ReturnType<typeof analyze>) {\n const reasons: string[] = [];\n\n // ts span\n const times = baselineEvents\n .map(e => Date.parse(e.ts))\n .filter(t => Number.isFinite(t))\n .sort((a, b) => a - b);\n if (times.length < 2) reasons.push('ts span unknown');\n else {\n const spanDays = Math.max(0, (times[times.length - 1] - times[0]) / (1000 * 60 * 60 * 24));\n if (spanDays < 0.25) reasons.push('ts span too short');\n }\n\n // feature tag coverage\n const missingFt = baselineEvents.filter(e => !e.feature_tag && !(e.meta && (e.meta as any).feature_tag)).length;\n if (missingFt / Math.max(1, baselineEvents.length) > 0.2) reasons.push('feature_tag missing >20%');\n\n // unknown model/provider\n const unknown = (base.analysis.unknown_models || []).length;\n if (unknown / Math.max(1, baselineEvents.length) > 0.2) reasons.push('unknown model/provider >20%');\n\n // Map to a confidence penalty.\n let penalty: 'none'|'low'|'medium' = 'none';\n if (reasons.length >= 2) penalty = 'medium';\n else if (reasons.length === 1) penalty = 'low';\n\n return { reasons, penalty };\n}\n\nfunction degrade(level: 'High'|'Medium'|'Low', penalty: 'none'|'low'|'medium'): 'High'|'Medium'|'Low' {\n if (penalty === 'none') return level;\n if (penalty === 'low') return level === 'High' ? 'Medium' : 'Low';\n // medium\n return 'Low';\n}\n\nexport function runGuard(rt: RateTable, input: GuardInput): GuardResult {\n if (!input.baselineEvents || input.baselineEvents.length === 0) {\n const conf = { level: 'Low' as const, reasons: ['baseline empty'] };\n const msg = [\n 'FAIL: baseline usage is empty (need aiopt-output/usage.jsonl)',\n 'Impact (monthly est): +$0 (insufficient baseline)',\n `Accident risk: ${accidentRiskFromMonthly(100)}`,\n `Confidence: ${conf.level} (${(conf.reasons.length ? conf.reasons.join(', ') : 'baseline empty')})`,\n 'Recommendation: run the wrapper to collect baseline usage before using guard.'\n ].join('\\n');\n return { exitCode: 3, message: msg };\n }\n\n // For fair comparison, ignore billed_cost/cost_usd and recompute both sides from rate table.\n const baselineEvents = input.baselineEvents.map(e => ({ ...e, billed_cost: undefined }));\n const base = analyze(rt, baselineEvents);\n const candidateEvents = applyCandidate(baselineEvents, input.candidate);\n const cand = analyze(rt, candidateEvents);\n\n const baseCost = base.analysis.total_cost;\n let candCost = cand.analysis.total_cost;\n\n // call volume multiplier (traffic spike)\n const callMult = input.candidate.callMultiplier && input.candidate.callMultiplier > 0 ? input.candidate.callMultiplier : 1;\n if (callMult !== 1) {\n candCost = candCost * callMult;\n }\n\n // attempt-log baseline: retriesDelta should be interpreted as \"extra attempts\".\n const attemptLog = baselineEvents.some(e => (e.trace_id && String(e.trace_id).length > 0) || (e.attempt !== undefined && Number(e.attempt) > 0));\n if (attemptLog && input.candidate.retriesDelta && input.candidate.retriesDelta > 0) {\n // More accurate deterministic approximation:\n // - If baseline already has retry attempts (attempt>=2), use their average cost as retry unit.\n // - Else fall back to avg baseline attempt cost.\n let retryUnit = 0;\n let retryCount = 0;\n for (const ev of baselineEvents) {\n const attempt = Number(ev.attempt || 1);\n if (attempt >= 2) {\n retryUnit += costOfEvent(rt, ev).cost;\n retryCount += 1;\n }\n }\n if (retryCount > 0) {\n retryUnit = retryUnit / retryCount;\n } else {\n retryUnit = baseCost / Math.max(1, baselineEvents.length);\n }\n candCost += retryUnit * input.candidate.retriesDelta;\n }\n\n const delta = candCost - baseCost;\n\n const changeConf = confidenceFromChange(input.candidate);\n const dq = assessDataQuality(baselineEvents, base);\n const conf = { level: degrade(changeConf.level, dq.penalty), reasons: [...changeConf.reasons, ...dq.reasons.map(r => `data: ${r}`)] };\n\n // Guard logic:\n // - Warning if delta > 0 and monthEstimate(delta) >= $10\n // - Fail if delta > 0 and monthEstimate(delta) >= $100 (merge-blocking)\n const monthly = monthEstimate(Math.max(0, delta), baselineEvents);\n const monthlyRounded = round2(monthly);\n\n let exitCode: 0 | 2 | 3 = 0;\n let headline = 'OK: no cost accident risk detected';\n\n if (monthly >= 100) { exitCode = 3; headline = 'FAIL: high risk of LLM cost accident'; }\n else if (monthly >= 10) { exitCode = 2; headline = 'WARN: possible LLM cost accident'; }\n\n const reasons = conf.reasons.length ? conf.reasons.join(', ') : 'n/a';\n\n const msg = [\n headline,\n `Summary: baseline=$${round2(baseCost)} → candidate=$${round2(candCost)} (Δ=$${round2(delta)})`,\n callMult !== 1 ? `Call volume multiplier: x${callMult}` : null,\n `Impact (monthly est): +$${monthlyRounded}`,\n `Accident risk: ${accidentRiskFromMonthly(monthly)}`,\n `Confidence: ${conf.level} (${reasons})`,\n 'Recommendation: review model/provider/retry/context changes before deploy.'\n ].filter(Boolean).join('\\n');\n\n return { exitCode, message: msg };\n}\n","import http from 'http';\nimport fs from 'fs';\nimport path from 'path';\n\nexport async function startDashboard(cwd: string, opts: { port: number }) {\n const host = '127.0.0.1';\n const port = opts.port || 3010;\n\n const outDir = path.join(cwd, 'aiopt-output');\n const file = (name: string) => path.join(outDir, name);\n\n function readOrNull(p: string) {\n try {\n if (!fs.existsSync(p)) return null;\n return fs.readFileSync(p, 'utf8');\n } catch {\n return null;\n }\n }\n\n const indexHtml = `<!doctype html>\n<html>\n<head>\n <meta charset=\"utf-8\"/>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"/>\n <title>AIOpt Local Dashboard</title>\n <style>\n body{font-family:ui-sans-serif,system-ui,Arial; margin:16px; max-width:980px}\n .row{display:flex; gap:12px; flex-wrap:wrap}\n .card{border:1px solid #ddd; border-radius:10px; padding:12px; flex:1; min-width:320px}\n pre{white-space:pre-wrap; word-break:break-word; background:#0b1020; color:#e6e6e6; padding:12px; border-radius:10px; overflow:auto}\n a{color:#2d6cdf}\n </style>\n</head>\n<body>\n <h1>AIOpt Local Dashboard</h1>\n <p>Local-only (bind: 127.0.0.1). Reads files from <code>./aiopt-output/</code>.</p>\n\n <div class=\"row\">\n <div class=\"card\">\n <h2>Last Guard</h2>\n <div id=\"guardMeta\"></div>\n <pre id=\"guard\">loading...</pre>\n <p><a href=\"/api/guard-last.txt\" target=\"_blank\">raw</a></p>\n </div>\n <div class=\"card\">\n <h2>Last Scan</h2>\n <pre id=\"scan\">loading...</pre>\n <p>\n <a href=\"/api/report.md\" target=\"_blank\">report.md</a> ·\n <a href=\"/api/report.json\" target=\"_blank\">report.json</a>\n </p>\n </div>\n </div>\n\n<script>\nasync function load() {\n const guardTxt = await fetch('/api/guard-last.txt').then(r=>r.ok?r.text():null);\n const guardMeta = await fetch('/api/guard-last.json').then(r=>r.ok?r.json():null);\n document.getElementById('guard').textContent = guardTxt || '(no guard-last.txt yet)';\n document.getElementById('guardMeta').textContent = guardMeta ? ('exit=' + guardMeta.exitCode + ' @ ' + guardMeta.ts) : '';\n\n const reportMd = await fetch('/api/report.md').then(r=>r.ok?r.text():null);\n document.getElementById('scan').textContent = reportMd || '(no report.md yet — run: aiopt scan)';\n}\nload();\n</script>\n</body>\n</html>`;\n\n const server = http.createServer((req, res) => {\n const url = req.url || '/';\n if (url === '/' || url === '/index.html') {\n res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });\n res.end(indexHtml);\n return;\n }\n\n if (url.startsWith('/api/')) {\n const name = url.replace('/api/', '');\n const allow = new Set(['guard-last.txt', 'guard-last.json', 'report.md', 'report.json']);\n if (!allow.has(name)) {\n res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });\n res.end('not found');\n return;\n }\n\n const p = file(name);\n const txt = readOrNull(p);\n if (txt === null) {\n res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });\n res.end('missing');\n return;\n }\n\n const ct = name.endsWith('.json') ? 'application/json; charset=utf-8' : 'text/plain; charset=utf-8';\n res.writeHead(200, { 'content-type': ct });\n res.end(txt);\n return;\n }\n\n res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });\n res.end('not found');\n });\n\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject);\n server.listen(port, host, () => resolve());\n });\n\n console.log(`OK: dashboard http://${host}:${port}/`);\n console.log('Tip: run `aiopt guard ...` and `aiopt scan` to populate aiopt-output files.');\n\n // keep alive\n await new Promise(() => {});\n}\n","#!/usr/bin/env node\n\nimport fs from 'fs';\nimport path from 'path';\nimport { Command } from 'commander';\nimport { ensureDir, isCsvPath, readCsv, readJsonl } from './io';\nimport { RateTable } from './types';\nimport { analyze, writeOutputs } from './scan';\n\nconst program = new Command();\n\nconst DEFAULT_INPUT = './aiopt-output/usage.jsonl';\nconst DEFAULT_OUTPUT_DIR = './aiopt-output';\n\nfunction loadRateTable(): RateTable {\n const p = path.join(__dirname, '..', 'rates', 'rate_table.json');\n return JSON.parse(fs.readFileSync(p, 'utf8'));\n}\n\nprogram\n .name('aiopt')\n .description('AI 비용 자동 절감 인프라 — 서버 없는 로컬 CLI MVP')\n // keep CLI version in sync with package.json\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n .version(require('../package.json').version);\n\nprogram\n .command('init')\n .description('aiopt-input/ 및 샘플 usage.jsonl, aiopt-output/ 생성')\n .action(() => {\n ensureDir('./aiopt-input');\n ensureDir('./aiopt-output');\n\n const sampleSrc = path.join(__dirname, '..', 'samples', 'sample_usage.jsonl');\n const dst = path.join('./aiopt-input', 'usage.jsonl');\n\n if (!fs.existsSync(dst)) {\n fs.copyFileSync(sampleSrc, dst);\n console.log('Created ./aiopt-input/usage.jsonl (sample)');\n } else {\n console.log('Exists ./aiopt-input/usage.jsonl (skip)');\n }\n\n console.log('Ready: ./aiopt-output/');\n });\n\nprogram\n .command('scan')\n .description('입력 로그(JSONL/CSV)를 분석하고 report.md/report.json + patches까지 생성')\n .option('--input <path>', 'input file path (default: ./aiopt-output/usage.jsonl)', DEFAULT_INPUT)\n .option('--out <dir>', 'output dir (default: ./aiopt-output)', DEFAULT_OUTPUT_DIR)\n .action(async (opts) => {\n const inputPath = String(opts.input);\n const outDir = String(opts.out);\n\n if (!fs.existsSync(inputPath)) {\n console.error(`Input not found: ${inputPath}`);\n process.exit(1);\n }\n\n const rt = loadRateTable();\n const events = isCsvPath(inputPath) ? readCsv(inputPath) : readJsonl(inputPath);\n\n const { analysis, savings, policy, meta } = analyze(rt, events);\n // For reproducibility: embed input path & rate table meta\n policy.generated_from.input = inputPath;\n\n writeOutputs(outDir, analysis, savings, policy, meta);\n\n // Console: Top Fix 3 (data-driven)\n const { buildTopFixes } = await import('./solutions');\n const fixes = buildTopFixes(analysis, savings).slice(0, 3);\n\n console.log('Top Fix 3:');\n fixes.forEach((f, i) => {\n const tag = f.status === 'no-issue' ? '(no issue detected)' : `($${Math.round(f.impact_usd * 100) / 100})`;\n console.log(`${i + 1}) ${f.title} ${tag}`);\n });\n console.log(`Report: ${path.join(outDir, 'report.md')}`);\n });\n\nprogram\n .command('policy')\n .description('마지막 scan 결과 기반으로 cost-policy.json만 재생성 (MVP: scan과 동일 로직)')\n .option('--input <path>', 'input file path (default: ./aiopt-input/usage.jsonl)', DEFAULT_INPUT)\n .option('--out <dir>', 'output dir (default: ./aiopt-output)', DEFAULT_OUTPUT_DIR)\n .action((opts) => {\n const inputPath = String(opts.input);\n const outDir = String(opts.out);\n const rt = loadRateTable();\n const events = isCsvPath(inputPath) ? readCsv(inputPath) : readJsonl(inputPath);\n const { policy } = analyze(rt, events);\n policy.generated_from.input = inputPath;\n\n ensureDir(outDir);\n fs.writeFileSync(path.join(outDir, 'cost-policy.json'), JSON.stringify(policy, null, 2));\n console.log(`OK: ${outDir}/cost-policy.json`);\n });\n\n// v0.2: install/doctor (no servers)\nprogram\n .command('install')\n .description('Install AIOpt guardrails: create aiopt/ + policies + usage.jsonl')\n .option('--force', 'overwrite existing files')\n .option('--seed-sample', 'seed 1 sample line into aiopt-output/usage.jsonl')\n .action(async (opts) => {\n const { runInstall } = await import('./install');\n const result = runInstall(process.cwd(), { force: Boolean(opts.force), seedSample: Boolean(opts.seedSample) });\n for (const c of result.created) {\n console.log(`${c.status === 'created' ? 'CREATED' : 'SKIP'}: ${c.path}`);\n }\n });\n\nprogram\n .command('doctor')\n .description('Check installation + print last 5 usage events')\n .action(async () => {\n const { runDoctor } = await import('./doctor');\n const r = runDoctor(process.cwd());\n console.log(r.ok ? 'OK: doctor' : 'WARN: doctor');\n for (const c of r.checks) {\n console.log(`${c.ok ? 'OK' : 'FAIL'}: ${c.name}${c.detail ? ` (${c.detail})` : ''}`);\n }\n console.log('--- last5 usage');\n for (const x of r.last5) {\n console.log(JSON.stringify(x));\n }\n });\n\n// Offline license (no servers)\nconst licenseCmd = program\n .command('license')\n .description('Offline license activate/verify (public key only; no server calls)');\n\nlicenseCmd\n .command('activate')\n .argument('<KEY>', 'license key (<payloadB64Url>.<sigB64Url>)')\n .option('--out <path>', 'output license.json path (default: ./aiopt/license.json)')\n .action(async (key, opts) => {\n const { DEFAULT_PUBLIC_KEY_PEM, defaultLicensePath, verifyLicenseKey, writeLicenseFile } = await import('./license');\n const outPath = opts.out ? String(opts.out) : defaultLicensePath(process.cwd());\n const pub = process.env.AIOPT_LICENSE_PUBKEY || DEFAULT_PUBLIC_KEY_PEM;\n const v = verifyLicenseKey(String(key), pub);\n if (!v.payload) {\n console.error(`FAIL: ${v.reason || 'invalid license'}`);\n process.exit(3);\n }\n writeLicenseFile(outPath, String(key), v.payload, v.ok);\n console.log(v.ok ? `OK: activated (${outPath})` : `WARN: saved but not verified (${v.reason}) (${outPath})`);\n process.exit(v.ok ? 0 : 2);\n });\n\nlicenseCmd\n .command('verify')\n .option('--path <path>', 'license.json path (default: ./aiopt/license.json)')\n .action(async (opts) => {\n const { DEFAULT_PUBLIC_KEY_PEM, defaultLicensePath, readLicenseFile, verifyLicenseKey } = await import('./license');\n const p = opts.path ? String(opts.path) : defaultLicensePath(process.cwd());\n const pub = process.env.AIOPT_LICENSE_PUBKEY || DEFAULT_PUBLIC_KEY_PEM;\n if (!fs.existsSync(p)) {\n console.error(`FAIL: license file not found: ${p}`);\n process.exit(3);\n }\n const f = readLicenseFile(p);\n const v = verifyLicenseKey(f.key, pub);\n if (v.ok) {\n console.log('OK: license verified');\n process.exit(0);\n }\n console.error(`FAIL: license invalid (${v.reason || 'unknown'})`);\n process.exit(3);\n });\n\nlicenseCmd\n .command('status')\n .option('--path <path>', 'license.json path (default: ./aiopt/license.json)')\n .action(async (opts) => {\n const { DEFAULT_PUBLIC_KEY_PEM, defaultLicensePath, readLicenseFile, verifyLicenseKey } = await import('./license');\n const p = opts.path ? String(opts.path) : defaultLicensePath(process.cwd());\n const pub = process.env.AIOPT_LICENSE_PUBKEY || DEFAULT_PUBLIC_KEY_PEM;\n if (!fs.existsSync(p)) {\n console.log('NO_LICENSE');\n process.exit(2);\n }\n const f = readLicenseFile(p);\n const v = verifyLicenseKey(f.key, pub);\n if (v.ok) {\n console.log(`OK: ${f.payload.plan} exp=${f.payload.exp}`);\n process.exit(0);\n }\n console.log(`INVALID: ${v.reason || 'unknown'}`);\n process.exit(3);\n });\n\n// vNext: guardrail mode (pre-deploy warning)\nprogram\n .command('guard')\n .description('Pre-deploy guardrail: compare baseline usage vs candidate change and print warnings (exit codes 0/2/3)')\n .option('--input <path>', 'baseline usage jsonl/csv (default: ./aiopt-output/usage.jsonl)', DEFAULT_INPUT)\n .option('--provider <provider>', 'candidate provider override')\n .option('--model <model>', 'candidate model override')\n .option('--context-mult <n>', 'multiply input_tokens by n', (v) => Number(v))\n .option('--output-mult <n>', 'multiply output_tokens by n', (v) => Number(v))\n .option('--retries-delta <n>', 'add n to retries', (v) => Number(v))\n .option('--call-mult <n>', 'multiply call volume by n (traffic spike)', (v) => Number(v))\n .action(async (opts) => {\n const rt = loadRateTable();\n const inputPath = String(opts.input);\n if (!fs.existsSync(inputPath)) {\n console.error(`FAIL: baseline not found: ${inputPath}`);\n process.exit(3);\n }\n const events = isCsvPath(inputPath) ? readCsv(inputPath) : readJsonl(inputPath);\n\n const { runGuard } = await import('./guard');\n const r = runGuard(rt, {\n baselineEvents: events,\n candidate: {\n provider: opts.provider,\n model: opts.model,\n contextMultiplier: opts.contextMult,\n outputMultiplier: opts.outputMult,\n retriesDelta: opts.retriesDelta,\n callMultiplier: opts.callMult\n }\n });\n\n console.log(r.message);\n\n // Persist last guard output for local dashboard / CI attachments\n try {\n const outDir = path.resolve(DEFAULT_OUTPUT_DIR);\n fs.mkdirSync(outDir, { recursive: true });\n fs.writeFileSync(path.join(outDir, 'guard-last.txt'), r.message);\n fs.writeFileSync(path.join(outDir, 'guard-last.json'), JSON.stringify({ ts: new Date().toISOString(), exitCode: r.exitCode }, null, 2));\n } catch {\n // ignore\n }\n\n process.exit(r.exitCode);\n });\n\n// Local-only dashboard (no auth; binds to 127.0.0.1)\nprogram\n .command('dashboard')\n .description('Local dashboard (localhost only): view last guard + last scan outputs')\n .option('--port <n>', 'port (default: 3010)', (v) => Number(v), 3010)\n .action(async (opts) => {\n const { startDashboard } = await import('./dashboard');\n await startDashboard(process.cwd(), { port: Number(opts.port || 3010) });\n });\n\nprogram.parse(process.argv);\n","import fs from 'fs';\nimport path from 'path';\nimport { parse as parseCsv } from 'csv-parse/sync';\nimport { UsageEvent } from './types';\n\nexport function ensureDir(p: string) {\n fs.mkdirSync(p, { recursive: true });\n}\n\nexport function readJsonl(filePath: string): UsageEvent[] {\n const raw = fs.readFileSync(filePath, 'utf8');\n const lines = raw.split(/\\r?\\n/).filter(l => l.trim().length > 0);\n const out: UsageEvent[] = [];\n for (const line of lines) {\n const obj = JSON.parse(line);\n out.push(normalizeEvent(obj));\n }\n return out;\n}\n\nexport function readCsv(filePath: string): UsageEvent[] {\n const raw = fs.readFileSync(filePath, 'utf8');\n const records = parseCsv(raw, { columns: true, skip_empty_lines: true, trim: true });\n return records.map((r: any) => normalizeEvent(r));\n}\n\nfunction toNum(x: any, def = 0): number {\n const n = Number(x);\n return Number.isFinite(n) ? n : def;\n}\n\nfunction normalizeEvent(x: any): UsageEvent {\n // Supports two schemas:\n // 1) scan input schema: input_tokens/output_tokens/feature_tag/retries\n // 2) wrapper usage schema: prompt_tokens/completion_tokens/endpoint/attempt/trace_id/cost_usd\n\n const inputTokens = x.input_tokens ?? x.prompt_tokens;\n const outputTokens = x.output_tokens ?? x.completion_tokens;\n\n // feature_tag fallback: feature_tag -> meta.feature_tag -> endpoint\n const featureTag = x.feature_tag ?? x?.meta?.feature_tag ?? x.endpoint ?? '';\n\n // retries fallback: retries -> max(attempt-1,0)\n const retries = x.retries ?? (x.attempt !== undefined ? Math.max(0, toNum(x.attempt) - 1) : 0);\n\n // billed_cost fallback: billed_cost -> cost_usd\n const billed = x.billed_cost ?? x.cost_usd;\n\n return {\n ts: String(x.ts ?? ''),\n provider: String(x.provider ?? '').toLowerCase(),\n model: String(x.model ?? ''),\n input_tokens: toNum(inputTokens),\n output_tokens: toNum(outputTokens),\n feature_tag: String(featureTag ?? ''),\n retries: toNum(retries),\n status: String(x.status ?? ''),\n billed_cost: billed === undefined || billed === '' ? undefined : toNum(billed),\n\n trace_id: x.trace_id ? String(x.trace_id) : undefined,\n request_id: x.request_id ? String(x.request_id) : undefined,\n attempt: x.attempt === undefined ? undefined : toNum(x.attempt),\n endpoint: x.endpoint ? String(x.endpoint) : undefined\n };\n}\n\nexport function isCsvPath(p: string) {\n return path.extname(p).toLowerCase() === '.csv';\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaO,SAAS,SAAS,IAAe,UAAkB,OAAe;AACvE,QAAM,OAAO,OAAO,YAAY,EAAE,EAAE,YAAY;AAGhD,MAAI,SAAS,WAAW,SAAS,YAAY,SAAS,QAAQ;AAC5D,WAAO,EAAE,MAAM,YAAqB,OAAO,GAAG,QAAQ,EAAE;AAAA,EAC1D;AAEA,QAAM,IAAI,GAAG,UAAU,IAAI;AAC3B,MAAI,CAAC,EAAG,QAAO;AACf,QAAM,IAAI,EAAE,OAAO,KAAK;AACxB,MAAI,EAAG,QAAO,EAAE,MAAM,YAAqB,OAAO,EAAE,OAAO,QAAQ,EAAE,OAAO;AAC5E,SAAO,EAAE,MAAM,aAAsB,OAAO,EAAE,kBAAkB,OAAO,QAAQ,EAAE,kBAAkB,OAAO;AAC5G;AAEO,SAAS,YAAY,IAAe,IAA4B;AACrE,MAAI,OAAO,GAAG,gBAAgB,YAAY,OAAO,SAAS,GAAG,WAAW,GAAG;AACzE,WAAO;AAAA,MACL,MAAM,GAAG;AAAA,MACT,WAAW;AAAA,QACT,MAAM;AAAA,QACN,UAAU,GAAG;AAAA,QACb,OAAO,GAAG;AAAA,QACV,aAAa;AAAA,QACb,cAAc;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AAEA,QAAM,IAAI,SAAS,IAAI,GAAG,UAAU,GAAG,KAAK;AAC5C,MAAI,CAAC,GAAG;AAEN,UAAM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O,CAAC,GAAG,IAAI,EACnE,OAAO,OAAO,SAAS;AACtB,QAAM,EAAE,gBAAAW,gBAAe,IAAI,MAAM;AACjC,QAAMA,gBAAe,QAAQ,IAAI,GAAG,EAAE,MAAM,OAAO,KAAK,QAAQ,IAAI,EAAE,CAAC;AACzE,CAAC;AAEH,QAAQ,MAAM,QAAQ,IAAI;","names":["cost","path","fs","import_fs","import_path","round2","fs","path","import_fs","import_path","exports","module","ensureDir","fs","path","import_fs","import_path","fs","path","import_fs","import_path","crypto","path","fs","import_fs","import_path","round2","conf","msg","path","fs","http","import_fs","import_path","import_fs","import_path","fs","parseCsv","path","path","fs","buildTopFixes","runInstall","runDoctor","DEFAULT_PUBLIC_KEY_PEM","defaultLicensePath","verifyLicenseKey","writeLicenseFile","readLicenseFile","runGuard","startDashboard"]}
|
|
1
|
+
{"version":3,"sources":["../src/cost.ts","../src/solutions.ts","../src/scan.ts","../package.json","../src/install.ts","../src/doctor.ts","../src/license.ts","../src/guard.ts","../src/dashboard.ts","../src/cli.ts","../src/io.ts"],"sourcesContent":["import { RateTable, UsageEvent } from './types';\n\nexport type CostResult = {\n cost: number;\n used_rate: {\n kind: 'billed_cost' | 'official' | 'estimated';\n provider: string;\n model: string;\n input_per_m: number;\n output_per_m: number;\n };\n};\n\nexport function getRates(rt: RateTable, provider: string, model: string) {\n const prov = String(provider || '').toLowerCase();\n\n // local/offline LLM: treat cost as 0 (or user can add a provider rate later)\n if (prov === 'local' || prov === 'ollama' || prov === 'vllm') {\n return { kind: 'official' as const, input: 0, output: 0 };\n }\n\n const p = rt.providers[prov];\n if (!p) return null;\n const m = p.models[model];\n if (m) return { kind: 'official' as const, input: m.input, output: m.output };\n return { kind: 'estimated' as const, input: p.default_estimated.input, output: p.default_estimated.output };\n}\n\nexport function costOfEvent(rt: RateTable, ev: UsageEvent): CostResult {\n if (typeof ev.billed_cost === 'number' && Number.isFinite(ev.billed_cost)) {\n return {\n cost: ev.billed_cost,\n used_rate: {\n kind: 'billed_cost',\n provider: ev.provider,\n model: ev.model,\n input_per_m: 0,\n output_per_m: 0\n }\n };\n }\n\n const r = getRates(rt, ev.provider, ev.model);\n if (!r) {\n // Unknown provider: deterministic fallback estimate (kept stable for reproducibility)\n const input_per_m = 1.0;\n const output_per_m = 4.0;\n const cost = (ev.input_tokens / 1e6) * input_per_m + (ev.output_tokens / 1e6) * output_per_m;\n return {\n cost,\n used_rate: { kind: 'estimated', provider: String(ev.provider || '').toLowerCase(), model: ev.model, input_per_m, output_per_m }\n };\n }\n\n const cost = (ev.input_tokens / 1e6) * r.input + (ev.output_tokens / 1e6) * r.output;\n return {\n cost,\n used_rate: {\n kind: r.kind,\n provider: ev.provider,\n model: ev.model,\n input_per_m: r.input,\n output_per_m: r.output\n }\n };\n}\n","import fs from 'fs';\nimport path from 'path';\nimport { AnalysisJson, Savings } from './scan';\n\nexport type Fix = {\n id: string;\n title: string;\n impact_usd: number;\n why: string;\n what_to_change: string[];\n status: 'action' | 'no-issue';\n};\n\nconst EPS = 0.0001;\n\nexport function buildTopFixes(analysis: AnalysisJson, savings: Savings): Fix[] {\n const fixes: Fix[] = [];\n\n // Retry tuning\n fixes.push({\n id: 'fix-retry-tuning',\n title: 'Retry tuning',\n impact_usd: Number(savings.retry_waste || 0),\n status: Number(savings.retry_waste || 0) > EPS ? 'action' : 'no-issue',\n why: `Retry waste is estimated at $${round2(Number(savings.retry_waste || 0))}.`,\n what_to_change: [\n 'aiopt/policies/retry.json: lower max_attempts or adjust backoff_ms',\n 'Ensure idempotency keys are stable per trace_id',\n 'Log error_code to identify retryable classes'\n ]\n });\n\n // Output cap (use context_savings as proxy impact)\n fixes.push({\n id: 'fix-output-cap',\n title: 'Output cap',\n impact_usd: Number(savings.context_savings || 0),\n status: Number(savings.context_savings || 0) > EPS ? 'action' : 'no-issue',\n why: `Context savings estimate: $${round2(Number(savings.context_savings || 0))}. Output caps prevent runaway completions.`,\n what_to_change: [\n 'aiopt/policies/output.json: set max_output_tokens_default',\n 'aiopt/policies/output.json: set per_feature caps (summarize/classify/translate)'\n ]\n });\n\n // Routing\n const topFeature = analysis.by_feature_top?.[0]?.key;\n fixes.push({\n id: 'fix-routing',\n title: 'Routing rule',\n impact_usd: Number(savings.routing_savings || 0),\n status: Number(savings.routing_savings || 0) > EPS ? 'action' : 'no-issue',\n why: `Routing savings estimate: $${round2(Number(savings.routing_savings || 0))}.`,\n what_to_change: [\n 'aiopt/policies/routing.json: route summarize/classify/translate to cheap tier',\n `Consider adding feature_tag_in for top feature: ${topFeature || '(unknown)'}`\n ]\n });\n\n // sort by impact desc, deterministic tie-break\n fixes.sort((a, b) => (b.impact_usd - a.impact_usd) || a.id.localeCompare(b.id));\n return fixes;\n}\n\nfunction round2(n: number) {\n return Math.round(n * 100) / 100;\n}\n\nexport function writePatches(outDir: string, fixes: Fix[]) {\n const patchesDir = path.join(outDir, 'patches');\n fs.mkdirSync(patchesDir, { recursive: true });\n\n const readme = [\n '# AIOpt patches (MVP)',\n '',\n 'This folder contains suggested changes you can apply locally.',\n '',\n '## Top fixes',\n ...fixes.map((f, i) => `${i + 1}. ${f.title} — ${f.why}`),\n '',\n 'Files are stubs (human review required).',\n ''\n ].join('\\n');\n\n fs.writeFileSync(path.join(patchesDir, 'README.md'), readme);\n\n // Minimal stub files to satisfy DoD naming.\n fs.writeFileSync(path.join(patchesDir, 'policies.updated.routing.json'), JSON.stringify({ note: 'apply changes to aiopt/policies/routing.json', fixes: fixes.filter(f => f.id.includes('routing')) }, null, 2));\n fs.writeFileSync(path.join(patchesDir, 'policies.updated.retry.json'), JSON.stringify({ note: 'apply changes to aiopt/policies/retry.json', fixes: fixes.filter(f => f.id.includes('retry')) }, null, 2));\n fs.writeFileSync(path.join(patchesDir, 'policies.updated.output.json'), JSON.stringify({ note: 'apply changes to aiopt/policies/output.json', fixes: fixes.filter(f => f.id.includes('output')) }, null, 2));\n}\n","import fs from 'fs';\nimport path from 'path';\nimport { RateTable, UsageEvent } from './types';\nimport { costOfEvent, getRates } from './cost';\nimport { buildTopFixes, writePatches } from './solutions';\n\nexport type AnalysisJson = {\n total_cost: number;\n by_model_top: Array<{ key: string; cost: number; events: number }>;\n by_feature_top: Array<{ key: string; cost: number; events: number }>;\n unknown_models: Array<{ provider: string; model: string; reason: string }>;\n rate_table_version: string;\n rate_table_date: string;\n};\n\nexport type Savings = {\n estimated_savings_total: number;\n routing_savings: number;\n context_savings: number;\n retry_waste: number;\n notes: [string, string, string];\n};\n\nexport type PolicyJson = {\n version: number;\n default_provider: string;\n rules: Array<any>;\n budgets: { currency: string; notes?: string };\n generated_from: { rate_table_version: string; input: string };\n};\n\nconst ROUTE_TO_CHEAP_FEATURES = new Set(['summarize', 'classify', 'translate']);\n\nfunction topN(map: Map<string, { cost: number; events: number }>, n: number) {\n return [...map.entries()]\n .map(([key, v]) => ({ key, cost: v.cost, events: v.events }))\n .sort((a, b) => b.cost - a.cost)\n .slice(0, n);\n}\n\nexport function analyze(rt: RateTable, events: UsageEvent[]): { analysis: AnalysisJson; savings: Savings; policy: PolicyJson; meta: { mode: 'attempt-log'|'legacy' } } {\n const byModel = new Map<string, { cost: number; events: number }>();\n const byFeature = new Map<string, { cost: number; events: number }>();\n const unknownModels: AnalysisJson['unknown_models'] = [];\n\n const perEventCosts: Array<{ ev: UsageEvent; cost: number }> = [];\n\n // Detect wrapper attempt-log mode: each JSONL line is an attempt (trace_id/attempt present)\n const isAttemptLog = events.some(e => (e.trace_id && String(e.trace_id).length > 0) || (e.attempt !== undefined && Number(e.attempt) > 0));\n\n let baseTotal = 0;\n let total = 0;\n for (const ev of events) {\n const cr = costOfEvent(rt, ev);\n\n baseTotal += cr.cost;\n\n if (isAttemptLog) {\n // Each event line is already one attempt; do NOT multiply by retries.\n total += cr.cost;\n } else {\n // Legacy aggregate mode: one line represents a request with retries count.\n const retries = Math.max(0, Number(ev.retries || 0));\n total += cr.cost * (1 + retries);\n }\n\n perEventCosts.push({ ev, cost: cr.cost });\n\n const mk = `${ev.provider}:${ev.model}`;\n const fk = ev.feature_tag || '(none)';\n\n const mv = byModel.get(mk) || { cost: 0, events: 0 };\n mv.cost += cr.cost; mv.events += 1;\n byModel.set(mk, mv);\n\n const fv = byFeature.get(fk) || { cost: 0, events: 0 };\n fv.cost += cr.cost; fv.events += 1;\n byFeature.set(fk, fv);\n\n const rr = getRates(rt, ev.provider, ev.model);\n if (!rr) {\n unknownModels.push({ provider: ev.provider, model: ev.model, reason: 'unknown provider (estimated)' });\n } else if (rr.kind === 'estimated') {\n unknownModels.push({ provider: ev.provider, model: ev.model, reason: 'unknown model (estimated)' });\n }\n }\n\n // --- Savings simulator (refactor): per-event before/after with caps + no double counting\n type Pot = { routing: number; context: number; retry: number; total: number; waste: number };\n const potByIdx: Pot[] = [];\n\n // Potential routing/context computed per event\n for (const { ev, cost } of perEventCosts) {\n const retries = Math.max(0, Number(ev.retries || 0));\n const attempt = Number(ev.attempt || 1);\n\n const total_i = isAttemptLog ? cost : cost * (1 + retries);\n // Retry waste:\n // - attempt-log mode: attempts >= 2 are retry waste\n // - legacy mode: base_cost * retries\n const waste_i = isAttemptLog ? (attempt >= 2 ? cost : 0) : cost * retries;\n\n let routing_i = 0;\n if (ROUTE_TO_CHEAP_FEATURES.has(String(ev.feature_tag || '').toLowerCase())) {\n const provider = ev.provider;\n const p = rt.providers[provider];\n if (p) {\n const entries = Object.entries(p.models);\n if (entries.length > 0) {\n const cheapest = entries\n .map(([name, r]) => ({ name, score: (r.input + r.output) / 2, r }))\n .sort((a, b) => a.score - b.score)[0];\n const currentRate = getRates(rt, provider, ev.model);\n if (currentRate && currentRate.kind !== 'estimated') {\n const currentCost = (ev.input_tokens / 1e6) * currentRate.input + (ev.output_tokens / 1e6) * currentRate.output;\n const cheapCost = (ev.input_tokens / 1e6) * cheapest.r.input + (ev.output_tokens / 1e6) * cheapest.r.output;\n const diff = (currentCost - cheapCost) * (1 + retries);\n routing_i = Math.max(0, diff);\n }\n }\n }\n }\n\n // context: top 20% rule is applied later by index set\n potByIdx.push({ routing: routing_i, context: 0, retry: waste_i, total: total_i, waste: waste_i });\n }\n\n // context potential assignment (deterministic): top 20% by input_tokens => 25% reduction\n // In attempt-log mode, only apply to attempt==1 to avoid overcounting retries.\n const sortedIdx = [...events.map((e, i) => ({ i, input: Number(e.input_tokens || 0), ok: !isAttemptLog || Number(e.attempt || 1) === 1 }))]\n .filter(x => x.ok)\n .sort((a, b) => b.input - a.input);\n const k = Math.max(1, Math.floor(sortedIdx.length * 0.2));\n const topIdx = new Set(sortedIdx.slice(0, k).map(x => x.i));\n for (let i = 0; i < events.length; i++) {\n if (!topIdx.has(i)) continue;\n const ev = events[i];\n const retries = Math.max(0, Number(ev.retries || 0));\n const r = getRates(rt, ev.provider, ev.model);\n if (!r) continue;\n const saveTokens = (Number(ev.input_tokens || 0)) * 0.25;\n const multiplier = isAttemptLog ? 1 : (1 + retries);\n const diff = (saveTokens / 1e6) * r.input * multiplier;\n potByIdx[i].context = Math.max(0, diff);\n }\n\n // Allocate savings without overlap (routing -> context -> retry), each capped by remaining cost.\n let routingSavings = 0;\n let contextSavings = 0;\n let retryWaste = 0;\n\n for (const p of potByIdx) {\n let remaining = p.total;\n\n const rSave = Math.min(p.routing, remaining);\n remaining -= rSave;\n routingSavings += rSave;\n\n const cSave = Math.min(p.context, remaining);\n remaining -= cSave;\n contextSavings += cSave;\n\n // Retry tuning can only save the waste portion, and cannot exceed remaining.\n const retrySave = Math.min(p.retry, remaining);\n retryWaste += retrySave;\n }\n\n const estimatedSavingsTotal = routingSavings + contextSavings + retryWaste;\n // Global guard\n const guardedSavingsTotal = Math.min(estimatedSavingsTotal, total);\n\n const analysis: AnalysisJson = {\n total_cost: round2(total),\n by_model_top: topN(byModel, 10).map(x => ({ ...x, cost: round2(x.cost) })),\n by_feature_top: topN(byFeature, 10).map(x => ({ ...x, cost: round2(x.cost) })),\n unknown_models: uniqUnknown(unknownModels),\n rate_table_version: rt.version,\n rate_table_date: rt.date\n };\n\n const savings: Savings = {\n estimated_savings_total: round2(guardedSavingsTotal),\n routing_savings: round2(routingSavings),\n context_savings: round2(contextSavings),\n retry_waste: round2(retryWaste),\n notes: [\n `a) 모델 라우팅 절감(추정): $${round2(routingSavings)}`,\n `b) 컨텍스트 감축(추정): $${round2(contextSavings)} (상위 20% input에 25% 감축 가정)` ,\n `c) 재시도/오류 낭비(상한 적용): $${round2(retryWaste)} (retries 기반)`\n ]\n };\n\n const policy: PolicyJson = buildPolicy(rt, events);\n\n return { analysis, savings, policy, meta: { mode: isAttemptLog ? 'attempt-log' : 'legacy' } };\n}\n\nfunction buildPolicy(rt: RateTable, events: UsageEvent[]): PolicyJson {\n // Default provider: most frequent\n const freq = new Map<string, number>();\n for (const ev of events) freq.set(ev.provider, (freq.get(ev.provider) || 0) + 1);\n const defaultProvider = [...freq.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] || 'openai';\n\n // For cheap features: recommend cheapest known model per provider.\n const rules: any[] = [];\n for (const provider of Object.keys(rt.providers)) {\n const p = rt.providers[provider];\n const entries = Object.entries(p.models);\n if (entries.length === 0) continue;\n const cheapest = entries\n .map(([name, r]) => ({ name, score: (r.input + r.output) / 2, r }))\n .sort((a, b) => a.score - b.score)[0];\n\n rules.push({\n match: { provider, feature_tag_in: ['summarize', 'classify', 'translate'] },\n action: { recommend_model: cheapest.name, reason: 'cheap-feature routing' }\n });\n }\n\n // Unknown models: keep (no policy)\n rules.push({ match: { model_unknown: true }, action: { keep: true, reason: 'unknown model -> no policy applied' } });\n\n return {\n version: 1,\n default_provider: defaultProvider,\n rules,\n budgets: { currency: rt.currency, notes: 'MVP: budgets not enforced' },\n generated_from: { rate_table_version: rt.version, input: './aiopt-input/usage.jsonl' }\n };\n}\n\nfunction uniqUnknown(list: AnalysisJson['unknown_models']) {\n const seen = new Set<string>();\n const out: AnalysisJson['unknown_models'] = [];\n for (const x of list) {\n const k = `${x.provider}:${x.model}:${x.reason}`;\n if (seen.has(k)) continue;\n seen.add(k);\n out.push(x);\n }\n return out;\n}\n\nfunction round2(n: number) {\n return Math.round(n * 100) / 100;\n}\n\nexport function writeOutputs(outDir: string, analysis: AnalysisJson, savings: Savings, policy: PolicyJson, meta?: { mode?: 'attempt-log'|'legacy' }) {\n const mode = meta?.mode || 'legacy';\n\n fs.mkdirSync(outDir, { recursive: true });\n\n fs.writeFileSync(path.join(outDir, 'analysis.json'), JSON.stringify(analysis, null, 2));\n\n // report.json is the “one file to parse” summary for downstream tooling.\n const unknownCount = analysis.unknown_models?.length || 0;\n // confidence: downgrade if many unknowns; keep deterministic\n const confidence = unknownCount === 0 ? 'HIGH' : (unknownCount <= 3 ? 'MED' : 'LOW');\n const ratio = analysis.total_cost > 0 ? (savings.estimated_savings_total / analysis.total_cost) : 0;\n const warnings: string[] = [];\n if (ratio >= 0.9) warnings.push('estimated savings >= 90%');\n if (unknownCount > 0) warnings.push('unknown models/providers detected (estimated pricing used)');\n\n const reportJson = {\n version: 3,\n generated_at: new Date().toISOString(),\n confidence,\n warnings,\n assumptions: {\n no_double_counting: 'routing -> context -> retry allocation per-event with remaining-cost caps',\n retry_cost_model: mode === 'attempt-log'\n ? 'attempt-log mode: total_cost is sum of attempt lines; retry_waste is sum of attempts>=2'\n : 'legacy mode: total_cost includes retries as extra attempts (base_cost*(1+retries))',\n context_model: 'top 20% by input_tokens assume 25% input reduction',\n estimated_pricing_note: unknownCount > 0 ? 'some items use estimated rates; treat savings as a band' : 'all items used known rates'\n },\n summary: {\n total_cost_usd: analysis.total_cost,\n estimated_savings_usd: savings.estimated_savings_total,\n routing_savings_usd: savings.routing_savings,\n context_savings_usd: savings.context_savings,\n retry_waste_usd: savings.retry_waste\n },\n top: {\n by_model: analysis.by_model_top,\n by_feature: analysis.by_feature_top\n },\n unknown_models: analysis.unknown_models,\n notes: savings.notes\n };\n fs.writeFileSync(path.join(outDir, 'report.json'), JSON.stringify(reportJson, null, 2));\n\n // report.md: \"what to change\" guidance + confidence/assumptions (T4 DoD)\n const ratioMd = analysis.total_cost > 0 ? (savings.estimated_savings_total / analysis.total_cost) : 0;\n const warningsMd: string[] = [];\n if (ratioMd >= 0.9) warningsMd.push('WARNING: estimated savings >= 90% — check overlap/missing rate table');\n\n const reportMd = [\n '# AIOpt Report',\n '',\n `- Total cost: $${analysis.total_cost}`,\n `- Estimated savings: $${savings.estimated_savings_total} (guarded <= total_cost)`,\n `- Confidence: ${confidence}`,\n unknownCount > 0 ? `- Unknown models: ${unknownCount} (estimated pricing used)` : '- Unknown models: 0',\n ...warningsMd.map(w => `- ${w}`),\n '',\n '## ASSUMPTIONS',\n '- No double-counting: routing → context → retry savings allocated per-event with remaining-cost caps.',\n mode === 'attempt-log'\n ? '- Retry cost model: attempt-log mode (total_cost=sum attempts, retry_waste=sum attempt>=2).'\n : '- Retry cost model: legacy mode (total_cost=base_cost*(1+retries)).',\n '- Context savings: top 20% input_tokens events assume 25% input reduction.',\n '',\n '## WHAT TO CHANGE',\n '1) Retry tuning → edit `aiopt/policies/retry.json`',\n '2) Output cap → edit `aiopt/policies/output.json`',\n '3) Routing rule → edit `aiopt/policies/routing.json`',\n '',\n '## OUTPUTS',\n '- `aiopt-output/analysis.json`',\n '- `aiopt-output/report.json`',\n '- `aiopt-output/patches/*`',\n ''\n ].join('\\n');\n fs.writeFileSync(path.join(outDir, 'report.md'), reportMd);\n\n const reportTxt = [\n `총비용: $${analysis.total_cost}`,\n `절감 가능 금액(Estimated): $${savings.estimated_savings_total}`,\n `절감 근거 3줄:`,\n savings.notes[0],\n savings.notes[1],\n savings.notes[2],\n ''\n ].join('\\n');\n fs.writeFileSync(path.join(outDir, 'report.txt'), reportTxt);\n\n fs.writeFileSync(path.join(outDir, 'cost-policy.json'), JSON.stringify(policy, null, 2));\n\n // patches/*\n const fixes = buildTopFixes(analysis, savings);\n writePatches(outDir, fixes);\n}\n","{\n \"name\": \"aiopt\",\n \"version\": \"0.2.6\",\n \"description\": \"Pre-deploy LLM cost accident guardrail (serverless local CLI)\",\n \"bin\": {\n \"aiopt\": \"dist/cli.js\"\n },\n \"type\": \"commonjs\",\n \"main\": \"dist/cli.js\",\n \"files\": [\n \"dist\",\n \"rates\",\n \"samples\",\n \"README.md\"\n ],\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"node --enable-source-maps dist/cli.js\",\n \"prepack\": \"npm run build\",\n \"test:npx\": \"npm pack --silent && node -e \\\"const fs=require('fs');const p=fs.readdirSync('.').find(f=>/^aiopt-.*\\\\.tgz$/.test(f)); if(!p) throw new Error('tgz not found'); console.log('tgz',p);\\\" && npx --yes ./$(ls -1 aiopt-*.tgz | tail -n 1) install --force && npx --yes ./$(ls -1 aiopt-*.tgz | tail -n 1) doctor && npx --yes ./$(ls -1 aiopt-*.tgz | tail -n 1) scan && test -f ./aiopt-output/report.md && echo OK\",\n \"test:guard\": \"npm run build --silent && node scripts/test-guard.js\",\n \"test:license\": \"npm run build --silent && node scripts/test-license.js\",\n \"test:landing\": \"node scripts/test-landing.js\"\n },\n \"dependencies\": {\n \"commander\": \"^14.0.0\",\n \"csv-parse\": \"^6.1.0\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^24.0.0\",\n \"tsup\": \"^8.5.0\",\n \"typescript\": \"^5.9.2\"\n }\n}\n","import fs from 'fs';\nimport path from 'path';\n\nexport type InstallOptions = {\n force?: boolean;\n seedSample?: boolean;\n};\n\nfunction ensureDir(p: string) {\n fs.mkdirSync(p, { recursive: true });\n}\n\nfunction writeFile(filePath: string, content: string, force?: boolean) {\n if (!force && fs.existsSync(filePath)) return { wrote: false, reason: 'exists' as const };\n ensureDir(path.dirname(filePath));\n fs.writeFileSync(filePath, content);\n return { wrote: true as const };\n}\n\nexport function runInstall(cwd: string, opts: InstallOptions) {\n const force = Boolean(opts.force);\n\n const aioptDir = path.join(cwd, 'aiopt');\n const policiesDir = path.join(aioptDir, 'policies');\n const outDir = path.join(cwd, 'aiopt-output');\n\n ensureDir(aioptDir);\n ensureDir(policiesDir);\n ensureDir(outDir);\n\n const created: Array<{ path: string; status: 'created' | 'skipped' }> = [];\n\n // 1) aiopt/README.md\n const readme = `# AIOpt\n\nAIOpt는 **scan툴이 아니라 설치형 비용 가드레일이다.**\n\n## Quick start\n\\`\\`\\`bash\nnpx aiopt install --force\nnpx aiopt doctor\n# (your app runs, wrapper logs usage)\nnpx aiopt scan\n\\`\\`\\`\n\n- 서버/대시보드/계정/업로드/결제/프록시 없음\n- 로컬 파일 기반(정책 + usage.jsonl)\n- LLM 호출 금지(수학/룰 기반)\n\n## Wrapper usage (Node.js)\n\nAIOpt 설치 후, 앱 코드에서 wrapper를 불러서 사용량 JSONL을 자동 기록할 수 있습니다.\n\n\na) 최소 형태(토큰을 직접 넘김)\n\n\\`\\`\\`js\nconst { guardedCall } = require('./aiopt/aiopt-wrapper.js');\n\nawait guardedCall(process.cwd(), {\n provider: 'openai',\n model: 'gpt-5-mini',\n endpoint: 'responses.create',\n feature_tag: 'summarize',\n prompt_tokens: 1200,\n trace_id: 'my-trace'\n}, async (req) => {\n // req: { provider, model, endpoint, max_output_tokens, prompt_tokens, idempotency_key }\n // 여기서 실제 SDK 호출 후 결과를 반환\n return { status: 'ok', completion_tokens: 200 };\n});\n\\`\\`\\`\n\nb) OpenAI-style 응답(usage 자동 추출)\n\n\\`\\`\\`js\nreturn {\n status: 'ok',\n response: {\n usage: { prompt_tokens: 1200, completion_tokens: 200, total_tokens: 1400 }\n }\n};\n\\`\\`\\`\n`;\n\n const r1 = writeFile(path.join(aioptDir, 'README.md'), readme, force);\n created.push({ path: 'aiopt/README.md', status: r1.wrote ? 'created' : 'skipped' });\n\n // 2) aiopt/aiopt.config.json\n const config = {\n version: 1,\n installed_at: new Date().toISOString(),\n output_dir: './aiopt-output',\n usage_path: './aiopt-output/usage.jsonl',\n policies_dir: './aiopt/policies',\n rate_table: { path: './rates/rate_table.json' }\n };\n const r2 = writeFile(path.join(aioptDir, 'aiopt.config.json'), JSON.stringify(config, null, 2) + '\\n', force);\n created.push({ path: 'aiopt/aiopt.config.json', status: r2.wrote ? 'created' : 'skipped' });\n\n // 3) policies\n const routing = {\n version: 1,\n rules: [\n { match: { feature_tag_in: ['summarize', 'classify', 'translate'] }, action: { tier: 'cheap', reason: 'cheap feature routing' } },\n { match: { feature_tag_in: ['coding', 'reasoning'] }, action: { tier: 'default', reason: 'keep for quality' } }\n ]\n };\n const retry = {\n version: 1,\n max_attempts: 2,\n backoff_ms: [200, 500],\n retry_on_status: ['error', 'timeout'],\n notes: 'MVP deterministic retry tuning'\n };\n const output = {\n version: 1,\n max_output_tokens_default: 1024,\n per_feature: {\n summarize: 512,\n classify: 256,\n translate: 512\n }\n };\n const context = {\n version: 1,\n input_token_soft_cap: 12000,\n reduce_top_percentile: 0.2,\n assumed_reduction_ratio: 0.25\n };\n\n const p1 = writeFile(path.join(policiesDir, 'routing.json'), JSON.stringify(routing, null, 2) + '\\n', force);\n const p2 = writeFile(path.join(policiesDir, 'retry.json'), JSON.stringify(retry, null, 2) + '\\n', force);\n const p3 = writeFile(path.join(policiesDir, 'output.json'), JSON.stringify(output, null, 2) + '\\n', force);\n const p4 = writeFile(path.join(policiesDir, 'context.json'), JSON.stringify(context, null, 2) + '\\n', force);\n\n created.push({ path: 'aiopt/policies/routing.json', status: p1.wrote ? 'created' : 'skipped' });\n created.push({ path: 'aiopt/policies/retry.json', status: p2.wrote ? 'created' : 'skipped' });\n created.push({ path: 'aiopt/policies/output.json', status: p3.wrote ? 'created' : 'skipped' });\n created.push({ path: 'aiopt/policies/context.json', status: p4.wrote ? 'created' : 'skipped' });\n\n // 4) wrapper template (T2: real guardrails wrapper)\n const wrapperPath = path.join(aioptDir, 'aiopt-wrapper.js');\n const wrapper = \n`// AIOpt Wrapper (guardrails) — local-only (CommonJS)\n\nconst fs = require('fs');\n\nconst path = require('path');\n\nconst crypto = require('crypto');\n\nfunction readJson(p){ return JSON.parse(fs.readFileSync(p,'utf8')); }\nfunction ensureDir(p){ fs.mkdirSync(p,{recursive:true}); }\nfunction appendJsonl(filePath,obj){ ensureDir(path.dirname(filePath)); fs.appendFileSync(filePath, JSON.stringify(obj)+'\\\\n'); }\nfunction sleep(ms){ return new Promise(r=>setTimeout(r,ms)); }\n\nfunction loadConfig(cwd){ return readJson(path.join(cwd,'aiopt','aiopt.config.json')); }\nfunction loadPolicies(cwd,cfg){ const dir=path.isAbsolute(cfg.policies_dir)?cfg.policies_dir:path.join(cwd,cfg.policies_dir);\n return {\n retry: readJson(path.join(dir,'retry.json')) ,\n output: readJson(path.join(dir,'output.json'))\n };\n}\nfunction loadRates(cwd,cfg){\n const rp=path.isAbsolute(cfg.rate_table.path)?cfg.rate_table.path:path.join(cwd,cfg.rate_table.path);\n try{ return readJson(rp); }catch(e){\n // Fresh projects may not have a rates/ table yet. Fall back to a safe default.\n return { providers: {} };\n }\n}\n\nfunction costUsd(rt, provider, model, promptTokens, completionTokens){\n const p=rt.providers && rt.providers[provider];\n const r=(p && p.models && p.models[model]) || (p && p.default_estimated) || {input:1.0, output:4.0};\n return (promptTokens/1e6)*r.input + (completionTokens/1e6)*r.output;\n}\n\nfunction pickRoutedModel(rt, provider, featureTag, currentModel){\n const cheap=['summarize','classify','translate'];\n if(!cheap.includes(String(featureTag||'').toLowerCase())) return { model: currentModel, routed_from: null, hit: null };\n const p=rt.providers && rt.providers[provider];\n const entries=p && p.models ? Object.entries(p.models) : [];\n if(!entries.length) return { model: currentModel, routed_from: null, hit: null };\n const cheapest=entries.map(([name,r])=>({name,score:(r.input+r.output)/2})).sort((a,b)=>a.score-b.score)[0];\n if(!cheapest || cheapest.name===currentModel) return { model: currentModel, routed_from: null, hit: null };\n return { model: cheapest.name, routed_from: currentModel, hit: 'routing:cheap-feature' };\n}\n\nfunction outputCap(outputPolicy, featureTag, requested){\n const per=(outputPolicy && outputPolicy.per_feature) || {};\n const cap=per[String(featureTag||'').toLowerCase()] ?? (outputPolicy.max_output_tokens_default || 1024);\n const req=requested ?? cap;\n return Math.min(req, cap);\n}\n\nconst IDEMPOTENCY=new Map();\n\nfunction normalizeResult(out, input){\n // Accept either normalized return or provider raw.\n const o = (out && out.response) ? out.response : out;\n const status = (out && out.status) || o.status || (o.error ? 'error' : 'ok');\n const usage = o.usage || (o.data && o.data.usage) || null;\n\n const prompt_tokens = Number(\n (out && out.prompt_tokens) ??\n (o && o.prompt_tokens) ??\n (usage && usage.prompt_tokens) ??\n input.prompt_tokens ??\n 0\n );\n const completion_tokens = Number(\n (out && out.completion_tokens) ??\n (o && o.completion_tokens) ??\n (usage && usage.completion_tokens) ??\n 0\n );\n const total_tokens = Number(\n (out && out.total_tokens) ??\n (o && o.total_tokens) ??\n (usage && usage.total_tokens) ??\n (prompt_tokens + completion_tokens)\n );\n\n const error_code = status === 'ok' ? null : String((out && out.error_code) || (o && o.error_code) || (o && o.error && (o.error.code || o.error.type)) || status);\n const cost_usd = (out && typeof out.cost_usd === 'number') ? out.cost_usd : null;\n\n return { status, prompt_tokens, completion_tokens, total_tokens, error_code, cost_usd };\n}\n\n/**\n * guardedCall(cwd, input, fn)\n *\n * fn(req) can return either:\n * 1) Normalized shape:\n * { status: 'ok'|'error'|'timeout', prompt_tokens?, completion_tokens?, total_tokens?, cost_usd?, error_code? }\n * 2) Provider raw response (OpenAI-style), e.g.:\n * { status:'ok', response:{ usage:{prompt_tokens, completion_tokens, total_tokens} } }\n * { usage:{prompt_tokens, completion_tokens, total_tokens} }\n *\n * If token fields are missing, AIOpt will fall back to input.prompt_tokens and/or 0.\n */\nasync function guardedCall(cwd, input, fn){\n const cfg=loadConfig(cwd);\n const pol=loadPolicies(cwd,cfg);\n const rt=loadRates(cwd,cfg);\n\n const request_id=crypto.randomUUID();\n const trace_id=input.trace_id || request_id;\n const idem=input.idempotency_key || trace_id;\n if(IDEMPOTENCY.has(idem)) return IDEMPOTENCY.get(idem);\n\n const routed=pickRoutedModel(rt, input.provider, input.feature_tag, input.model);\n const maxOut=outputCap(pol.output, input.feature_tag, input.max_output_tokens);\n const usagePath=path.isAbsolute(cfg.usage_path)?cfg.usage_path:path.join(cwd,cfg.usage_path);\n\n const maxAttempts=Math.max(1, Number(pol.retry.max_attempts||1));\n const backoffs=pol.retry.backoff_ms || [200];\n const retryOn=new Set(pol.retry.retry_on_status || ['error','timeout']);\n\n let last={status:'error', completion_tokens:0, error_code:'unknown'};\n\n for(let attempt=1; attempt<=maxAttempts; attempt++){\n const t0=Date.now();\n const policy_hits=[];\n if(routed.hit) policy_hits.push(routed.hit);\n policy_hits.push('outputcap:'+maxOut);\n try{\n const out=await fn({ provider: input.provider, model: routed.model, endpoint: input.endpoint, max_output_tokens: maxOut, prompt_tokens: input.prompt_tokens, idempotency_key: idem });\n const latency_ms=Date.now()-t0;\n const norm=normalizeResult(out, input);\n const cost_usd=(typeof norm.cost_usd==='number') ? norm.cost_usd : costUsd(rt, input.provider, routed.model, norm.prompt_tokens, norm.completion_tokens);\n const feature_tag = input.feature_tag || input.endpoint || 'unknown';\n appendJsonl(usagePath, { ts:new Date().toISOString(), request_id, trace_id, attempt, status: norm.status, error_code: norm.error_code, provider: input.provider, model: routed.model, endpoint: input.endpoint, prompt_tokens: norm.prompt_tokens, completion_tokens: norm.completion_tokens, total_tokens: norm.total_tokens, cost_usd, latency_ms, meta:{ feature_tag, routed_from: routed.routed_from, policy_hits } });\n last={ status: norm.status, completion_tokens: norm.completion_tokens, error_code: norm.error_code };\n if(norm.status==='ok'){ IDEMPOTENCY.set(idem,out); return out; }\n if(retryOn.has(norm.status) && attempt<maxAttempts){ await sleep(Number(backoffs[Math.min(attempt-1, backoffs.length-1)]||200)); continue; }\n IDEMPOTENCY.set(idem,out); return out;\n }catch(e){\n const latency_ms=Date.now()-t0;\n const out={ status:'error', completion_tokens:0, error_code:String(e && (e.code||e.name) || 'exception') };\n const feature_tag = input.feature_tag || input.endpoint || 'unknown';\n appendJsonl(usagePath, { ts:new Date().toISOString(), request_id, trace_id, attempt, status: out.status, error_code: out.error_code, provider: input.provider, model: routed.model, endpoint: input.endpoint, prompt_tokens:Number(input.prompt_tokens||0), completion_tokens:0, total_tokens:Number(input.prompt_tokens||0), cost_usd:costUsd(rt, input.provider, routed.model, Number(input.prompt_tokens||0), 0), latency_ms, meta:{ feature_tag, routed_from: routed.routed_from, policy_hits:[routed.hit||'routing:none','outputcap:'+maxOut,'error:exception'] } });\n last=out;\n if(attempt<maxAttempts){ await sleep(Number(backoffs[Math.min(attempt-1, backoffs.length-1)]||200)); continue; }\n IDEMPOTENCY.set(idem,out); return out;\n }\n }\n IDEMPOTENCY.set(idem,last);\n return last;\n}\n\nmodule.exports = { guardedCall };\n`;\n;\n const w = writeFile(wrapperPath, wrapper, force);\n created.push({ path: 'aiopt/aiopt-wrapper.js', status: w.wrote ? 'created' : 'skipped' });\n\n // 5) usage.jsonl\n const usagePath = path.join(outDir, 'usage.jsonl');\n if (force || !fs.existsSync(usagePath)) {\n // default: empty file (avoid mixing demo data into real user logs)\n fs.writeFileSync(usagePath, '');\n created.push({ path: 'aiopt-output/usage.jsonl', status: 'created' });\n\n if (opts.seedSample) {\n const sample = {\n ts: new Date().toISOString(),\n request_id: 'sample',\n trace_id: 'sample',\n attempt: 1,\n status: 'ok',\n error_code: null,\n provider: 'openai',\n model: 'gpt-5-mini',\n endpoint: 'demo',\n prompt_tokens: 12,\n completion_tokens: 3,\n total_tokens: 15,\n cost_usd: 0.0,\n latency_ms: 1,\n meta: { feature_tag: 'demo', routed_from: null, policy_hits: ['install-sample'] }\n };\n fs.appendFileSync(usagePath, JSON.stringify(sample) + '\\n');\n }\n } else {\n created.push({ path: 'aiopt-output/usage.jsonl', status: 'skipped' });\n }\n\n return { created };\n}\n","import fs from 'fs';\nimport path from 'path';\n\nfunction canWrite(dir: string) {\n try {\n fs.mkdirSync(dir, { recursive: true });\n const p = path.join(dir, `.aiopt-write-test-${Date.now()}`);\n fs.writeFileSync(p, 'ok');\n fs.unlinkSync(p);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction tailLines(filePath: string, n: number): string[] {\n try {\n const raw = fs.readFileSync(filePath, 'utf8');\n const lines = raw.split(/\\r?\\n/).filter(l => l.trim().length > 0);\n return lines.slice(Math.max(0, lines.length - n));\n } catch {\n return [];\n }\n}\n\nexport type DoctorResult = {\n ok: boolean;\n checks: Array<{ name: string; ok: boolean; detail?: string }>;\n last5: Array<{ status?: string; provider?: string; model?: string; endpoint?: string; attempt?: number }>;\n};\n\nexport function runDoctor(cwd: string): DoctorResult {\n const aioptDir = path.join(cwd, 'aiopt');\n const policiesDir = path.join(aioptDir, 'policies');\n const outDir = path.join(cwd, 'aiopt-output');\n const usagePath = path.join(outDir, 'usage.jsonl');\n\n const checks: DoctorResult['checks'] = [];\n\n checks.push({ name: 'aiopt/ exists', ok: fs.existsSync(aioptDir) });\n checks.push({ name: 'aiopt/policies exists', ok: fs.existsSync(policiesDir) });\n checks.push({ name: 'aiopt-output/ writable', ok: canWrite(outDir) });\n checks.push({ name: 'usage.jsonl exists', ok: fs.existsSync(usagePath), detail: usagePath });\n\n const last5raw = tailLines(usagePath, 5);\n const last5 = last5raw.length === 0 ? [{ status: '(empty usage.jsonl)' }] as any : last5raw.map(l => {\n try {\n const j = JSON.parse(l);\n return {\n status: j.status,\n provider: j.provider,\n model: j.model,\n endpoint: j.endpoint,\n attempt: j.attempt,\n feature_tag: j?.meta?.feature_tag\n };\n } catch {\n return {};\n }\n });\n\n // Feature-tag quality check (sample last 50 lines)\n const last50 = tailLines(usagePath, 50);\n let missing = 0;\n let total50 = 0;\n for (const l of last50) {\n total50++;\n try {\n const j = JSON.parse(l);\n const ft = j?.meta?.feature_tag;\n if (!ft || String(ft).trim() === '') missing++;\n } catch {\n missing++;\n }\n }\n if (total50 > 0 && missing > 0) {\n checks.push({ name: 'feature_tag quality (last50)', ok: false, detail: `${missing}/${total50} missing meta.feature_tag` });\n } else {\n checks.push({ name: 'feature_tag quality (last50)', ok: true, detail: 'meta.feature_tag present' });\n }\n\n const ok = checks.every(c => c.ok);\n return { ok, checks, last5 };\n}\n\n","import crypto from 'crypto';\nimport fs from 'fs';\nimport path from 'path';\n\nexport type LicensePayload = {\n sub: string; // customer id/email/etc\n plan: 'pro' | 'team' | 'trial' | string;\n iat: number; // issued at (unix seconds)\n exp: number; // expires at (unix seconds)\n features?: Record<string, boolean>;\n};\n\nexport type LicenseFile = {\n key: string;\n payload: LicensePayload;\n verified: boolean;\n verified_at: string;\n};\n\n// NOTE: Public key only. No servers.\n// Replace this with your own RSA public key in PEM (SPKI) format.\nexport const DEFAULT_PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz1LLE/pXIx5TloDa0LAf\njg9NSIW6STWhsAFP2ZzXgpWoQ3cCmW6xcB/4QNEmPpGlfMWhyRfkxsdKuhnjUMTg\n8MpMAcbjjF8JrGS9iLnW4yrLm7jzsOcndjkGO7pH+32GopZk98dVzmIRPok2Je76\n3MQRaxLi0jWytaCmacEB4R7HyuquOQlHPg0vD9NOEwrC/+br2GdQbD1lKPyLeLv3\nRidwAs8Iw2xx5g8G+BsVSM/HRC3jQT5GynfnuDsvMHCvGLRct/76ajiR71/NFZEP\nZ7liILNnZzCTlKGGZfZmG70t+zkg8HKdpRuWy8rZ0DPWyQg5MKm6TZOMV6dC0Rpg\nDwIDAQAB\n-----END PUBLIC KEY-----`;\n\nfunction b64urlDecodeToBuffer(s: string): Buffer {\n const padLen = (4 - (s.length % 4)) % 4;\n const padded = s.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat(padLen);\n return Buffer.from(padded, 'base64');\n}\n\nfunction safeJsonParse(buf: Buffer): any {\n const txt = buf.toString('utf8');\n return JSON.parse(txt);\n}\n\nexport function parseLicenseKey(key: string): { payload: LicensePayload; signature: Buffer; payloadB64Url: string } {\n const parts = String(key).trim().split('.');\n if (parts.length !== 2) throw new Error('invalid license key format: expected <payloadB64Url>.<sigB64Url>');\n const [payloadB64Url, sigB64Url] = parts;\n const payloadBuf = b64urlDecodeToBuffer(payloadB64Url);\n const sigBuf = b64urlDecodeToBuffer(sigB64Url);\n const payload = safeJsonParse(payloadBuf) as LicensePayload;\n return { payload, signature: sigBuf, payloadB64Url };\n}\n\nexport function verifyLicenseKey(key: string, publicKeyPem: string): { ok: boolean; reason?: string; payload?: LicensePayload } {\n let parsed: { payload: LicensePayload; signature: Buffer; payloadB64Url: string };\n try {\n parsed = parseLicenseKey(key);\n } catch (e: any) {\n return { ok: false, reason: e?.message || 'parse error' };\n }\n\n const now = Math.floor(Date.now() / 1000);\n if (typeof parsed.payload?.exp !== 'number' || parsed.payload.exp < now) {\n return { ok: false, reason: 'expired', payload: parsed.payload };\n }\n\n try {\n const verifier = crypto.createVerify('RSA-SHA256');\n verifier.update(parsed.payloadB64Url);\n verifier.end();\n const ok = verifier.verify(publicKeyPem, parsed.signature);\n if (!ok) return { ok: false, reason: 'bad signature', payload: parsed.payload };\n return { ok: true, payload: parsed.payload };\n } catch (e: any) {\n return { ok: false, reason: e?.message || 'verify error', payload: parsed.payload };\n }\n}\n\nexport function defaultLicensePath(cwd: string): string {\n return path.join(cwd, 'aiopt', 'license.json');\n}\n\nexport function writeLicenseFile(p: string, key: string, payload: LicensePayload, verified: boolean) {\n const out: LicenseFile = {\n key,\n payload,\n verified,\n verified_at: new Date().toISOString()\n };\n fs.mkdirSync(path.dirname(p), { recursive: true });\n fs.writeFileSync(p, JSON.stringify(out, null, 2));\n}\n\nexport function readLicenseFile(p: string): LicenseFile {\n return JSON.parse(fs.readFileSync(p, 'utf8')) as LicenseFile;\n}\n","import { RateTable, UsageEvent } from './types';\nimport { analyze } from './scan';\nimport { costOfEvent } from './cost';\n\nexport type GuardInput = {\n baselineEvents: UsageEvent[];\n candidate: {\n provider?: string;\n model?: string;\n contextMultiplier?: number; // multiplies input_tokens\n outputMultiplier?: number; // multiplies output_tokens\n retriesDelta?: number; // adds to retries\n callMultiplier?: number; // multiplies call volume\n };\n};\n\nexport type GuardResult = {\n exitCode: 0 | 2 | 3;\n message: string;\n};\n\nfunction accidentRiskFromMonthly(monthly: number): 'Low' | 'Medium' | 'High' {\n if (!Number.isFinite(monthly)) return 'Medium';\n if (monthly >= 100) return 'High';\n if (monthly >= 10) return 'Medium';\n return 'Low';\n}\n\nfunction round2(n: number) {\n return Math.round(n * 100) / 100;\n}\n\nfunction monthEstimate(delta: number, events: UsageEvent[]) {\n // Convert observed delta (over the sample window) into a monthly estimate.\n // Prefer timestamp-derived window length for determinism; fall back to 1 day.\n let days = 1;\n try {\n const times = events\n .map(e => Date.parse(e.ts))\n .filter(t => Number.isFinite(t))\n .sort((a, b) => a - b);\n if (times.length >= 2) {\n const spanMs = Math.max(0, times[times.length - 1] - times[0]);\n const spanDays = spanMs / (1000 * 60 * 60 * 24);\n // If logs cover <1 day (or identical timestamps), treat as 1 day.\n days = Math.max(1, spanDays);\n }\n } catch {\n days = 1;\n }\n return (delta * 30) / days;\n}\n\nfunction applyCandidate(events: UsageEvent[], cand: GuardInput['candidate']): UsageEvent[] {\n const ctxM = cand.contextMultiplier ?? 1;\n const outM = cand.outputMultiplier ?? 1;\n const rDelta = cand.retriesDelta ?? 0;\n\n return events.map(ev => ({\n ...ev,\n provider: cand.provider ? String(cand.provider).toLowerCase() : ev.provider,\n model: cand.model ? String(cand.model) : ev.model,\n input_tokens: Math.max(0, Math.round((ev.input_tokens || 0) * ctxM)),\n output_tokens: Math.max(0, Math.round((ev.output_tokens || 0) * outM)),\n retries: Math.max(0, Math.round((ev.retries || 0) + rDelta)),\n // clear billed_cost so pricing recalculates for new model/provider\n billed_cost: undefined\n }));\n}\n\nfunction confidenceFromChange(cand: GuardInput['candidate']): { level: 'High'|'Medium'|'Low'; reasons: string[] } {\n const reasons: string[] = [];\n\n if (cand.retriesDelta && cand.retriesDelta !== 0) reasons.push('retries change');\n if (cand.model) reasons.push('model change');\n if (cand.provider) reasons.push('provider change');\n if (cand.contextMultiplier && cand.contextMultiplier !== 1) reasons.push('context length change');\n if (cand.outputMultiplier && cand.outputMultiplier !== 1) reasons.push('output length change');\n\n // Spec rule:\n // High: retries/failed/dup calls (we only model retries here)\n // Medium: model/provider change\n // Low: context trimming / prompt structure\n if (cand.retriesDelta && cand.retriesDelta !== 0) return { level: 'High', reasons };\n if (cand.model || cand.provider) return { level: 'Medium', reasons };\n if ((cand.contextMultiplier && cand.contextMultiplier !== 1) || (cand.outputMultiplier && cand.outputMultiplier !== 1)) {\n return { level: 'Low', reasons };\n }\n return { level: 'Medium', reasons: reasons.length ? reasons : ['unknown change'] };\n}\n\nfunction assessDataQuality(baselineEvents: UsageEvent[], base: ReturnType<typeof analyze>) {\n const reasons: string[] = [];\n\n // ts span\n const times = baselineEvents\n .map(e => Date.parse(e.ts))\n .filter(t => Number.isFinite(t))\n .sort((a, b) => a - b);\n if (times.length < 2) reasons.push('ts span unknown');\n else {\n const spanDays = Math.max(0, (times[times.length - 1] - times[0]) / (1000 * 60 * 60 * 24));\n if (spanDays < 0.25) reasons.push('ts span too short');\n }\n\n // feature tag coverage\n const missingFt = baselineEvents.filter(e => !e.feature_tag && !(e.meta && (e.meta as any).feature_tag)).length;\n if (missingFt / Math.max(1, baselineEvents.length) > 0.2) reasons.push('feature_tag missing >20%');\n\n // unknown model/provider\n const unknown = (base.analysis.unknown_models || []).length;\n if (unknown / Math.max(1, baselineEvents.length) > 0.2) reasons.push('unknown model/provider >20%');\n\n // Map to a confidence penalty.\n let penalty: 'none'|'low'|'medium' = 'none';\n if (reasons.length >= 2) penalty = 'medium';\n else if (reasons.length === 1) penalty = 'low';\n\n return { reasons, penalty };\n}\n\nfunction degrade(level: 'High'|'Medium'|'Low', penalty: 'none'|'low'|'medium'): 'High'|'Medium'|'Low' {\n if (penalty === 'none') return level;\n if (penalty === 'low') return level === 'High' ? 'Medium' : 'Low';\n // medium\n return 'Low';\n}\n\nexport function runGuard(rt: RateTable, input: GuardInput): GuardResult {\n if (!input.baselineEvents || input.baselineEvents.length === 0) {\n const conf = { level: 'Low' as const, reasons: ['baseline empty'] };\n const msg = [\n 'FAIL: baseline usage is empty (need aiopt-output/usage.jsonl)',\n 'Impact (monthly est): +$0 (insufficient baseline)',\n `Accident risk: ${accidentRiskFromMonthly(100)}`,\n `Confidence: ${conf.level} (${(conf.reasons.length ? conf.reasons.join(', ') : 'baseline empty')})`,\n 'Recommendation: run the wrapper to collect baseline usage before using guard.'\n ].join('\\n');\n return { exitCode: 3, message: msg };\n }\n\n // For fair comparison, ignore billed_cost/cost_usd and recompute both sides from rate table.\n const baselineEvents = input.baselineEvents.map(e => ({ ...e, billed_cost: undefined }));\n const base = analyze(rt, baselineEvents);\n const candidateEvents = applyCandidate(baselineEvents, input.candidate);\n const cand = analyze(rt, candidateEvents);\n\n const baseCost = base.analysis.total_cost;\n let candCost = cand.analysis.total_cost;\n\n // call volume multiplier (traffic spike)\n const callMult = input.candidate.callMultiplier && input.candidate.callMultiplier > 0 ? input.candidate.callMultiplier : 1;\n if (callMult !== 1) {\n candCost = candCost * callMult;\n }\n\n // attempt-log baseline: retriesDelta should be interpreted as \"extra attempts\".\n const attemptLog = baselineEvents.some(e => (e.trace_id && String(e.trace_id).length > 0) || (e.attempt !== undefined && Number(e.attempt) > 0));\n if (attemptLog && input.candidate.retriesDelta && input.candidate.retriesDelta > 0) {\n // More accurate deterministic approximation:\n // - If baseline already has retry attempts (attempt>=2), use their average cost as retry unit.\n // - Else fall back to avg baseline attempt cost.\n let retryUnit = 0;\n let retryCount = 0;\n for (const ev of baselineEvents) {\n const attempt = Number(ev.attempt || 1);\n if (attempt >= 2) {\n retryUnit += costOfEvent(rt, ev).cost;\n retryCount += 1;\n }\n }\n if (retryCount > 0) {\n retryUnit = retryUnit / retryCount;\n } else {\n retryUnit = baseCost / Math.max(1, baselineEvents.length);\n }\n candCost += retryUnit * input.candidate.retriesDelta;\n }\n\n const delta = candCost - baseCost;\n\n const changeConf = confidenceFromChange(input.candidate);\n const dq = assessDataQuality(baselineEvents, base);\n const conf = { level: degrade(changeConf.level, dq.penalty), reasons: [...changeConf.reasons, ...dq.reasons.map(r => `data: ${r}`)] };\n\n // Guard logic:\n // - Warning if delta > 0 and monthEstimate(delta) >= $10\n // - Fail if delta > 0 and monthEstimate(delta) >= $100 (merge-blocking)\n const monthly = monthEstimate(Math.max(0, delta), baselineEvents);\n const monthlyRounded = round2(monthly);\n\n let exitCode: 0 | 2 | 3 = 0;\n let headline = 'OK: no cost accident risk detected';\n\n if (monthly >= 100) { exitCode = 3; headline = 'FAIL: high risk of LLM cost accident'; }\n else if (monthly >= 10) { exitCode = 2; headline = 'WARN: possible LLM cost accident'; }\n\n const reasons = conf.reasons.length ? conf.reasons.join(', ') : 'n/a';\n\n const msg = [\n headline,\n `Summary: baseline=$${round2(baseCost)} → candidate=$${round2(candCost)} (Δ=$${round2(delta)})`,\n callMult !== 1 ? `Call volume multiplier: x${callMult}` : null,\n `Impact (monthly est): +$${monthlyRounded}`,\n `Accident risk: ${accidentRiskFromMonthly(monthly)}`,\n `Confidence: ${conf.level} (${reasons})`,\n 'Recommendation: review model/provider/retry/context changes before deploy.'\n ].filter(Boolean).join('\\n');\n\n return { exitCode, message: msg };\n}\n","import http from 'http';\nimport fs from 'fs';\nimport path from 'path';\n\nexport async function startDashboard(cwd: string, opts: { port: number }) {\n const host = '127.0.0.1';\n const port = opts.port || 3010;\n\n const outDir = path.join(cwd, 'aiopt-output');\n const file = (name: string) => path.join(outDir, name);\n\n function readOrNull(p: string) {\n try {\n if (!fs.existsSync(p)) return null;\n return fs.readFileSync(p, 'utf8');\n } catch {\n return null;\n }\n }\n\n const indexHtml = `<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\"/>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"/>\n <title>AIOpt Local Dashboard</title>\n <style>\n :root{\n --bg:#070b16; --card:#0b1222; --card2:#0e1730; --txt:#e7eaf2; --muted:#a3acc2;\n --border:rgba(255,255,255,.10);\n --ok:#34d399; --warn:#fbbf24; --fail:#fb7185;\n --shadow:0 18px 70px rgba(0,0,0,.35);\n }\n *{box-sizing:border-box}\n body{margin:0; font-family: ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto; background:var(--bg); color:var(--txt)}\n a{color:#bfffe3; text-decoration:none} a:hover{text-decoration:underline}\n .wrap{max-width:1100px; margin:0 auto; padding:18px}\n .top{display:flex; align-items:center; justify-content:space-between; gap:10px; flex-wrap:wrap}\n .h1{font-size:22px; font-weight:950; letter-spacing:-.02em}\n .pill{display:inline-flex; align-items:center; gap:8px; padding:7px 10px; border-radius:999px; border:1px solid var(--border);\n background:rgba(255,255,255,.03); color:var(--muted); font-size:12px; line-height:1}\n .dot{width:8px;height:8px;border-radius:99px;background:linear-gradient(90deg,#60a5fa,#34d399)}\n\n .grid{display:grid; grid-template-columns:repeat(12,1fr); gap:12px; margin-top:12px}\n .card{grid-column: span 12; background:linear-gradient(180deg, rgba(255,255,255,.03), rgba(255,255,255,0)), var(--card);\n border:1px solid var(--border); border-radius:18px; padding:14px; box-shadow: var(--shadow)}\n @media(min-width: 920px){\n .c6{grid-column: span 6}\n .c4{grid-column: span 4}\n .c8{grid-column: span 8}\n }\n\n .k{padding:2px 6px; border-radius:8px; border:1px solid var(--border); font-family: ui-monospace; font-size:12px; color:#d7def2; background:rgba(255,255,255,.03)}\n .muted{color:var(--muted)}\n .row{display:flex; gap:10px; flex-wrap:wrap; align-items:center}\n\n .badge{display:inline-flex; align-items:center; gap:8px; padding:8px 10px; border-radius:14px; border:1px solid var(--border);\n background:rgba(255,255,255,.03); font-weight:900}\n .badge.ok{border-color:rgba(52,211,153,.35)}\n .badge.warn{border-color:rgba(251,191,36,.35)}\n .badge.fail{border-color:rgba(251,113,133,.35)}\n .badge .b{width:10px;height:10px;border-radius:99px}\n .badge.ok .b{background:var(--ok)}\n .badge.warn .b{background:var(--warn)}\n .badge.fail .b{background:var(--fail)}\n\n pre{margin:0; white-space:pre-wrap; word-break:break-word; background: rgba(3,6,14,.65);\n border:1px solid rgba(255,255,255,.12);\n padding:12px; border-radius:14px;\n font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \"Liberation Mono\"; font-size:13px; line-height:1.55}\n\n .bars{display:flex; flex-direction:column; gap:8px; margin-top:8px}\n .bar{display:grid; grid-template-columns: 1fr 64px; gap:10px; align-items:center}\n .track{height:10px; border-radius:999px; background:rgba(255,255,255,.08); overflow:hidden; border:1px solid rgba(255,255,255,.10)}\n .fill{height:100%; border-radius:999px; background:linear-gradient(90deg,#60a5fa,#34d399)}\n .label{font-size:13px}\n .val{font-family: ui-monospace; font-size:12px; color:#d7def2; text-align:right}\n\n .mini{font-size:12px; color:var(--muted)}\n </style>\n</head>\n<body>\n <div class=\"wrap\">\n <div class=\"top\">\n <div class=\"h1\">AIOpt Local Dashboard</div>\n <div class=\"pill\"><span class=\"dot\"></span> local-only · reads <span class=\"k\">./aiopt-output</span></div>\n </div>\n\n <div class=\"grid\">\n <div class=\"card c6\">\n <div class=\"row\" style=\"justify-content:space-between\">\n <div style=\"font-weight:950\">Guard verdict</div>\n <div class=\"mini\" id=\"guardMeta\">—</div>\n </div>\n <div style=\"height:8px\"></div>\n <div id=\"guardBadge\" class=\"badge\"><span class=\"b\"></span><span id=\"guardBadgeText\">loading…</span></div>\n <div style=\"height:10px\"></div>\n <pre id=\"guard\">loading…</pre>\n <div style=\"height:10px\"></div>\n <div class=\"row\">\n <a href=\"/api/guard-last.txt\" target=\"_blank\">raw txt</a>\n <span class=\"muted\">·</span>\n <a href=\"/api/guard-last.json\" target=\"_blank\">raw json</a>\n </div>\n </div>\n\n <div class=\"card c6\">\n <div class=\"row\" style=\"justify-content:space-between\">\n <div style=\"font-weight:950\">Scan summary</div>\n <div class=\"mini\"><a href=\"/api/report.json\" target=\"_blank\">report.json</a> · <a href=\"/api/report.md\" target=\"_blank\">report.md</a></div>\n </div>\n <div style=\"height:8px\"></div>\n <div class=\"row\">\n <div class=\"badge\" id=\"totalCostBadge\"><span class=\"b\" style=\"background:#60a5fa\"></span><span id=\"totalCost\">total: —</span></div>\n <div class=\"badge\" id=\"savingsBadge\"><span class=\"b\" style=\"background:#a78bfa\"></span><span id=\"savings\">savings: —</span></div>\n </div>\n\n <div style=\"height:12px\"></div>\n <div style=\"font-weight:900\">Cost by model</div>\n <div id=\"byModel\" class=\"bars\"></div>\n\n <div style=\"height:12px\"></div>\n <div style=\"font-weight:900\">Cost by feature</div>\n <div id=\"byFeature\" class=\"bars\"></div>\n\n <div style=\"height:10px\"></div>\n <div class=\"mini\" id=\"scanMeta\">—</div>\n </div>\n\n <div class=\"card\">\n <div class=\"row\" style=\"justify-content:space-between\">\n <div style=\"font-weight:950\">Latest report.md</div>\n <div class=\"mini\">Tip: run <span class=\"k\">aiopt scan</span> after collecting baseline</div>\n </div>\n <div style=\"height:8px\"></div>\n <pre id=\"scan\">loading…</pre>\n </div>\n </div>\n </div>\n\n<script>\nfunction money(x){\n if (x === null || x === undefined || Number.isNaN(Number(x))) return '—';\n return '$' + (Math.round(Number(x)*100)/100);\n}\nfunction renderBars(el, items){\n el.innerHTML='';\n if(!items || items.length===0){ el.innerHTML='<div class=\"mini\">(no data)</div>'; return; }\n const max = Math.max(...items.map(i=>Number(i.cost)||0), 0.000001);\n for(const it of items.slice(0,8)){\n const w = Math.max(2, Math.round(((Number(it.cost)||0)/max)*100));\n const row = document.createElement('div');\n row.className='bar';\n row.innerHTML =\n '<div>'+\n '<div class=\"label\">'+ String(it.key) +'</div>'+\n '<div class=\"track\"><div class=\"fill\" style=\"width:'+ w +'%\"></div></div>'+\n '</div>'+\n '<div class=\"val\">'+ money(it.cost) +'</div>';\n el.appendChild(row);\n }\n}\n\nasync function load(){\n const guardTxt = await fetch('/api/guard-last.txt').then(r=>r.ok?r.text():null);\n const guardMeta = await fetch('/api/guard-last.json').then(r=>r.ok?r.json():null);\n\n document.getElementById('guard').textContent = guardTxt || '(no guard-last.txt yet — run: aiopt guard)';\n if(guardMeta){\n document.getElementById('guardMeta').textContent = 'exit=' + guardMeta.exitCode + ' · ' + guardMeta.ts;\n const badge = document.getElementById('guardBadge');\n const t = document.getElementById('guardBadgeText');\n const code = Number(guardMeta.exitCode);\n badge.classList.remove('ok','warn','fail');\n if(code===0){badge.classList.add('ok'); t.textContent='OK (0)';}\n else if(code===2){badge.classList.add('warn'); t.textContent='WARN (2)';}\n else {badge.classList.add('fail'); t.textContent='FAIL (3)';}\n }\n\n const reportJson = await fetch('/api/report.json').then(r=>r.ok?r.json():null);\n if(reportJson){\n const total = reportJson.summary && reportJson.summary.total_cost_usd;\n const sav = reportJson.summary && reportJson.summary.estimated_savings_usd;\n document.getElementById('totalCost').textContent = 'total: ' + money(total);\n document.getElementById('savings').textContent = 'savings: ' + money(sav);\n renderBars(document.getElementById('byModel'), reportJson.top && reportJson.top.by_model);\n renderBars(document.getElementById('byFeature'), reportJson.top && reportJson.top.by_feature);\n document.getElementById('scanMeta').textContent = 'confidence=' + (reportJson.confidence || '—') + ' · generated_at=' + (reportJson.generated_at || '—');\n } else {\n document.getElementById('scanMeta').textContent = '(no report.json yet — run: aiopt scan)';\n }\n\n const reportMd = await fetch('/api/report.md').then(r=>r.ok?r.text():null);\n document.getElementById('scan').textContent = reportMd || '(no report.md yet — run: aiopt scan)';\n}\nload();\n</script>\n</body>\n</html>`;\n\n const server = http.createServer((req, res) => {\n const url = req.url || '/';\n if (url === '/' || url === '/index.html') {\n res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });\n res.end(indexHtml);\n return;\n }\n\n if (url.startsWith('/api/')) {\n const name = url.replace('/api/', '');\n const allow = new Set(['guard-last.txt', 'guard-last.json', 'report.md', 'report.json']);\n if (!allow.has(name)) {\n res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });\n res.end('not found');\n return;\n }\n\n const p = file(name);\n const txt = readOrNull(p);\n if (txt === null) {\n res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });\n res.end('missing');\n return;\n }\n\n const ct = name.endsWith('.json') ? 'application/json; charset=utf-8' : 'text/plain; charset=utf-8';\n res.writeHead(200, { 'content-type': ct });\n res.end(txt);\n return;\n }\n\n res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });\n res.end('not found');\n });\n\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject);\n server.listen(port, host, () => resolve());\n });\n\n console.log(`OK: dashboard http://${host}:${port}/`);\n console.log('Tip: run `aiopt guard ...` and `aiopt scan` to populate aiopt-output files.');\n\n // keep alive\n await new Promise(() => {});\n}\n","#!/usr/bin/env node\n\nimport fs from 'fs';\nimport path from 'path';\nimport { Command } from 'commander';\nimport { ensureDir, isCsvPath, readCsv, readJsonl } from './io';\nimport { RateTable } from './types';\nimport { analyze, writeOutputs } from './scan';\n\nconst program = new Command();\n\nconst DEFAULT_INPUT = './aiopt-output/usage.jsonl';\nconst DEFAULT_OUTPUT_DIR = './aiopt-output';\n\nfunction loadRateTable(): RateTable {\n const p = path.join(__dirname, '..', 'rates', 'rate_table.json');\n return JSON.parse(fs.readFileSync(p, 'utf8'));\n}\n\nprogram\n .name('aiopt')\n .description('AI 비용 자동 절감 인프라 — 서버 없는 로컬 CLI MVP')\n // keep CLI version in sync with package.json\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n .version(require('../package.json').version);\n\nprogram\n .command('init')\n .description('aiopt-input/ 및 샘플 usage.jsonl, aiopt-output/ 생성')\n .action(() => {\n ensureDir('./aiopt-input');\n ensureDir('./aiopt-output');\n\n const sampleSrc = path.join(__dirname, '..', 'samples', 'sample_usage.jsonl');\n const dst = path.join('./aiopt-input', 'usage.jsonl');\n\n if (!fs.existsSync(dst)) {\n fs.copyFileSync(sampleSrc, dst);\n console.log('Created ./aiopt-input/usage.jsonl (sample)');\n } else {\n console.log('Exists ./aiopt-input/usage.jsonl (skip)');\n }\n\n console.log('Ready: ./aiopt-output/');\n });\n\nprogram\n .command('scan')\n .description('입력 로그(JSONL/CSV)를 분석하고 report.md/report.json + patches까지 생성')\n .option('--input <path>', 'input file path (default: ./aiopt-output/usage.jsonl)', DEFAULT_INPUT)\n .option('--out <dir>', 'output dir (default: ./aiopt-output)', DEFAULT_OUTPUT_DIR)\n .action(async (opts) => {\n const inputPath = String(opts.input);\n const outDir = String(opts.out);\n\n if (!fs.existsSync(inputPath)) {\n console.error(`Input not found: ${inputPath}`);\n process.exit(1);\n }\n\n const rt = loadRateTable();\n const events = isCsvPath(inputPath) ? readCsv(inputPath) : readJsonl(inputPath);\n\n const { analysis, savings, policy, meta } = analyze(rt, events);\n // For reproducibility: embed input path & rate table meta\n policy.generated_from.input = inputPath;\n\n writeOutputs(outDir, analysis, savings, policy, meta);\n\n // Console: Top Fix 3 (data-driven)\n const { buildTopFixes } = await import('./solutions');\n const fixes = buildTopFixes(analysis, savings).slice(0, 3);\n\n console.log('Top Fix 3:');\n fixes.forEach((f, i) => {\n const tag = f.status === 'no-issue' ? '(no issue detected)' : `($${Math.round(f.impact_usd * 100) / 100})`;\n console.log(`${i + 1}) ${f.title} ${tag}`);\n });\n console.log(`Report: ${path.join(outDir, 'report.md')}`);\n });\n\nprogram\n .command('policy')\n .description('마지막 scan 결과 기반으로 cost-policy.json만 재생성 (MVP: scan과 동일 로직)')\n .option('--input <path>', 'input file path (default: ./aiopt-input/usage.jsonl)', DEFAULT_INPUT)\n .option('--out <dir>', 'output dir (default: ./aiopt-output)', DEFAULT_OUTPUT_DIR)\n .action((opts) => {\n const inputPath = String(opts.input);\n const outDir = String(opts.out);\n const rt = loadRateTable();\n const events = isCsvPath(inputPath) ? readCsv(inputPath) : readJsonl(inputPath);\n const { policy } = analyze(rt, events);\n policy.generated_from.input = inputPath;\n\n ensureDir(outDir);\n fs.writeFileSync(path.join(outDir, 'cost-policy.json'), JSON.stringify(policy, null, 2));\n console.log(`OK: ${outDir}/cost-policy.json`);\n });\n\n// v0.2: install/doctor (no servers)\nprogram\n .command('install')\n .description('Install AIOpt guardrails: create aiopt/ + policies + usage.jsonl')\n .option('--force', 'overwrite existing files')\n .option('--seed-sample', 'seed 1 sample line into aiopt-output/usage.jsonl')\n .action(async (opts) => {\n const { runInstall } = await import('./install');\n const result = runInstall(process.cwd(), { force: Boolean(opts.force), seedSample: Boolean(opts.seedSample) });\n for (const c of result.created) {\n console.log(`${c.status === 'created' ? 'CREATED' : 'SKIP'}: ${c.path}`);\n }\n });\n\nprogram\n .command('doctor')\n .description('Check installation + print last 5 usage events')\n .action(async () => {\n const { runDoctor } = await import('./doctor');\n const r = runDoctor(process.cwd());\n console.log(r.ok ? 'OK: doctor' : 'WARN: doctor');\n for (const c of r.checks) {\n console.log(`${c.ok ? 'OK' : 'FAIL'}: ${c.name}${c.detail ? ` (${c.detail})` : ''}`);\n }\n console.log('--- last5 usage');\n for (const x of r.last5) {\n console.log(JSON.stringify(x));\n }\n });\n\n// Offline license (no servers)\nconst licenseCmd = program\n .command('license')\n .description('Offline license activate/verify (public key only; no server calls)');\n\nlicenseCmd\n .command('activate')\n .argument('<KEY>', 'license key (<payloadB64Url>.<sigB64Url>)')\n .option('--out <path>', 'output license.json path (default: ./aiopt/license.json)')\n .action(async (key, opts) => {\n const { DEFAULT_PUBLIC_KEY_PEM, defaultLicensePath, verifyLicenseKey, writeLicenseFile } = await import('./license');\n const outPath = opts.out ? String(opts.out) : defaultLicensePath(process.cwd());\n const pub = process.env.AIOPT_LICENSE_PUBKEY || DEFAULT_PUBLIC_KEY_PEM;\n const v = verifyLicenseKey(String(key), pub);\n if (!v.payload) {\n console.error(`FAIL: ${v.reason || 'invalid license'}`);\n process.exit(3);\n }\n writeLicenseFile(outPath, String(key), v.payload, v.ok);\n console.log(v.ok ? `OK: activated (${outPath})` : `WARN: saved but not verified (${v.reason}) (${outPath})`);\n process.exit(v.ok ? 0 : 2);\n });\n\nlicenseCmd\n .command('verify')\n .option('--path <path>', 'license.json path (default: ./aiopt/license.json)')\n .action(async (opts) => {\n const { DEFAULT_PUBLIC_KEY_PEM, defaultLicensePath, readLicenseFile, verifyLicenseKey } = await import('./license');\n const p = opts.path ? String(opts.path) : defaultLicensePath(process.cwd());\n const pub = process.env.AIOPT_LICENSE_PUBKEY || DEFAULT_PUBLIC_KEY_PEM;\n if (!fs.existsSync(p)) {\n console.error(`FAIL: license file not found: ${p}`);\n process.exit(3);\n }\n const f = readLicenseFile(p);\n const v = verifyLicenseKey(f.key, pub);\n if (v.ok) {\n console.log('OK: license verified');\n process.exit(0);\n }\n console.error(`FAIL: license invalid (${v.reason || 'unknown'})`);\n process.exit(3);\n });\n\nlicenseCmd\n .command('status')\n .option('--path <path>', 'license.json path (default: ./aiopt/license.json)')\n .action(async (opts) => {\n const { DEFAULT_PUBLIC_KEY_PEM, defaultLicensePath, readLicenseFile, verifyLicenseKey } = await import('./license');\n const p = opts.path ? String(opts.path) : defaultLicensePath(process.cwd());\n const pub = process.env.AIOPT_LICENSE_PUBKEY || DEFAULT_PUBLIC_KEY_PEM;\n if (!fs.existsSync(p)) {\n console.log('NO_LICENSE');\n process.exit(2);\n }\n const f = readLicenseFile(p);\n const v = verifyLicenseKey(f.key, pub);\n if (v.ok) {\n console.log(`OK: ${f.payload.plan} exp=${f.payload.exp}`);\n process.exit(0);\n }\n console.log(`INVALID: ${v.reason || 'unknown'}`);\n process.exit(3);\n });\n\n// vNext: guardrail mode (pre-deploy warning)\nprogram\n .command('guard')\n .description('Pre-deploy guardrail: compare baseline usage vs candidate change and print warnings (exit codes 0/2/3)')\n .option('--input <path>', 'baseline usage jsonl/csv (default: ./aiopt-output/usage.jsonl)', DEFAULT_INPUT)\n .option('--provider <provider>', 'candidate provider override')\n .option('--model <model>', 'candidate model override')\n .option('--context-mult <n>', 'multiply input_tokens by n', (v) => Number(v))\n .option('--output-mult <n>', 'multiply output_tokens by n', (v) => Number(v))\n .option('--retries-delta <n>', 'add n to retries', (v) => Number(v))\n .option('--call-mult <n>', 'multiply call volume by n (traffic spike)', (v) => Number(v))\n .action(async (opts) => {\n const rt = loadRateTable();\n const inputPath = String(opts.input);\n if (!fs.existsSync(inputPath)) {\n console.error(`FAIL: baseline not found: ${inputPath}`);\n process.exit(3);\n }\n const events = isCsvPath(inputPath) ? readCsv(inputPath) : readJsonl(inputPath);\n\n const { runGuard } = await import('./guard');\n const r = runGuard(rt, {\n baselineEvents: events,\n candidate: {\n provider: opts.provider,\n model: opts.model,\n contextMultiplier: opts.contextMult,\n outputMultiplier: opts.outputMult,\n retriesDelta: opts.retriesDelta,\n callMultiplier: opts.callMult\n }\n });\n\n console.log(r.message);\n\n // Persist last guard output for local dashboard / CI attachments\n try {\n const outDir = path.resolve(DEFAULT_OUTPUT_DIR);\n fs.mkdirSync(outDir, { recursive: true });\n fs.writeFileSync(path.join(outDir, 'guard-last.txt'), r.message);\n fs.writeFileSync(path.join(outDir, 'guard-last.json'), JSON.stringify({ ts: new Date().toISOString(), exitCode: r.exitCode }, null, 2));\n } catch {\n // ignore\n }\n\n process.exit(r.exitCode);\n });\n\n// Local-only dashboard (no auth; binds to 127.0.0.1)\nprogram\n .command('dashboard')\n .description('Local dashboard (localhost only): view last guard + last scan outputs')\n .option('--port <n>', 'port (default: 3010)', (v) => Number(v), 3010)\n .action(async (opts) => {\n const { startDashboard } = await import('./dashboard');\n await startDashboard(process.cwd(), { port: Number(opts.port || 3010) });\n });\n\nprogram.parse(process.argv);\n","import fs from 'fs';\nimport path from 'path';\nimport { parse as parseCsv } from 'csv-parse/sync';\nimport { UsageEvent } from './types';\n\nexport function ensureDir(p: string) {\n fs.mkdirSync(p, { recursive: true });\n}\n\nexport function readJsonl(filePath: string): UsageEvent[] {\n const raw = fs.readFileSync(filePath, 'utf8');\n const lines = raw.split(/\\r?\\n/).filter(l => l.trim().length > 0);\n const out: UsageEvent[] = [];\n for (const line of lines) {\n const obj = JSON.parse(line);\n out.push(normalizeEvent(obj));\n }\n return out;\n}\n\nexport function readCsv(filePath: string): UsageEvent[] {\n const raw = fs.readFileSync(filePath, 'utf8');\n const records = parseCsv(raw, { columns: true, skip_empty_lines: true, trim: true });\n return records.map((r: any) => normalizeEvent(r));\n}\n\nfunction toNum(x: any, def = 0): number {\n const n = Number(x);\n return Number.isFinite(n) ? n : def;\n}\n\nfunction normalizeEvent(x: any): UsageEvent {\n // Supports two schemas:\n // 1) scan input schema: input_tokens/output_tokens/feature_tag/retries\n // 2) wrapper usage schema: prompt_tokens/completion_tokens/endpoint/attempt/trace_id/cost_usd\n\n const inputTokens = x.input_tokens ?? x.prompt_tokens;\n const outputTokens = x.output_tokens ?? x.completion_tokens;\n\n // feature_tag fallback: feature_tag -> meta.feature_tag -> endpoint\n const featureTag = x.feature_tag ?? x?.meta?.feature_tag ?? x.endpoint ?? '';\n\n // retries fallback: retries -> max(attempt-1,0)\n const retries = x.retries ?? (x.attempt !== undefined ? Math.max(0, toNum(x.attempt) - 1) : 0);\n\n // billed_cost fallback: billed_cost -> cost_usd\n const billed = x.billed_cost ?? x.cost_usd;\n\n return {\n ts: String(x.ts ?? ''),\n provider: String(x.provider ?? '').toLowerCase(),\n model: String(x.model ?? ''),\n input_tokens: toNum(inputTokens),\n output_tokens: toNum(outputTokens),\n feature_tag: String(featureTag ?? ''),\n retries: toNum(retries),\n status: String(x.status ?? ''),\n billed_cost: billed === undefined || billed === '' ? undefined : toNum(billed),\n\n trace_id: x.trace_id ? String(x.trace_id) : undefined,\n request_id: x.request_id ? String(x.request_id) : undefined,\n attempt: x.attempt === undefined ? undefined : toNum(x.attempt),\n endpoint: x.endpoint ? String(x.endpoint) : undefined\n };\n}\n\nexport function isCsvPath(p: string) {\n return path.extname(p).toLowerCase() === '.csv';\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaO,SAAS,SAAS,IAAe,UAAkB,OAAe;AACvE,QAAM,OAAO,OAAO,YAAY,EAAE,EAAE,YAAY;AAGhD,MAAI,SAAS,WAAW,SAAS,YAAY,SAAS,QAAQ;AAC5D,WAAO,EAAE,MAAM,YAAqB,OAAO,GAAG,QAAQ,EAAE;AAAA,EAC1D;AAEA,QAAM,IAAI,GAAG,UAAU,IAAI;AAC3B,MAAI,CAAC,EAAG,QAAO;AACf,QAAM,IAAI,EAAE,OAAO,KAAK;AACxB,MAAI,EAAG,QAAO,EAAE,MAAM,YAAqB,O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Q,WAAW,EACnB,YAAY,uEAAuE,EACnF,OAAO,cAAc,wBAAwB,CAAC,MAAM,OAAO,CAAC,GAAG,IAAI,EACnE,OAAO,OAAO,SAAS;AACtB,QAAM,EAAE,gBAAAW,gBAAe,IAAI,MAAM;AACjC,QAAMA,gBAAe,QAAQ,IAAI,GAAG,EAAE,MAAM,OAAO,KAAK,QAAQ,IAAI,EAAE,CAAC;AACzE,CAAC;AAEH,QAAQ,MAAM,QAAQ,IAAI;","names":["cost","path","fs","import_fs","import_path","round2","fs","path","import_fs","import_path","exports","module","ensureDir","fs","path","import_fs","import_path","fs","path","import_fs","import_path","crypto","path","fs","import_fs","import_path","round2","conf","msg","path","fs","http","import_fs","import_path","import_fs","import_path","fs","parseCsv","path","path","fs","buildTopFixes","runInstall","runDoctor","DEFAULT_PUBLIC_KEY_PEM","defaultLicensePath","verifyLicenseKey","writeLicenseFile","readLicenseFile","runGuard","startDashboard"]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aiopt",
|
|
3
|
-
"version": "0.2.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.2.6",
|
|
4
|
+
"description": "Pre-deploy LLM cost accident guardrail (serverless local CLI)",
|
|
5
5
|
"bin": {
|
|
6
6
|
"aiopt": "dist/cli.js"
|
|
7
7
|
},
|
|
@@ -19,7 +19,8 @@
|
|
|
19
19
|
"prepack": "npm run build",
|
|
20
20
|
"test:npx": "npm pack --silent && node -e \"const fs=require('fs');const p=fs.readdirSync('.').find(f=>/^aiopt-.*\\.tgz$/.test(f)); if(!p) throw new Error('tgz not found'); console.log('tgz',p);\" && npx --yes ./$(ls -1 aiopt-*.tgz | tail -n 1) install --force && npx --yes ./$(ls -1 aiopt-*.tgz | tail -n 1) doctor && npx --yes ./$(ls -1 aiopt-*.tgz | tail -n 1) scan && test -f ./aiopt-output/report.md && echo OK",
|
|
21
21
|
"test:guard": "npm run build --silent && node scripts/test-guard.js",
|
|
22
|
-
"test:license": "npm run build --silent && node scripts/test-license.js"
|
|
22
|
+
"test:license": "npm run build --silent && node scripts/test-license.js",
|
|
23
|
+
"test:landing": "node scripts/test-landing.js"
|
|
23
24
|
},
|
|
24
25
|
"dependencies": {
|
|
25
26
|
"commander": "^14.0.0",
|