@mupt-ai/dari-router 0.1.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 (179) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +100 -0
  3. package/dist/anonymous_actions.d.ts +55 -0
  4. package/dist/anonymous_actions.js +277 -0
  5. package/dist/anonymous_actions.js.map +1 -0
  6. package/dist/auto_router.d.ts +10 -0
  7. package/dist/auto_router.js +56 -0
  8. package/dist/auto_router.js.map +1 -0
  9. package/dist/cache_behavior.d.ts +14 -0
  10. package/dist/cache_behavior.js +112 -0
  11. package/dist/cache_behavior.js.map +1 -0
  12. package/dist/cache_scope.d.ts +5 -0
  13. package/dist/cache_scope.js +49 -0
  14. package/dist/cache_scope.js.map +1 -0
  15. package/dist/cache_switch_decision.d.ts +24 -0
  16. package/dist/cache_switch_decision.js +21 -0
  17. package/dist/cache_switch_decision.js.map +1 -0
  18. package/dist/candidate_pruning.d.ts +45 -0
  19. package/dist/candidate_pruning.js +154 -0
  20. package/dist/candidate_pruning.js.map +1 -0
  21. package/dist/candidate_resolution.d.ts +41 -0
  22. package/dist/candidate_resolution.js +111 -0
  23. package/dist/candidate_resolution.js.map +1 -0
  24. package/dist/compatibility.d.ts +22 -0
  25. package/dist/compatibility.js +76 -0
  26. package/dist/compatibility.js.map +1 -0
  27. package/dist/continuation_state.d.ts +36 -0
  28. package/dist/continuation_state.js +249 -0
  29. package/dist/continuation_state.js.map +1 -0
  30. package/dist/cost.d.ts +31 -0
  31. package/dist/cost.js +314 -0
  32. package/dist/cost.js.map +1 -0
  33. package/dist/dari_policy.d.ts +34 -0
  34. package/dist/dari_policy.js +267 -0
  35. package/dist/dari_policy.js.map +1 -0
  36. package/dist/errors.d.ts +7 -0
  37. package/dist/errors.js +14 -0
  38. package/dist/errors.js.map +1 -0
  39. package/dist/fingerprint.d.ts +13 -0
  40. package/dist/fingerprint.js +130 -0
  41. package/dist/fingerprint.js.map +1 -0
  42. package/dist/fixed_turn_cost_config.d.ts +9 -0
  43. package/dist/fixed_turn_cost_config.js +22 -0
  44. package/dist/fixed_turn_cost_config.js.map +1 -0
  45. package/dist/framework_error.d.ts +8 -0
  46. package/dist/framework_error.js +24 -0
  47. package/dist/framework_error.js.map +1 -0
  48. package/dist/framework_lifecycle.d.ts +11 -0
  49. package/dist/framework_lifecycle.js +57 -0
  50. package/dist/framework_lifecycle.js.map +1 -0
  51. package/dist/framework_models.d.ts +3 -0
  52. package/dist/framework_models.js +120 -0
  53. package/dist/framework_models.js.map +1 -0
  54. package/dist/framework_router.d.ts +2 -0
  55. package/dist/framework_router.js +384 -0
  56. package/dist/framework_router.js.map +1 -0
  57. package/dist/framework_streaming.d.ts +26 -0
  58. package/dist/framework_streaming.js +486 -0
  59. package/dist/framework_streaming.js.map +1 -0
  60. package/dist/framework_types.d.ts +272 -0
  61. package/dist/framework_types.js +5 -0
  62. package/dist/framework_types.js.map +1 -0
  63. package/dist/framework_validation.d.ts +7 -0
  64. package/dist/framework_validation.js +169 -0
  65. package/dist/framework_validation.js.map +1 -0
  66. package/dist/index.d.ts +35 -0
  67. package/dist/index.js +38 -0
  68. package/dist/index.js.map +1 -0
  69. package/dist/json.d.ts +10 -0
  70. package/dist/json.js +29 -0
  71. package/dist/json.js.map +1 -0
  72. package/dist/model_ids.d.ts +4 -0
  73. package/dist/model_ids.js +26 -0
  74. package/dist/model_ids.js.map +1 -0
  75. package/dist/pi_context.d.ts +4 -0
  76. package/dist/pi_context.js +206 -0
  77. package/dist/pi_context.js.map +1 -0
  78. package/dist/pi_options.d.ts +3 -0
  79. package/dist/pi_options.js +240 -0
  80. package/dist/pi_options.js.map +1 -0
  81. package/dist/pi_output.d.ts +4 -0
  82. package/dist/pi_output.js +328 -0
  83. package/dist/pi_output.js.map +1 -0
  84. package/dist/pi_reasoning_signature.d.ts +10 -0
  85. package/dist/pi_reasoning_signature.js +33 -0
  86. package/dist/pi_reasoning_signature.js.map +1 -0
  87. package/dist/pi_runtime.d.ts +3 -0
  88. package/dist/pi_runtime.js +155 -0
  89. package/dist/pi_runtime.js.map +1 -0
  90. package/dist/pi_types.d.ts +35 -0
  91. package/dist/pi_types.js +2 -0
  92. package/dist/pi_types.js.map +1 -0
  93. package/dist/portable_reasoning_state.d.ts +7 -0
  94. package/dist/portable_reasoning_state.js +81 -0
  95. package/dist/portable_reasoning_state.js.map +1 -0
  96. package/dist/previous_decision.d.ts +13 -0
  97. package/dist/previous_decision.js +82 -0
  98. package/dist/previous_decision.js.map +1 -0
  99. package/dist/prompts.d.ts +3 -0
  100. package/dist/prompts.js +65 -0
  101. package/dist/prompts.js.map +1 -0
  102. package/dist/protocol_anthropic.d.ts +18 -0
  103. package/dist/protocol_anthropic.js +443 -0
  104. package/dist/protocol_anthropic.js.map +1 -0
  105. package/dist/protocol_openai_chat.d.ts +25 -0
  106. package/dist/protocol_openai_chat.js +503 -0
  107. package/dist/protocol_openai_chat.js.map +1 -0
  108. package/dist/protocol_validation.d.ts +23 -0
  109. package/dist/protocol_validation.js +134 -0
  110. package/dist/protocol_validation.js.map +1 -0
  111. package/dist/route.d.ts +105 -0
  112. package/dist/route.js +226 -0
  113. package/dist/route.js.map +1 -0
  114. package/dist/routing_history.d.ts +7 -0
  115. package/dist/routing_history.js +132 -0
  116. package/dist/routing_history.js.map +1 -0
  117. package/dist/selector_input.d.ts +42 -0
  118. package/dist/selector_input.js +153 -0
  119. package/dist/selector_input.js.map +1 -0
  120. package/dist/selector_parse.d.ts +13 -0
  121. package/dist/selector_parse.js +95 -0
  122. package/dist/selector_parse.js.map +1 -0
  123. package/dist/selector_request.d.ts +26 -0
  124. package/dist/selector_request.js +85 -0
  125. package/dist/selector_request.js.map +1 -0
  126. package/dist/selector_truncation.d.ts +2 -0
  127. package/dist/selector_truncation.js +48 -0
  128. package/dist/selector_truncation.js.map +1 -0
  129. package/dist/selector_wire.d.ts +10 -0
  130. package/dist/selector_wire.js +113 -0
  131. package/dist/selector_wire.js.map +1 -0
  132. package/dist/types.d.ts +152 -0
  133. package/dist/types.js +14 -0
  134. package/dist/types.js.map +1 -0
  135. package/package.json +64 -0
  136. package/src/anonymous_actions.ts +434 -0
  137. package/src/auto_router.ts +95 -0
  138. package/src/cache_behavior.ts +130 -0
  139. package/src/cache_scope.ts +58 -0
  140. package/src/cache_switch_decision.ts +53 -0
  141. package/src/candidate_pruning.ts +257 -0
  142. package/src/candidate_resolution.ts +208 -0
  143. package/src/compatibility.ts +162 -0
  144. package/src/continuation_state.ts +368 -0
  145. package/src/cost.ts +455 -0
  146. package/src/dari_policy.ts +360 -0
  147. package/src/errors.ts +27 -0
  148. package/src/fingerprint.ts +148 -0
  149. package/src/fixed_turn_cost_config.ts +24 -0
  150. package/src/framework_error.ts +38 -0
  151. package/src/framework_lifecycle.ts +74 -0
  152. package/src/framework_models.ts +186 -0
  153. package/src/framework_router.ts +490 -0
  154. package/src/framework_streaming.ts +613 -0
  155. package/src/framework_types.ts +372 -0
  156. package/src/framework_validation.ts +235 -0
  157. package/src/index.ts +37 -0
  158. package/src/json.ts +43 -0
  159. package/src/model_ids.ts +29 -0
  160. package/src/pi_context.ts +251 -0
  161. package/src/pi_options.ts +295 -0
  162. package/src/pi_output.ts +387 -0
  163. package/src/pi_reasoning_signature.ts +41 -0
  164. package/src/pi_runtime.ts +238 -0
  165. package/src/pi_types.ts +71 -0
  166. package/src/portable_reasoning_state.ts +129 -0
  167. package/src/previous_decision.ts +109 -0
  168. package/src/prompts.ts +69 -0
  169. package/src/protocol_anthropic.ts +571 -0
  170. package/src/protocol_openai_chat.ts +645 -0
  171. package/src/protocol_validation.ts +202 -0
  172. package/src/route.ts +490 -0
  173. package/src/routing_history.ts +157 -0
  174. package/src/selector_input.ts +246 -0
  175. package/src/selector_parse.ts +138 -0
  176. package/src/selector_request.ts +130 -0
  177. package/src/selector_truncation.ts +48 -0
  178. package/src/selector_wire.ts +167 -0
  179. package/src/types.ts +231 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,100 @@
1
+ # Dari Router Core
2
+
3
+ `@mupt-ai/dari-router` puts multiple LLMs behind one endpoint. Declare models, provide a routing policy, and expose one web-standard handler for OpenAI Chat Completions and Anthropic Messages requests.
4
+
5
+ ```text
6
+ OpenAI or Anthropic request
7
+ │
8
+ ▼
9
+ Normalize and filter models
10
+ │
11
+ ▼
12
+ Your policy chooses
13
+ │
14
+ ▼
15
+ Pi AI or a custom executor
16
+ │
17
+ ▼
18
+ Response in the input protocol
19
+ ```
20
+
21
+ Pi AI is the bundled provider-client runtime. Custom executors replace it per-model when you need another SDK or transport. `createRouter` also ships pluggable lease storage, lifecycle hooks (`onSelection`, `onCompletion`, `onStreamClose`, `onError`), and opt-in cross-model fallback. [Dari's managed platform](https://docs.dari.dev/router/overview) provides a hosted endpoint with credentials, telemetry, billing, retries, and speculative routing.
22
+
23
+ ## Install
24
+
25
+ ```bash
26
+ bun add @mupt-ai/dari-router
27
+ # or
28
+ npm install @mupt-ai/dari-router
29
+ ```
30
+
31
+ Requires Node.js 22.19+ or Bun. Source lives at [mupt-ai/dari-router-core](https://github.com/mupt-ai/dari-router-core), mirrored from the Dari monorepo.
32
+
33
+ ## Quick Start
34
+
35
+ From a checkout of this repository:
36
+
37
+ ```bash
38
+ bun install --frozen-lockfile
39
+ bun run example # credential-free, in-memory executor
40
+ OPENAI_API_KEY=... bun run example:pi # real OpenAI call through Pi
41
+ ```
42
+
43
+ ## Minimal Router
44
+
45
+ ```ts
46
+ import { createPiRuntime, createRouter } from "@mupt-ai/dari-router";
47
+
48
+ const pi = await createPiRuntime({ apiKey: process.env.OPENAI_API_KEY! });
49
+ const router = createRouter({
50
+ runtime: pi,
51
+ models: [pi.model("openai/gpt-5.4-mini"), pi.model("openai/gpt-5.4")],
52
+ policy: ({ request, candidates }) => {
53
+ const long = JSON.stringify(request.items).length > 500;
54
+ return {
55
+ model: candidates.find((c) => c.id === (long ? "openai/gpt-5.4" : "openai/gpt-5.4-mini"))?.id ?? candidates[0]!.id,
56
+ reason: long ? "Longer requests use the larger model." : "Short requests use the fast model.",
57
+ };
58
+ },
59
+ });
60
+
61
+ Bun.serve({ port: 3000, fetch: router.fetch });
62
+ ```
63
+
64
+ ```bash
65
+ curl http://localhost:3000/v1/chat/completions \
66
+ -H 'Content-Type: application/json' \
67
+ -d '{"model": "my-router", "messages": [{"role": "user", "content": "Explain cache locality."}]}'
68
+ ```
69
+
70
+ The response includes `dari_routing` (`requested_model`, `selected_model`, `reasoning_effort`, `reason` — the same shape the managed Dari platform emits) and `X-Router-Selected-Model`. The incoming `model` is a caller-facing name — it doesn't force the policy's choice. The same handler also accepts `/v1/messages` for Anthropic.
71
+
72
+ ## Documentation
73
+
74
+ - [Overview](https://docs.dari.dev/framework/overview)
75
+ - [Quickstart](https://docs.dari.dev/framework/quickstart)
76
+ - [Models](https://docs.dari.dev/framework/models)
77
+ - [Policies](https://docs.dari.dev/framework/policies)
78
+ - [Pi Runtime](https://docs.dari.dev/framework/pi-runtime)
79
+ - [Custom Executors](https://docs.dari.dev/framework/custom-executors)
80
+ - [Protocols And Streaming](https://docs.dari.dev/framework/protocols-and-streaming)
81
+ - [Auto Router](https://docs.dari.dev/framework/auto-router)
82
+ - [Speculative Routing](https://docs.dari.dev/framework/speculative-routing)
83
+ - [Decision Pipeline](https://docs.dari.dev/framework/decision-pipeline)
84
+
85
+ ## Development
86
+
87
+ ```bash
88
+ bun install --frozen-lockfile
89
+ bun run typecheck
90
+ bun test
91
+ bun run build
92
+ bun run example:dari-policy
93
+ bun run example:decision-pipeline
94
+ ```
95
+
96
+ ESM package. Uses web-standard `Request`, `Response`, streams, and `AbortSignal`. Bun serves `router.fetch` directly; Node.js 22.19+ needs a Request/Response adapter.
97
+
98
+ ## License
99
+
100
+ Apache-2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,55 @@
1
+ import { type JsonObject, type JsonValue } from "./json.js";
2
+ import type { TurnCostProjection } from "./types.js";
3
+ export type Rng = () => number;
4
+ export type AnonymousActionCandidate = {
5
+ model: string;
6
+ reasoningEffort: string;
7
+ };
8
+ export type AnonymousActionSlot = {
9
+ action: string;
10
+ candidate: AnonymousActionCandidate;
11
+ };
12
+ export type AnonymousSelectorMessage = {
13
+ role: "system" | "user";
14
+ content: string;
15
+ };
16
+ export type AnonymousPolicyPrompt = {
17
+ messages: [system: AnonymousSelectorMessage, user: AnonymousSelectorMessage];
18
+ actions: string[];
19
+ };
20
+ export type AnonymousActionSelection = {
21
+ action: string;
22
+ candidate: AnonymousActionCandidate;
23
+ turns?: number;
24
+ };
25
+ export type AnonymousEvalScore = {
26
+ action: string;
27
+ rank: number;
28
+ rank_total: number;
29
+ z_score: number;
30
+ };
31
+ export type AnonymousEvalCard = {
32
+ name: string;
33
+ description: string | null;
34
+ scores: AnonymousEvalScore[];
35
+ };
36
+ export type AnonymousActionCost = {
37
+ action: string;
38
+ projections: TurnCostProjection[];
39
+ };
40
+ export type AnonymousSelectorInput = {
41
+ candidate_actions: Array<{
42
+ action: string;
43
+ }>;
44
+ imported_evals: AnonymousEvalCard[];
45
+ previous_action: {
46
+ action: string;
47
+ } | null;
48
+ cost_estimates: AnonymousActionCost[];
49
+ messages: JsonValue;
50
+ };
51
+ export declare function assignAnonymousActions(candidates: readonly AnonymousActionCandidate[], rng: Rng): AnonymousActionSlot[];
52
+ export declare function anonymizeSelectorInput(selectorInput: JsonObject, slots: readonly AnonymousActionSlot[]): AnonymousSelectorInput;
53
+ export declare function buildAnonymousPolicyPrompt(anonymousSelectorInput: AnonymousSelectorInput, slots: readonly AnonymousActionSlot[]): AnonymousPolicyPrompt;
54
+ export declare function formatAnonymousPolicyInput(input: AnonymousSelectorInput): string;
55
+ export declare function parseAnonymousActionSelection(completion: string, slots: readonly AnonymousActionSlot[], leaseTurns?: readonly number[]): AnonymousActionSelection;
@@ -0,0 +1,277 @@
1
+ // Anonymous candidate-action selector protocol. Candidates are shuffled into
2
+ // anonymous action slots ("A", "B", ..., "AA", ...) and every model-identifying
3
+ // field in the selector input is replaced by its slot, so a trained policy
4
+ // cannot memorize model names or list positions. This is the canonical
5
+ // open-weight selector protocol used by Dari's SLM routing strategy; the
6
+ // named-candidate protocol in selector_input.ts/prompts.ts remains available
7
+ // for custom routers that use a general-purpose LLM selector.
8
+ import { ANONYMOUS_ACTION_SYSTEM_PROMPT } from "./prompts.js";
9
+ import { jsonRecord, jsonValue, requiredString, } from "./json.js";
10
+ // Shuffles candidates into spreadsheet-style action slots A..Z, AA..AZ, ...
11
+ // with the injected rng.
12
+ export function assignAnonymousActions(candidates, rng) {
13
+ if (candidates.length < 2) {
14
+ throw new Error(`Anonymous action routing requires at least two candidates, got ${candidates.length}`);
15
+ }
16
+ const keys = new Set();
17
+ for (const candidate of candidates) {
18
+ const key = candidateKey(candidate.model, candidate.reasoningEffort);
19
+ if (keys.has(key))
20
+ throw new Error(`Duplicate anonymous action candidate ${key}`);
21
+ keys.add(key);
22
+ }
23
+ return shuffled(candidates, rng).map((candidate, index) => ({
24
+ action: actionForIndex(index),
25
+ candidate,
26
+ }));
27
+ }
28
+ function actionForIndex(index) {
29
+ let remaining = index;
30
+ let action = "";
31
+ do {
32
+ action = String.fromCharCode("A".charCodeAt(0) + (remaining % 26)) + action;
33
+ remaining = Math.floor(remaining / 26) - 1;
34
+ } while (remaining >= 0);
35
+ return action;
36
+ }
37
+ // Rewrites a named-candidate selector input (see selector_input.ts) into its
38
+ // anonymous-action form. The input must reference exactly the candidates in
39
+ // `slots`; any mismatch is an error rather than a silent partial rewrite.
40
+ export function anonymizeSelectorInput(selectorInput, slots) {
41
+ const input = jsonRecord(structuredClone(selectorInput), "selector input");
42
+ const byCandidate = new Map(slots.map((slot) => [candidateKey(slot.candidate.model, slot.candidate.reasoningEffort), slot.action]));
43
+ assertSelectorCandidates(input["candidate_pairs"], byCandidate);
44
+ return {
45
+ candidate_actions: slots.map((slot) => ({ action: slot.action })),
46
+ imported_evals: anonymizeEvals(input["imported_evals"], byCandidate),
47
+ previous_action: anonymizePreviousDecision(input["previous_decision"], byCandidate),
48
+ cost_estimates: anonymizeCosts(input["cost_estimates"], byCandidate),
49
+ messages: jsonValue(input["messages"], "selector input messages"),
50
+ };
51
+ }
52
+ export function buildAnonymousPolicyPrompt(anonymousSelectorInput, slots) {
53
+ return {
54
+ messages: [
55
+ { role: "system", content: ANONYMOUS_ACTION_SYSTEM_PROMPT },
56
+ { role: "user", content: formatAnonymousPolicyInput(anonymousSelectorInput) },
57
+ ],
58
+ actions: slots.map((slot) => slot.action),
59
+ };
60
+ }
61
+ // Renders the anonymous selector input as sectioned text rather than raw JSON.
62
+ // One block per action carries that action's benchmark standing and its
63
+ // projected cost, so the policy compares like against like instead of
64
+ // re-deriving comparisons from scores on incomparable scales and six cost
65
+ // fields. How to read those blocks lives in ANONYMOUS_ACTION_SYSTEM_PROMPT,
66
+ // keeping this message pure data. The conversation goes last: it is the only
67
+ // section that grows turn over turn, so keeping it at the end preserves the
68
+ // shared prefix.
69
+ export function formatAnonymousPolicyInput(input) {
70
+ const sections = [
71
+ ...(input.imported_evals.length > 0
72
+ ? [section("benchmarks", input.imported_evals.map(glossaryLine).join("\n"))]
73
+ : []),
74
+ section("candidates", input.candidate_actions
75
+ .map((candidate) => candidateBlock(candidate.action, input))
76
+ .join("\n\n")),
77
+ ...(input.previous_action === null
78
+ ? []
79
+ : [section("previous_action", input.previous_action.action)]),
80
+ section("conversation", JSON.stringify(input.messages)),
81
+ ];
82
+ return sections.join("\n\n");
83
+ }
84
+ function section(name, body) {
85
+ return `<${name}>\n${body}\n</${name}>`;
86
+ }
87
+ function candidateBlock(action, input) {
88
+ const cost = input.cost_estimates.find((entry) => entry.action === action);
89
+ const lines = [`## Action ${action}`];
90
+ if (cost !== undefined)
91
+ lines.push(costLine(cost));
92
+ for (const card of input.imported_evals) {
93
+ const score = card.scores.find((entry) => entry.action === action);
94
+ if (score !== undefined) {
95
+ lines.push(`- ${card.name}: Rank ${score.rank}/${score.rank_total}, Z ${signed(score.z_score)}`);
96
+ }
97
+ }
98
+ return lines.join("\n");
99
+ }
100
+ // One line, one unit, the same horizons for every action.
101
+ function costLine(cost) {
102
+ const horizons = cost.projections.map((projection) => `${projection.projected_turns} turn${projection.projected_turns === 1 ? "" : "s"} ${usd(projection.total_cost_usd)}`);
103
+ return `- Cost: ${horizons.join(", ")}`;
104
+ }
105
+ function signed(value) {
106
+ return value >= 0 ? `+${value.toFixed(2)}` : value.toFixed(2);
107
+ }
108
+ function usd(value) {
109
+ if (value >= 1)
110
+ return `$${value.toFixed(2)}`;
111
+ const trimmed = value.toPrecision(3).replace(/0+$/, "").replace(/\.$/, "");
112
+ return `$${trimmed}`;
113
+ }
114
+ function glossaryLine(card) {
115
+ return card.description === null ? `- ${card.name}` : `- ${card.name}: ${card.description}`;
116
+ }
117
+ function previousAction(value) {
118
+ if (value === null || value === undefined)
119
+ return null;
120
+ return requiredString(jsonRecord(value, "anonymous previous_action")["action"], "anonymous previous_action.action");
121
+ }
122
+ function isRecordValue(value) {
123
+ return typeof value === "object" && value !== null && !Array.isArray(value);
124
+ }
125
+ // Parses a policy completion against the permutation's slots. Without a lease
126
+ // menu the exact shape is {"action":"B"}; with one it is
127
+ // {"action":"B","turns":10} and turns must be on the menu.
128
+ export function parseAnonymousActionSelection(completion, slots, leaseTurns) {
129
+ let parsed;
130
+ try {
131
+ parsed = JSON.parse(completion);
132
+ }
133
+ catch {
134
+ throw new Error("Anonymous action completion is not valid JSON");
135
+ }
136
+ const record = jsonRecord(parsed, "anonymous action completion");
137
+ const keys = Object.keys(record);
138
+ // An empty menu means the caller routes one turn at a time, same as no menu.
139
+ const offeredLeaseTurns = leaseTurns !== undefined && leaseTurns.length > 0 ? leaseTurns : undefined;
140
+ const expected = offeredLeaseTurns === undefined ? ["action"] : ["action", "turns"];
141
+ if (keys.length !== expected.length || expected.some((key, i) => keys[i] !== key)) {
142
+ throw new Error(`Anonymous action completion must contain exactly {${expected
143
+ .map((key) => `"${key}":...`)
144
+ .join(",")}}`);
145
+ }
146
+ const action = record["action"];
147
+ if (typeof action !== "string") {
148
+ throw new Error("Anonymous action completion action must be a string");
149
+ }
150
+ const slot = slots.find((candidate) => candidate.action === action);
151
+ if (slot === undefined) {
152
+ throw new Error(`Anonymous action completion selected unavailable action ${action}`);
153
+ }
154
+ if (offeredLeaseTurns === undefined)
155
+ return { action, candidate: slot.candidate };
156
+ const turns = record["turns"];
157
+ if (typeof turns !== "number" || !offeredLeaseTurns.includes(turns)) {
158
+ throw new Error(`Anonymous action completion turns must be one of ${offeredLeaseTurns.join(", ")}`);
159
+ }
160
+ return { action, candidate: slot.candidate, turns };
161
+ }
162
+ // Fisher-Yates copy, drawing from the end, matching d3-array's shuffler so an
163
+ // injected rng reproduces permutations recorded by harnesses that used d3.
164
+ function shuffled(items, rng) {
165
+ const array = [...items];
166
+ let m = array.length;
167
+ while (m) {
168
+ const i = (rng() * m--) | 0;
169
+ const t = array[m];
170
+ array[m] = array[i];
171
+ array[i] = t;
172
+ }
173
+ return array;
174
+ }
175
+ function assertSelectorCandidates(value, byCandidate) {
176
+ if (!Array.isArray(value)) {
177
+ throw new Error("Selector input candidate_pairs must be an array");
178
+ }
179
+ const selectorKeys = new Set(value.map((candidate, index) => {
180
+ const record = jsonRecord(candidate, `selector candidate[${index}]`);
181
+ return candidateKey(requiredString(record["model"], `selector candidate[${index}].model`), requiredString(record["thinking_level"], `selector candidate[${index}].thinking_level`));
182
+ }));
183
+ if (selectorKeys.size !== byCandidate.size || [...byCandidate.keys()].some((key) => !selectorKeys.has(key))) {
184
+ throw new Error("Routing and selector candidates do not match");
185
+ }
186
+ }
187
+ function anonymizeEvals(value, byCandidate) {
188
+ if (!Array.isArray(value)) {
189
+ throw new Error("Selector input imported_evals must be an array");
190
+ }
191
+ return value.map((entry, evalIndex) => {
192
+ const card = jsonRecord(entry, `selector eval[${evalIndex}]`);
193
+ const scores = card["scores"];
194
+ if (!Array.isArray(scores)) {
195
+ throw new Error(`selector eval[${evalIndex}].scores must be an array`);
196
+ }
197
+ return {
198
+ name: requiredString(card["name"], `selector eval[${evalIndex}].name`),
199
+ description: typeof card["description"] === "string" ? card["description"] : null,
200
+ // Explicit allowlist: notes and any future field can name the model.
201
+ scores: scores.map((entryScore, scoreIndex) => {
202
+ const label = `selector eval[${evalIndex}].scores[${scoreIndex}]`;
203
+ const score = jsonRecord(entryScore, label);
204
+ return {
205
+ action: actionForCandidate(byCandidate, requiredString(score["model_id"], `${label}.model_id`), requiredString(score["thinking_level"], `${label}.thinking_level`)),
206
+ rank: requiredNumber(score["rank"], `${label}.rank`),
207
+ rank_total: requiredNumber(score["rank_total"], `${label}.rank_total`),
208
+ z_score: requiredNumber(score["z_score"], `${label}.z_score`),
209
+ };
210
+ }),
211
+ };
212
+ });
213
+ }
214
+ function anonymizePreviousDecision(value, byCandidate) {
215
+ if (value === null || value === undefined)
216
+ return null;
217
+ const previous = jsonRecord(value, "selector previous_decision");
218
+ const model = requiredString(previous["model"], "selector previous_decision.model");
219
+ const thinkingLevel = requiredString(previous["thinking_level"], "selector previous_decision.thinking_level");
220
+ return {
221
+ action: actionForCandidate(byCandidate, model, thinkingLevel),
222
+ };
223
+ }
224
+ function anonymizeCosts(value, byCandidate) {
225
+ if (value === null || value === undefined)
226
+ return [];
227
+ if (!Array.isArray(value)) {
228
+ throw new Error("Selector input cost_estimates must be an array or null");
229
+ }
230
+ // Only the loop projections survive. The per-request fields the prompt does
231
+ // not show would be dead weight, and assumed_reasoning_effort names the
232
+ // candidate's thinking level, which the protocol exists to hide.
233
+ return value.flatMap((entry, index) => {
234
+ const label = `selector cost_estimates[${index}]`;
235
+ const cost = jsonRecord(entry, label);
236
+ const action = actionForCandidate(byCandidate, requiredString(cost["model"], `${label}.model`), requiredString(cost["reasoning_effort"], `${label}.reasoning_effort`));
237
+ const fixedTurn = cost["fixed_turn_cost_estimate"];
238
+ if (fixedTurn === null || fixedTurn === undefined)
239
+ return [];
240
+ if (!isRecordValue(fixedTurn) || !Array.isArray(fixedTurn["projections"])) {
241
+ // A present estimate without projections is the pre-projection schema.
242
+ // Reject it loudly: silently dropping it would show "Cost: unavailable"
243
+ // for a candidate whose cost the caller thinks it supplied.
244
+ throw new Error(`${label}.fixed_turn_cost_estimate must carry a projections array`);
245
+ }
246
+ return [
247
+ {
248
+ action,
249
+ projections: fixedTurn["projections"].map((projection, projectionIndex) => {
250
+ const projectionLabel = `${label}.fixed_turn_cost_estimate.projections[${projectionIndex}]`;
251
+ const record = jsonRecord(projection, projectionLabel);
252
+ return {
253
+ projected_turns: requiredNumber(record["projected_turns"], `${projectionLabel}.projected_turns`),
254
+ total_cost_usd: requiredNumber(record["total_cost_usd"], `${projectionLabel}.total_cost_usd`),
255
+ };
256
+ }),
257
+ },
258
+ ];
259
+ });
260
+ }
261
+ function requiredNumber(value, label) {
262
+ if (typeof value !== "number" || !Number.isFinite(value)) {
263
+ throw new Error(`${label} must be a finite number`);
264
+ }
265
+ return value;
266
+ }
267
+ function actionForCandidate(byCandidate, model, thinkingLevel) {
268
+ const action = byCandidate.get(candidateKey(model, thinkingLevel));
269
+ if (action === undefined) {
270
+ throw new Error(`Selector field references unavailable candidate ${model}/${thinkingLevel}`);
271
+ }
272
+ return action;
273
+ }
274
+ function candidateKey(model, thinkingLevel) {
275
+ return `${model}\u0000${thinkingLevel}`;
276
+ }
277
+ //# sourceMappingURL=anonymous_actions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"anonymous_actions.js","sourceRoot":"","sources":["../src/anonymous_actions.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,gFAAgF;AAChF,2EAA2E;AAC3E,uEAAuE;AACvE,yEAAyE;AACzE,6EAA6E;AAC7E,8DAA8D;AAE9D,OAAO,EAAE,8BAA8B,EAAE,MAAM,cAAc,CAAC;AAC9D,OAAO,EACL,UAAU,EACV,SAAS,EACT,cAAc,GAGf,MAAM,WAAW,CAAC;AAiEnB,4EAA4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