omnicell-router 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (212) hide show
  1. package/RELEASING.md +238 -238
  2. package/RELEASING.zh-CN.md +230 -230
  3. package/backend/dist/capture/recorder.js +2 -1
  4. package/backend/dist/cli/clients/base.js +8 -16
  5. package/backend/dist/cli/clients/dsh.js +8 -16
  6. package/backend/dist/cli/clients/pi.js +16 -9
  7. package/backend/dist/cli/types.d.ts +5 -0
  8. package/backend/dist/config/env.js +2 -1
  9. package/backend/dist/config/index.js +2 -0
  10. package/backend/dist/config/types.d.ts +23 -0
  11. package/backend/dist/harness/adapters/amp.d.ts +2 -0
  12. package/backend/dist/harness/adapters/amp.js +7 -0
  13. package/backend/dist/harness/adapters/claude.d.ts +2 -0
  14. package/backend/dist/harness/adapters/claude.js +7 -0
  15. package/backend/dist/harness/adapters/cline.d.ts +2 -0
  16. package/backend/dist/harness/adapters/cline.js +6 -0
  17. package/backend/dist/harness/adapters/codex.d.ts +2 -0
  18. package/backend/dist/harness/adapters/codex.js +6 -0
  19. package/backend/dist/harness/adapters/cursor.d.ts +5 -0
  20. package/backend/dist/harness/adapters/cursor.js +10 -0
  21. package/backend/dist/harness/adapters/declarative.d.ts +62 -0
  22. package/backend/dist/harness/adapters/declarative.js +202 -0
  23. package/backend/dist/harness/adapters/dsh.d.ts +5 -0
  24. package/backend/dist/harness/adapters/dsh.js +6 -0
  25. package/backend/dist/harness/adapters/gemini-cli.d.ts +2 -0
  26. package/backend/dist/harness/adapters/gemini-cli.js +7 -0
  27. package/backend/dist/harness/adapters/github-copilot.d.ts +5 -0
  28. package/backend/dist/harness/adapters/github-copilot.js +10 -0
  29. package/backend/dist/harness/adapters/index.d.ts +44 -0
  30. package/backend/dist/harness/adapters/index.js +99 -0
  31. package/backend/dist/harness/adapters/opencode.d.ts +2 -0
  32. package/backend/dist/harness/adapters/opencode.js +55 -0
  33. package/backend/dist/harness/adapters/pi.d.ts +1 -0
  34. package/backend/dist/harness/adapters/pi.js +22 -0
  35. package/backend/dist/harness/adapters/skills-paths.d.ts +15 -0
  36. package/backend/dist/harness/adapters/skills-paths.js +17 -0
  37. package/backend/dist/harness/adapters/types.d.ts +174 -0
  38. package/backend/dist/harness/adapters/types.js +12 -0
  39. package/backend/dist/harness/adapters/universal.d.ts +6 -0
  40. package/backend/dist/harness/adapters/universal.js +10 -0
  41. package/backend/dist/harness/adapters/windsurf.d.ts +2 -0
  42. package/backend/dist/harness/adapters/windsurf.js +10 -0
  43. package/backend/dist/harness/adapters/zed.d.ts +2 -0
  44. package/backend/dist/harness/adapters/zed.js +6 -0
  45. package/backend/dist/harness/awesome-opencode.d.ts +40 -0
  46. package/backend/dist/harness/awesome-opencode.js +75 -0
  47. package/backend/dist/harness/browse.d.ts +202 -0
  48. package/backend/dist/harness/browse.js +1214 -0
  49. package/backend/dist/harness/catalog-npm.d.ts +59 -0
  50. package/backend/dist/harness/catalog-npm.js +145 -0
  51. package/backend/dist/harness/clawhub.d.ts +212 -0
  52. package/backend/dist/harness/clawhub.js +426 -0
  53. package/backend/dist/harness/config-file.d.ts +29 -0
  54. package/backend/dist/harness/config-file.js +35 -0
  55. package/backend/dist/harness/detail.d.ts +74 -0
  56. package/backend/dist/harness/detail.js +330 -0
  57. package/backend/dist/harness/discover.d.ts +118 -0
  58. package/backend/dist/harness/discover.js +507 -0
  59. package/backend/dist/harness/drift.d.ts +21 -0
  60. package/backend/dist/harness/drift.js +25 -0
  61. package/backend/dist/harness/hash.d.ts +10 -0
  62. package/backend/dist/harness/hash.js +63 -0
  63. package/backend/dist/harness/hosts.d.ts +18 -0
  64. package/backend/dist/harness/hosts.js +15 -0
  65. package/backend/dist/harness/install.d.ts +88 -0
  66. package/backend/dist/harness/install.js +301 -0
  67. package/backend/dist/harness/inventory.d.ts +10 -0
  68. package/backend/dist/harness/inventory.js +198 -0
  69. package/backend/dist/harness/ledger.d.ts +39 -0
  70. package/backend/dist/harness/ledger.js +83 -0
  71. package/backend/dist/harness/maintenance.d.ts +115 -0
  72. package/backend/dist/harness/maintenance.js +603 -0
  73. package/backend/dist/harness/manifest.d.ts +31 -0
  74. package/backend/dist/harness/manifest.js +234 -0
  75. package/backend/dist/harness/net.d.ts +86 -0
  76. package/backend/dist/harness/net.js +113 -0
  77. package/backend/dist/harness/opencode-cafe.d.ts +40 -0
  78. package/backend/dist/harness/opencode-cafe.js +85 -0
  79. package/backend/dist/harness/opencode-ecosystem.d.ts +34 -0
  80. package/backend/dist/harness/opencode-ecosystem.js +246 -0
  81. package/backend/dist/harness/pi-dev.d.ts +81 -0
  82. package/backend/dist/harness/pi-dev.js +187 -0
  83. package/backend/dist/harness/probe.d.ts +33 -0
  84. package/backend/dist/harness/probe.js +85 -0
  85. package/backend/dist/harness/registry.d.ts +2 -0
  86. package/backend/dist/harness/registry.js +26 -0
  87. package/backend/dist/harness/scopes.d.ts +21 -0
  88. package/backend/dist/harness/scopes.js +22 -0
  89. package/backend/dist/harness/skill-md.d.ts +18 -0
  90. package/backend/dist/harness/skill-md.js +71 -0
  91. package/backend/dist/harness/skills-sh.d.ts +109 -0
  92. package/backend/dist/harness/skills-sh.js +178 -0
  93. package/backend/dist/harness/smithery.d.ts +64 -0
  94. package/backend/dist/harness/smithery.js +146 -0
  95. package/backend/dist/harness/sources/awesome-opencode.d.ts +11 -0
  96. package/backend/dist/harness/sources/awesome-opencode.js +39 -0
  97. package/backend/dist/harness/sources/clawhub.d.ts +2 -0
  98. package/backend/dist/harness/sources/clawhub.js +83 -0
  99. package/backend/dist/harness/sources/github.d.ts +9 -0
  100. package/backend/dist/harness/sources/github.js +202 -0
  101. package/backend/dist/harness/sources/mcp-official.d.ts +2 -0
  102. package/backend/dist/harness/sources/mcp-official.js +110 -0
  103. package/backend/dist/harness/sources/npm.d.ts +2 -0
  104. package/backend/dist/harness/sources/npm.js +152 -0
  105. package/backend/dist/harness/sources/opencode-cafe.d.ts +11 -0
  106. package/backend/dist/harness/sources/opencode-cafe.js +41 -0
  107. package/backend/dist/harness/sources/smithery.d.ts +2 -0
  108. package/backend/dist/harness/sources/smithery.js +81 -0
  109. package/backend/dist/harness/spi.d.ts +98 -0
  110. package/backend/dist/harness/spi.js +8 -0
  111. package/backend/dist/harness/stars.d.ts +70 -0
  112. package/backend/dist/harness/stars.js +202 -0
  113. package/backend/dist/harness/translation.d.ts +142 -0
  114. package/backend/dist/harness/translation.js +567 -0
  115. package/backend/dist/harness/tree.d.ts +13 -0
  116. package/backend/dist/harness/tree.js +19 -0
  117. package/backend/dist/harness/types.d.ts +286 -0
  118. package/backend/dist/harness/types.js +8 -0
  119. package/backend/dist/harness/writers/extension.d.ts +116 -0
  120. package/backend/dist/harness/writers/extension.js +219 -0
  121. package/backend/dist/harness/writers/mcp.d.ts +72 -0
  122. package/backend/dist/harness/writers/mcp.js +195 -0
  123. package/backend/dist/harness/writers/skill.d.ts +60 -0
  124. package/backend/dist/harness/writers/skill.js +146 -0
  125. package/backend/dist/opencode/agents.d.ts +5 -0
  126. package/backend/dist/opencode/agents.js +10 -1
  127. package/backend/dist/opencode/catalog/cache.js +2 -1
  128. package/backend/dist/opencode/catalog/logos.js +2 -1
  129. package/backend/dist/opencode/catalog/ocr-store.js +2 -1
  130. package/backend/dist/opencode/catalog/overrides-store.js +2 -1
  131. package/backend/dist/opencode/credentials/factory.js +10 -27
  132. package/backend/dist/opencode/credentials/ocr-store.js +2 -1
  133. package/backend/dist/opencode/provider-defs.js +2 -1
  134. package/backend/dist/opencode/user-config.js +8 -16
  135. package/backend/dist/providers/registry.d.ts +15 -4
  136. package/backend/dist/providers/registry.js +29 -5
  137. package/backend/dist/providers/virtual-meta.d.ts +13 -0
  138. package/backend/dist/providers/virtual-meta.js +18 -0
  139. package/backend/dist/quota/store.js +2 -1
  140. package/backend/dist/resilience/breaker-state.js +2 -1
  141. package/backend/dist/resilience/credential-state.js +2 -1
  142. package/backend/dist/routes/console.js +137 -15
  143. package/backend/dist/routes/harness.d.ts +2 -0
  144. package/backend/dist/routes/harness.js +622 -0
  145. package/backend/dist/server.js +4 -0
  146. package/backend/dist/session/session-manager.js +2 -1
  147. package/backend/dist/surfaces/systemone-probe.d.ts +25 -0
  148. package/backend/dist/surfaces/systemone-probe.js +74 -0
  149. package/backend/dist/utils/atomic-write.d.ts +12 -0
  150. package/backend/dist/utils/atomic-write.js +29 -0
  151. package/bin/ocr.js +2 -2
  152. package/frontend/dist/assets/{index-DEo2iAT7.css → index-1o7qI-KJ.css} +1 -1
  153. package/frontend/dist/assets/index-DvXKvNxl.js +962 -0
  154. package/frontend/dist/index.html +2 -2
  155. package/package.json +87 -87
  156. package/backend/dist/budget/budget-manager.d.ts +0 -25
  157. package/backend/dist/budget/budget-manager.js +0 -54
  158. package/backend/dist/config/governance-limits.d.ts +0 -68
  159. package/backend/dist/config/governance-limits.js +0 -261
  160. package/backend/dist/flywheel/collector.d.ts +0 -74
  161. package/backend/dist/flywheel/collector.js +0 -235
  162. package/backend/dist/flywheel/dataset.d.ts +0 -130
  163. package/backend/dist/flywheel/dataset.js +0 -638
  164. package/backend/dist/flywheel/decision-capture.d.ts +0 -68
  165. package/backend/dist/flywheel/decision-capture.js +0 -85
  166. package/backend/dist/flywheel/prune.d.ts +0 -133
  167. package/backend/dist/flywheel/prune.js +0 -495
  168. package/backend/dist/flywheel/schema.d.ts +0 -108
  169. package/backend/dist/flywheel/schema.js +0 -117
  170. package/backend/dist/flywheel/trainer.d.ts +0 -84
  171. package/backend/dist/flywheel/trainer.js +0 -198
  172. package/backend/dist/opencode/catalog/custom-store.d.ts +0 -50
  173. package/backend/dist/opencode/catalog/custom-store.js +0 -144
  174. package/backend/dist/opencode/credentials/push.d.ts +0 -38
  175. package/backend/dist/opencode/credentials/push.js +0 -116
  176. package/backend/dist/opencode/credentials/reconcile.d.ts +0 -49
  177. package/backend/dist/opencode/credentials/reconcile.js +0 -216
  178. package/backend/dist/opencode/sync.d.ts +0 -29
  179. package/backend/dist/opencode/sync.js +0 -186
  180. package/backend/dist/pipeline/account-selection.d.ts +0 -101
  181. package/backend/dist/pipeline/account-selection.js +0 -112
  182. package/backend/dist/providers/systemone.d.ts +0 -29
  183. package/backend/dist/providers/systemone.js +0 -170
  184. package/backend/dist/ratelimit/duration.d.ts +0 -24
  185. package/backend/dist/ratelimit/duration.js +0 -43
  186. package/backend/dist/ratelimit/governance-runtime.d.ts +0 -121
  187. package/backend/dist/ratelimit/governance-runtime.js +0 -183
  188. package/backend/dist/ratelimit/index.d.ts +0 -4
  189. package/backend/dist/ratelimit/index.js +0 -4
  190. package/backend/dist/ratelimit/limiter.d.ts +0 -157
  191. package/backend/dist/ratelimit/limiter.js +0 -244
  192. package/backend/dist/ratelimit/sliding-window-counter.d.ts +0 -63
  193. package/backend/dist/ratelimit/sliding-window-counter.js +0 -103
  194. package/backend/dist/ratelimit/subject.d.ts +0 -26
  195. package/backend/dist/ratelimit/subject.js +0 -28
  196. package/backend/dist/resilience/account-state.d.ts +0 -84
  197. package/backend/dist/resilience/account-state.js +0 -228
  198. package/backend/dist/router/layer1-classifier.d.ts +0 -111
  199. package/backend/dist/router/layer1-classifier.js +0 -467
  200. package/backend/dist/router/layer2-judge.d.ts +0 -111
  201. package/backend/dist/router/layer2-judge.js +0 -373
  202. package/backend/dist/router/retry-escalation.d.ts +0 -89
  203. package/backend/dist/router/retry-escalation.js +0 -99
  204. package/backend/dist/routes/flywheel.d.ts +0 -3
  205. package/backend/dist/routes/flywheel.js +0 -268
  206. package/backend/dist/routes/systemone.d.ts +0 -3
  207. package/backend/dist/routes/systemone.js +0 -90
  208. package/backend/dist/surfaces/governance-envelope.d.ts +0 -34
  209. package/backend/dist/surfaces/governance-envelope.js +0 -47
  210. package/backend/dist/utils/token-estimator.d.ts +0 -7
  211. package/backend/dist/utils/token-estimator.js +0 -20
  212. package/frontend/dist/assets/index-nwgWkmU1.js +0 -840
@@ -5,8 +5,8 @@
5
5
  <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'><path d='M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z'/></svg>" />
6
6
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
7
  <title>OmniCellRouter (OCR) - Gateway Console</title>
8
- <script type="module" crossorigin src="/admin/assets/index-nwgWkmU1.js"></script>
9
- <link rel="stylesheet" crossorigin href="/admin/assets/index-DEo2iAT7.css">
8
+ <script type="module" crossorigin src="/admin/assets/index-DvXKvNxl.js"></script>
9
+ <link rel="stylesheet" crossorigin href="/admin/assets/index-1o7qI-KJ.css">
10
10
  </head>
11
11
  <body>
12
12
  <div id="root"></div>
package/package.json CHANGED
@@ -1,87 +1,87 @@
1
- {
2
- "name": "omnicell-router",
3
- "version": "0.1.0",
4
- "description": "High-performance OmniCellRouter (OCR) & Cascading Gateway",
5
- "publishConfig": {
6
- "access": "public"
7
- },
8
- "type": "module",
9
- "engines": {
10
- "node": ">=18.0.0"
11
- },
12
- "files": [
13
- "bin",
14
- "backend/dist",
15
- "frontend/dist",
16
- "README.md",
17
- "README.zh-CN.md",
18
- "RELEASING.md",
19
- "RELEASING.zh-CN.md",
20
- "LICENSE"
21
- ],
22
- "workspaces": [
23
- "backend",
24
- "frontend"
25
- ],
26
- "scripts": {
27
- "ocr": "bun --no-env-file backend/src/cli/index.ts",
28
- "version": "bun --no-env-file scripts/version-sync.ts",
29
- "setup": "bun install && bun run build",
30
- "dev": "bun --no-env-file scripts/dev.ts",
31
- "dev:backend": "bun --filter @omnicell-router/backend dev",
32
- "dev:frontend": "bun --filter @omnicell-router/frontend dev",
33
- "build": "tsc -p backend && vite build frontend",
34
- "build:backend": "tsc -p backend",
35
- "build:frontend": "vite build frontend",
36
- "build:sidecar": "cd desktop && bun run sidecar",
37
- "build:desktop": "bun run build && bun run build:sidecar && cd desktop && bun run build",
38
- "start": "node backend/dist/index.js",
39
- "start:bun": "bun --no-env-file backend/src/index.ts",
40
- "test": "bun --no-env-file scripts/test-isolated.ts",
41
- "check:matrix": "bun --no-env-file scripts/check-guardrails-matrix.ts",
42
- "test:node": "tsx --test backend/tests/**/*.test.ts",
43
- "test:system": "bun --no-env-file scripts/full-system-test.ts",
44
- "typecheck": "tsc -p backend --noEmit && tsc -p frontend --noEmit",
45
- "prepublishOnly": "bun run build"
46
- },
47
- "keywords": [
48
- "llm",
49
- "router",
50
- "finops",
51
- "cascading",
52
- "openai-proxy",
53
- "semantic-cache",
54
- "deepseek",
55
- "anthropic"
56
- ],
57
- "author": "Ken Lin",
58
- "license": "MIT",
59
- "repository": {
60
- "type": "git",
61
- "url": "git+https://github.com/kenlin8827/omnicell-router.git"
62
- },
63
- "bugs": {
64
- "url": "https://github.com/kenlin8827/omnicell-router/issues"
65
- },
66
- "homepage": "https://github.com/kenlin8827/omnicell-router#readme",
67
- "dependencies": {
68
- "@fastify/cors": "^11.0.0",
69
- "@zip.js/zip.js": "^2.23.0",
70
- "fastify": "^5.2.1",
71
- "fflate": "^0.8.3",
72
- "jsonc-parser": "^3.3.1",
73
- "node-forge": "^1.4.0",
74
- "yaml": "^2.7.0",
75
- "zod": "^3.24.2",
76
- "zod-to-json-schema": "^3.24.3"
77
- },
78
- "devDependencies": {
79
- "@types/node": "^22.13.9",
80
- "tsx": "^4.19.3",
81
- "typescript": "^5.7.3"
82
- },
83
- "bin": {
84
- "ocr": "./bin/ocr.js",
85
- "omnicell-router": "./bin/ocr.js"
86
- }
87
- }
1
+ {
2
+ "name": "omnicell-router",
3
+ "version": "0.2.0",
4
+ "description": "High-performance OmniCellRouter (OCR) & Cascading Gateway",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "type": "module",
9
+ "engines": {
10
+ "node": ">=18.0.0"
11
+ },
12
+ "files": [
13
+ "bin",
14
+ "backend/dist",
15
+ "frontend/dist",
16
+ "README.md",
17
+ "README.zh-CN.md",
18
+ "RELEASING.md",
19
+ "RELEASING.zh-CN.md",
20
+ "LICENSE"
21
+ ],
22
+ "workspaces": [
23
+ "backend",
24
+ "frontend"
25
+ ],
26
+ "scripts": {
27
+ "ocr": "bun --no-env-file backend/src/cli/index.ts",
28
+ "version": "bun --no-env-file scripts/version-sync.ts",
29
+ "setup": "bun install && bun run build",
30
+ "dev": "PORT=3000 bun --no-env-file scripts/dev.ts",
31
+ "dev:backend": "bun --filter @omnicell-router/backend dev",
32
+ "dev:frontend": "bun --filter @omnicell-router/frontend dev",
33
+ "build": "tsc -p backend && vite build frontend",
34
+ "build:backend": "tsc -p backend",
35
+ "build:frontend": "vite build frontend",
36
+ "build:sidecar": "cd desktop && bun run sidecar",
37
+ "build:desktop": "bun run build && bun run build:sidecar && cd desktop && bun run build",
38
+ "start": "node backend/dist/index.js",
39
+ "start:bun": "bun --no-env-file backend/src/index.ts",
40
+ "test": "bun --no-env-file scripts/test-isolated.ts",
41
+ "check:matrix": "bun --no-env-file scripts/check-guardrails-matrix.ts",
42
+ "test:node": "tsx --test backend/tests/**/*.test.ts",
43
+ "test:system": "bun --no-env-file scripts/full-system-test.ts",
44
+ "typecheck": "tsc -p backend --noEmit && tsc -p frontend --noEmit",
45
+ "prepublishOnly": "bun run build"
46
+ },
47
+ "keywords": [
48
+ "llm",
49
+ "router",
50
+ "finops",
51
+ "cascading",
52
+ "openai-proxy",
53
+ "semantic-cache",
54
+ "deepseek",
55
+ "anthropic"
56
+ ],
57
+ "author": "Ken Lin",
58
+ "license": "MIT",
59
+ "repository": {
60
+ "type": "git",
61
+ "url": "git+https://github.com/kenlin8827/omnicell-router.git"
62
+ },
63
+ "bugs": {
64
+ "url": "https://github.com/kenlin8827/omnicell-router/issues"
65
+ },
66
+ "homepage": "https://github.com/kenlin8827/omnicell-router#readme",
67
+ "dependencies": {
68
+ "@fastify/cors": "^11.0.0",
69
+ "@zip.js/zip.js": "^2.23.0",
70
+ "fastify": "^5.2.1",
71
+ "fflate": "^0.8.3",
72
+ "jsonc-parser": "^3.3.1",
73
+ "node-forge": "^1.4.0",
74
+ "yaml": "^2.7.0",
75
+ "zod": "^3.24.2",
76
+ "zod-to-json-schema": "^3.24.3"
77
+ },
78
+ "devDependencies": {
79
+ "@types/node": "^22.13.9",
80
+ "tsx": "^4.19.3",
81
+ "typescript": "^5.7.3"
82
+ },
83
+ "bin": {
84
+ "ocr": "./bin/ocr.js",
85
+ "omnicell-router": "./bin/ocr.js"
86
+ }
87
+ }
@@ -1,25 +0,0 @@
1
- import { Usage } from '../types/openai.js';
2
- import { ModelPricing } from '../types/router.js';
3
- /**
4
- * FinOps cost accounting only — the budget/limit enforcement mechanism
5
- * (reasoning-effort clamping + max_completion_tokens cap) was removed;
6
- * cost math is kept because savings/trace stats still depend on it.
7
- */
8
- export declare class BudgetManager {
9
- /**
10
- * Calculate exact cost in USD for a given usage and model pricing.
11
- *
12
- * Reasoning tokens are billed at `pricing.reasoning` when the catalog
13
- * declares it (preferred for models with separate thinking surcharge
14
- * like OpenAI o-series / Anthropic extended-thinking). Otherwise they
15
- * roll into `pricing.output` at the same rate — most models bill
16
- * thinking tokens as plain output, so this is the natural baseline and
17
- * a higher effort level simply produces more tokens, which costs more
18
- * without any per-token multiplier gymnastics.
19
- */
20
- static calculateCost(usage: Usage | undefined, pricing: ModelPricing): number;
21
- /**
22
- * Calculate baseline cost if this request was sent to a standard plus-tier model (e.g. Claude 3.5 Sonnet).
23
- */
24
- static calculateBaselineCost(usage: Usage | undefined, baselinePricing: ModelPricing): number;
25
- }
@@ -1,54 +0,0 @@
1
- /**
2
- * FinOps cost accounting only — the budget/limit enforcement mechanism
3
- * (reasoning-effort clamping + max_completion_tokens cap) was removed;
4
- * cost math is kept because savings/trace stats still depend on it.
5
- */
6
- export class BudgetManager {
7
- /**
8
- * Calculate exact cost in USD for a given usage and model pricing.
9
- *
10
- * Reasoning tokens are billed at `pricing.reasoning` when the catalog
11
- * declares it (preferred for models with separate thinking surcharge
12
- * like OpenAI o-series / Anthropic extended-thinking). Otherwise they
13
- * roll into `pricing.output` at the same rate — most models bill
14
- * thinking tokens as plain output, so this is the natural baseline and
15
- * a higher effort level simply produces more tokens, which costs more
16
- * without any per-token multiplier gymnastics.
17
- */
18
- static calculateCost(usage, pricing) {
19
- if (!usage)
20
- return 0;
21
- const cachedPromptTokens = usage.prompt_tokens_details?.cached_tokens || 0;
22
- const uncachedPromptTokens = Math.max(0, usage.prompt_tokens - cachedPromptTokens);
23
- const completionTokens = usage.completion_tokens || 0;
24
- const reasoningTokens = usage.completion_tokens_details?.reasoning_tokens || 0;
25
- const promptCost = (uncachedPromptTokens / 1_000_000) * pricing.input;
26
- const cachedPromptCost = (cachedPromptTokens / 1_000_000) * pricing.cacheRead;
27
- let completionCost;
28
- if (pricing.reasoning && reasoningTokens > 0) {
29
- // Catalog declares a dedicated reasoning price — charge reasoning
30
- // tokens at that rate and the visible output at the normal rate.
31
- const normalCompletionTokens = Math.max(0, completionTokens - reasoningTokens);
32
- completionCost =
33
- (normalCompletionTokens / 1_000_000) * pricing.output +
34
- (reasoningTokens / 1_000_000) * pricing.reasoning;
35
- }
36
- else {
37
- // No dedicated reasoning price → reasoning tokens are billed as
38
- // plain output (the model-default behavior of every upstream we
39
- // route to today). Higher effort simply spends more tokens.
40
- completionCost = (completionTokens / 1_000_000) * pricing.output;
41
- }
42
- return promptCost + cachedPromptCost + completionCost;
43
- }
44
- /**
45
- * Calculate baseline cost if this request was sent to a standard plus-tier model (e.g. Claude 3.5 Sonnet).
46
- */
47
- static calculateBaselineCost(usage, baselinePricing) {
48
- if (!usage)
49
- return 0;
50
- const promptCost = (usage.prompt_tokens / 1_000_000) * baselinePricing.input;
51
- const completionCost = (usage.completion_tokens / 1_000_000) * baselinePricing.output;
52
- return promptCost + completionCost;
53
- }
54
- }
@@ -1,68 +0,0 @@
1
- /**
2
- * Governance-overlay validator + typed accessors (P2b, design §2 / §3a-4 / §5).
3
- *
4
- * Trust boundary: every junk shape gets a LOUD boot error naming the offending
5
- * entry (provider + index + keyHashPrefix, or apiKey id + index) — never a
6
- * silent drop, never a silent repair. The Limiter (P1) stays config-ignorant;
7
- * this module never builds a Limiter instance — it only validates the raw tree
8
- * and hands thin `LimitEntryConfig[]` slices to the P3/P4 wiring.
9
- *
10
- * Rules enforced here (binding design lines):
11
- * - window: parseWindow must accept (30s / 5m / 1h / 1d — lowercase integer
12
- * duration strings; "5", "1x", "", "1M", "0s", numbers rejected).
13
- * - window span upper bound: parsed length <= 31 days — governance windows
14
- * are shaping windows, not accounting periods (longer horizons hide a
15
- * stale budget behind a counter nobody prunes back).
16
- * - keyHashPrefix: lowercase hex only (/^[0-9a-f]+$/) — the anchor is a
17
- * one-way hash prefix of the credential, never a name or a mixed-case
18
- * digest; all-hex digits stay a STRING at the YAML boundary (the emitter
19
- * quotes number-lookalikes; round-trip pinned in tests).
20
- * - EXACTLY ONE countable per entry (zero or ≥2 → error naming them).
21
- * - countable value: positive finite number (zero/negative/NaN/non-number → error).
22
- * - costUsd is inbound-only (error on `accounts:` entries; allowed on apiKeys).
23
- * - per-subject uniqueness of (window, countable) within one entry list —
24
- * equivalence on the PARSED duration (60s and 1m collide), which is what
25
- * makes limiter rule ids unique addresses (design §5).
26
- * - duplicate keyHashPrefix within the same provider → error.
27
- * - shape guards: non-array list, non-object entry, unknown keys → error.
28
- * - provider ids are NOT checked against the live registry here — unknown
29
- * provider + stale-prefix anchors are P3 boot/pool-rebuild checks against
30
- * resolveKeyChain.
31
- *
32
- * Degeneracy promise: absent `accounts:` / absent per-key `limits` → zero
33
- * issues, zero state, byte-identical request paths.
34
- */
35
- import { type LimitEntryConfig } from '../ratelimit/index.js';
36
- import type { RouterConfig } from './types.js';
37
- /** One structured validation failure: where it lives + what is wrong. */
38
- export type GovernanceValidationIssue = {
39
- /** Offending entry locator, e.g. accounts.anthropic[0] (keyHashPrefix "ab12…") limits[1] */
40
- location: string;
41
- problem: string;
42
- };
43
- /** Loud boot error carrying every issue — loadConfig throws it, saveConfig surfaces it. */
44
- export declare class GovernanceConfigError extends Error {
45
- readonly issues: GovernanceValidationIssue[];
46
- constructor(issues: GovernanceValidationIssue[]);
47
- }
48
- export declare function formatGovernanceIssues(issues: GovernanceValidationIssue[]): string;
49
- /**
50
- * Validate the governance tree + per-apiKey limits. Both arguments are RAW
51
- * YAML-derived (any shape allowed — every guard below is a trust-boundary
52
- * guard). Returns [] when nothing is configured: absent `accounts` and absent
53
- * per-key `limits` never produce issues (degeneracy).
54
- */
55
- export declare function validateGovernanceLimits(accounts: unknown, apiKeys: unknown): GovernanceValidationIssue[];
56
- /**
57
- * Limits governing one account subject — the thin accessor P3 wiring feeds to
58
- * `Limiter.setRules(accountSubject(provider, prefix), rules)`. undefined =
59
- * unconfigured (no cap, no state: never build a Limiter rule from it).
60
- * Returns the live config array — callers MUST treat it as read-only.
61
- */
62
- export declare function limitsForAccountSubject(config: Pick<RouterConfig, 'accounts'>, provider: string, keyHashPrefix: string): LimitEntryConfig[] | undefined;
63
- /**
64
- * Limits governing one inbound client key — the P4 auth-middleware counterpart
65
- * (`Limiter.setRules(apiKeySubject(id), rules)`). undefined = unlimited.
66
- * Returns the live config array — callers MUST treat it as read-only.
67
- */
68
- export declare function limitsForApiKey(config: Pick<RouterConfig, 'apiKeys'>, id: string): LimitEntryConfig[] | undefined;
@@ -1,261 +0,0 @@
1
- /**
2
- * Governance-overlay validator + typed accessors (P2b, design §2 / §3a-4 / §5).
3
- *
4
- * Trust boundary: every junk shape gets a LOUD boot error naming the offending
5
- * entry (provider + index + keyHashPrefix, or apiKey id + index) — never a
6
- * silent drop, never a silent repair. The Limiter (P1) stays config-ignorant;
7
- * this module never builds a Limiter instance — it only validates the raw tree
8
- * and hands thin `LimitEntryConfig[]` slices to the P3/P4 wiring.
9
- *
10
- * Rules enforced here (binding design lines):
11
- * - window: parseWindow must accept (30s / 5m / 1h / 1d — lowercase integer
12
- * duration strings; "5", "1x", "", "1M", "0s", numbers rejected).
13
- * - window span upper bound: parsed length <= 31 days — governance windows
14
- * are shaping windows, not accounting periods (longer horizons hide a
15
- * stale budget behind a counter nobody prunes back).
16
- * - keyHashPrefix: lowercase hex only (/^[0-9a-f]+$/) — the anchor is a
17
- * one-way hash prefix of the credential, never a name or a mixed-case
18
- * digest; all-hex digits stay a STRING at the YAML boundary (the emitter
19
- * quotes number-lookalikes; round-trip pinned in tests).
20
- * - EXACTLY ONE countable per entry (zero or ≥2 → error naming them).
21
- * - countable value: positive finite number (zero/negative/NaN/non-number → error).
22
- * - costUsd is inbound-only (error on `accounts:` entries; allowed on apiKeys).
23
- * - per-subject uniqueness of (window, countable) within one entry list —
24
- * equivalence on the PARSED duration (60s and 1m collide), which is what
25
- * makes limiter rule ids unique addresses (design §5).
26
- * - duplicate keyHashPrefix within the same provider → error.
27
- * - shape guards: non-array list, non-object entry, unknown keys → error.
28
- * - provider ids are NOT checked against the live registry here — unknown
29
- * provider + stale-prefix anchors are P3 boot/pool-rebuild checks against
30
- * resolveKeyChain.
31
- *
32
- * Degeneracy promise: absent `accounts:` / absent per-key `limits` → zero
33
- * issues, zero state, byte-identical request paths.
34
- */
35
- import { DAY_WINDOW_MS, parseWindow } from '../ratelimit/index.js';
36
- /** Loud boot error carrying every issue — loadConfig throws it, saveConfig surfaces it. */
37
- export class GovernanceConfigError extends Error {
38
- issues;
39
- constructor(issues) {
40
- super(formatGovernanceIssues(issues));
41
- this.name = 'GovernanceConfigError';
42
- this.issues = issues;
43
- }
44
- }
45
- export function formatGovernanceIssues(issues) {
46
- const lines = issues.map((i) => ` - ${i.location}: ${i.problem}`);
47
- return (`[Config] account governance limits validation failed (${issues.length} issue(s)) — ` +
48
- `fix config.yaml, refusing to silently drop or apply:\n${lines.join('\n')}`);
49
- }
50
- const COUNTABLES = ['requests', 'tokens', 'costUsd'];
51
- const LIMIT_ENTRY_KEYS = new Set(['window', ...COUNTABLES]);
52
- const GOVERNANCE_ENTRY_KEYS = new Set(['keyHashPrefix', 'limits']);
53
- /** Upper bound any accepted window may span (31 days — validator-side only; the engine stays syntax-only). */
54
- const MAX_WINDOW_MS = 31 * DAY_WINDOW_MS;
55
- /** The account anchor alphabet: lowercase hex (a sha256-prefix digest — anything else is a name, alias, or typo). */
56
- const KEY_HASH_PREFIX_RE = /^[0-9a-f]+$/;
57
- const isPlainObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
58
- /** Short human rendering of an offending value for error messages. */
59
- function describeValue(v) {
60
- if (v === undefined)
61
- return 'undefined';
62
- if (v === null)
63
- return 'null';
64
- if (Array.isArray(v))
65
- return `array(len ${v.length})`;
66
- if (typeof v === 'string')
67
- return JSON.stringify(v);
68
- if (typeof v === 'number' && Number.isNaN(v))
69
- return 'NaN';
70
- if (typeof v === 'object')
71
- return 'object';
72
- return String(v);
73
- }
74
- const quoteList = (items) => items.map((s) => `"${s}"`).join(', ');
75
- /** Validate one limits array (shared shape, direction decides the costUsd gate). */
76
- function validateLimitsList(limits, listLoc, direction, issues) {
77
- if (!Array.isArray(limits)) {
78
- issues.push({
79
- location: listLoc,
80
- problem: `must be an array of { window, <one countable> } entries, got ${describeValue(limits)}`,
81
- });
82
- return;
83
- }
84
- // parsed-windowMs + countable -> first entry carrying it (equivalence on the
85
- // parsed duration, not the spelling: 60s/requests collides with 1m/requests).
86
- const seen = new Map();
87
- limits.forEach((raw, j) => {
88
- const loc = `${listLoc}[${j}]`;
89
- if (!isPlainObject(raw)) {
90
- issues.push({
91
- location: loc,
92
- problem: `limit entry must be an object { window, one countable }, got ${describeValue(raw)}`,
93
- });
94
- return;
95
- }
96
- const unknownKeys = Object.keys(raw).filter((k) => !LIMIT_ENTRY_KEYS.has(k));
97
- if (unknownKeys.length > 0) {
98
- issues.push({
99
- location: loc,
100
- problem: `unknown key(s) ${quoteList(unknownKeys)} — allowed: window plus exactly one countable ` +
101
- `(${COUNTABLES.join(' / ')})`,
102
- });
103
- }
104
- const window = raw.window;
105
- const windowMs = typeof window === 'string' ? parseWindow(window) : null;
106
- if (windowMs === null) {
107
- issues.push({
108
- location: `${loc} window`,
109
- problem: typeof window === 'string'
110
- ? `invalid window ${JSON.stringify(window)} — expected an integer duration string like 30s / 5m / 1h / 1d (unsigned, uppercase, zero and fractional are rejected)`
111
- : `window must be a duration string like 30s / 5m / 1h / 1d, got ${describeValue(window)}`,
112
- });
113
- }
114
- else if (windowMs > MAX_WINDOW_MS) {
115
- issues.push({
116
- location: `${loc} window`,
117
- problem: `window ${JSON.stringify(window)} exceeds the 31-day upper bound (${MAX_WINDOW_MS / DAY_WINDOW_MS}d) — ` +
118
- 'governance windows are sliding shaping windows, not accounting periods; a longer horizon reads as a budget nobody prunes back',
119
- });
120
- }
121
- const present = COUNTABLES.filter((c) => raw[c] !== undefined);
122
- if (present.length !== 1) {
123
- issues.push({
124
- location: loc,
125
- problem: present.length === 0
126
- ? `must carry exactly one countable (${COUNTABLES.join(' / ')}), got none`
127
- : `co-located countables ${quoteList(present)} — one entry = one window = one countable; split them into separate entries (design §3a item 4)`,
128
- });
129
- return; // value/uniqueness checks below assume the single-countable shape
130
- }
131
- const countable = present[0];
132
- const value = raw[countable];
133
- const valueLoc = `${loc} ${countable}`;
134
- if (direction === 'accounts' && countable === 'costUsd') {
135
- issues.push({
136
- location: valueLoc,
137
- problem: 'costUsd is inbound-only (apiKeys limits) — a budget is a contract with the caller, ' +
138
- 'never a cap on the provider\'s own key (design §2)',
139
- });
140
- }
141
- if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
142
- issues.push({ location: valueLoc, problem: `must be a positive finite number, got ${describeValue(value)}` });
143
- }
144
- if (windowMs === null)
145
- return; // no valid window — nothing to address uniquely
146
- const key = `${windowMs}|${countable}`;
147
- const first = seen.get(key);
148
- if (first !== undefined) {
149
- issues.push({
150
- location: loc,
151
- problem: `duplicate rule "${window}/${countable}" — the same window+countable is already at [${first.at}] ` +
152
- `("${first.window}/${countable}"); (window, countable) must be unique per subject so one verdict ` +
153
- 'names exactly one YAML line (design §5)',
154
- });
155
- }
156
- else {
157
- seen.set(key, { at: j, window: window });
158
- }
159
- });
160
- }
161
- /**
162
- * Validate the governance tree + per-apiKey limits. Both arguments are RAW
163
- * YAML-derived (any shape allowed — every guard below is a trust-boundary
164
- * guard). Returns [] when nothing is configured: absent `accounts` and absent
165
- * per-key `limits` never produce issues (degeneracy).
166
- */
167
- export function validateGovernanceLimits(accounts, apiKeys) {
168
- const issues = [];
169
- if (accounts !== undefined && accounts !== null) {
170
- if (!isPlainObject(accounts)) {
171
- issues.push({
172
- location: 'accounts',
173
- problem: `must be a mapping providerId -> governance entry list, got ${describeValue(accounts)}`,
174
- });
175
- }
176
- else {
177
- for (const [provider, list] of Object.entries(accounts)) {
178
- const loc = `accounts.${provider}`;
179
- if (!Array.isArray(list)) {
180
- issues.push({ location: loc, problem: `must be an array of { keyHashPrefix, limits } entries, got ${describeValue(list)}` });
181
- continue;
182
- }
183
- const firstByPrefix = new Map();
184
- list.forEach((raw, i) => {
185
- if (!isPlainObject(raw)) {
186
- issues.push({
187
- location: `${loc}[${i}]`,
188
- problem: `governance entry must be an object { keyHashPrefix, limits }, got ${describeValue(raw)}`,
189
- });
190
- return;
191
- }
192
- const unknownKeys = Object.keys(raw).filter((k) => !GOVERNANCE_ENTRY_KEYS.has(k));
193
- if (unknownKeys.length > 0) {
194
- issues.push({
195
- location: `${loc}[${i}]`,
196
- problem: `unknown key(s) ${quoteList(unknownKeys)} — allowed: keyHashPrefix, limits ` +
197
- '(the account alias lives in account-state.json meta, not in config)',
198
- });
199
- }
200
- const prefix = raw.keyHashPrefix;
201
- let entryLoc = `${loc}[${i}]`;
202
- if (typeof prefix !== 'string' || prefix.trim() === '') {
203
- issues.push({
204
- location: `${entryLoc} keyHashPrefix`,
205
- problem: `must be a non-empty string anchor, got ${describeValue(prefix)}`,
206
- });
207
- }
208
- else {
209
- if (!KEY_HASH_PREFIX_RE.test(prefix)) {
210
- issues.push({
211
- location: `${loc}[${i}] keyHashPrefix`,
212
- problem: `keyHashPrefix ${JSON.stringify(prefix)} must match /^[0-9a-f]+$/ — the anchor is a lowercase ` +
213
- 'hex prefix of the credential hash, never a name, alias, or mixed-case digest',
214
- });
215
- }
216
- const first = firstByPrefix.get(prefix);
217
- if (first !== undefined) {
218
- issues.push({
219
- location: `${entryLoc} keyHashPrefix`,
220
- problem: `duplicate keyHashPrefix "${prefix}" within provider "${provider}" (first entry at [${first}]) — one governance entry per account anchor`,
221
- });
222
- }
223
- else {
224
- firstByPrefix.set(prefix, i);
225
- }
226
- entryLoc = `${loc}[${i}] (keyHashPrefix "${prefix}")`;
227
- }
228
- validateLimitsList(raw.limits, `${entryLoc} limits`, 'accounts', issues);
229
- });
230
- }
231
- }
232
- }
233
- if (Array.isArray(apiKeys)) {
234
- apiKeys.forEach((raw, i) => {
235
- if (!isPlainObject(raw) || raw.limits === undefined)
236
- return; // absent = unlimited (degeneracy)
237
- const id = typeof raw.id === 'string' && raw.id !== '' ? raw.id : `#${i}`;
238
- validateLimitsList(raw.limits, `apiKeys[${i}] (id "${id}") limits`, 'apiKeys', issues);
239
- });
240
- }
241
- return issues;
242
- }
243
- /**
244
- * Limits governing one account subject — the thin accessor P3 wiring feeds to
245
- * `Limiter.setRules(accountSubject(provider, prefix), rules)`. undefined =
246
- * unconfigured (no cap, no state: never build a Limiter rule from it).
247
- * Returns the live config array — callers MUST treat it as read-only.
248
- */
249
- export function limitsForAccountSubject(config, provider, keyHashPrefix) {
250
- const entry = config.accounts?.[provider]?.find((e) => e.keyHashPrefix === keyHashPrefix);
251
- return entry && entry.limits.length > 0 ? entry.limits : undefined;
252
- }
253
- /**
254
- * Limits governing one inbound client key — the P4 auth-middleware counterpart
255
- * (`Limiter.setRules(apiKeySubject(id), rules)`). undefined = unlimited.
256
- * Returns the live config array — callers MUST treat it as read-only.
257
- */
258
- export function limitsForApiKey(config, id) {
259
- const key = config.apiKeys?.find((k) => k.id === id);
260
- return key?.limits && key.limits.length > 0 ? key.limits : undefined;
261
- }