@vllm-sr/dsh 0.0.0-stage → 0.3.1

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,129 @@
1
- # Temporary Holding Version
1
+ # @vllm-sr/dsh
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **System Duo** for [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness): *Thinking, fast and slow. One
4
+ key.*
5
+
6
+ An agent's LLM thinks slowly, in tokens. System One, a decision model, answers the many small questions around it in
7
+ about half a second each, with calibrated probabilities: is this command dangerous, does this file try to give the
8
+ agent orders, is the work really done, which team should get each of these 230 tickets.
9
+
10
+ - **System Two**, the LLM, plans and acts: `vllm-sr/auto` from [vLLM Semantic Router](https://github.com/vllm-project/semantic-router),
11
+ which sends each step to the right open model.
12
+ - **System One**, the decision model, decides: `vllm-sr/d3-ultra`. It answers typed questions (choice, yes/no, score,
13
+ box) with probabilities, from one forward pass per question instead of generated text.
14
+
15
+ Both come from [System Duo](https://app.vllm-sr.ai) with one free key, and the plugin gets that key for you: System One
16
+ answers at `https://app.vllm-sr.ai/v1/systemone`, and `vllm-sr/auto` at `https://app.vllm-sr.ai/v1/chat/completions`.
17
+
18
+ ## Quick start
19
+
20
+ ```bash
21
+ npm install -g @deepseek-ai/dsh # DeepSeek Harness 0.2.1-rc.5 or a later 0.2 release, Node 24.9 or later
22
+ dsh plugin --profile web add @vllm-sr/dsh
23
+ dsh web
24
+ ```
25
+
26
+ The package can also come straight from GitHub: `dsh plugin --profile web add github:Xunzhuo/dsh-system-one-plugin`.
27
+
28
+ On its first start the plugin gets one free System Duo key, with the same small proof of work the site's "Get your
29
+ API key" button runs in the browser, and saves it in DeepSeek Harness's credential store and in `~/.dsh/.env` (readable
30
+ by you only). A notice in the session says so. `vllm-sr/auto` becomes the default model; choose another model
31
+ in the app and System One keeps working beside it.
32
+
33
+ Headless:
34
+
35
+ ```bash
36
+ dsh plugin --profile headless add @vllm-sr/dsh
37
+ dsh headless "Triage tickets.jsonl: route each ticket, score its urgency, flag churn risk"
38
+ ```
39
+
40
+ A headless run reads its key when it starts. If there is none yet, the first run fetches and saves it, and the LLM
41
+ answers from the next run (or start `dsh web` once first). In CI, set `VLLM_SR_API_KEY` to a key from
42
+ [app.vllm-sr.ai](https://app.vllm-sr.ai) instead; a key you set yourself is always used and never replaced.
43
+
44
+ Had the earlier `dsh-system-one` 0.2 from GitHub or a local path? Replace it with
45
+ `dsh plugin --profile web remove dsh-system-one`, then add `@vllm-sr/dsh` as above. Your keys and the `system-one` row
46
+ of your profile patch stay as they are.
47
+
48
+ ## What it does
49
+
50
+ | Reflex | Hook | What System One answers | What happens |
51
+ | --- | --- | --- | --- |
52
+ | Triage | `agent/pre-step` | kind of work, effort, unclear?, risky? | a one-line brief joins the request, with hints (use `system_one` for batch work, ask first when unclear) |
53
+ | Guard | `tools/pre-execute` | risk (Safe, Normal, Dangerous, Critical), leaks secrets?, on task? | the call runs, waits for your approval (Web UI), or is denied with the reason (headless) |
54
+ | Shield | `tools/post-execute` | does this passage give orders to an AI agent? | flagged passages are scored again line by line, and only the injected lines are removed |
55
+ | Done-check | `agent/turn-stopping` | complete?, checked?, waiting for you? | an unfinished turn goes back once or twice to finish and verify |
56
+ | Tool | `system_one` | any rubric the LLM writes, over a file of items or images | one result row per item (JSONL or CSV) and a summary |
57
+
58
+ ## Your data
59
+
60
+ System One sends what it decides about: the user's request (clipped), each tool call it reviews, the passages of tool
61
+ results it screens, the end of the turn, and the items given to the `system_one` tool. System Two receives the
62
+ conversation as any LLM provider does. System Duo logs requests to improve the services and to train models; read its
63
+ [terms](https://app.vllm-sr.ai/terms) and [privacy](https://app.vllm-sr.ai/privacy) pages before you use it with
64
+ private code or data. Each reflex can be turned off.
65
+
66
+ The local trace (`~/.dsh/system-one/trace.jsonl`, readable by you only) records every decision with its probabilities
67
+ and redacts secret-shaped strings; it never records keys. Set `trace: off` to disable it.
68
+
69
+ ## Configuration
70
+
71
+ Every field has a default. Set any of them on the `system-one` row of a profile patch
72
+ (`~/.dsh/profiles/<name>/cordis.patch.yml`):
73
+
74
+ ```yaml
75
+ - id: system-one
76
+ config:
77
+ model: vllm-sr/d3-ultra # vllm-sr/d3-flash is a little faster; d3-ultra is the most accurate
78
+ autoKeys: true # fetch the free System Duo key on first use
79
+ guardAskMode: ask # what a flagged call does: ask (wait for approval) or deny
80
+ guardAskAt: 1.8 # risk score (0 Safe to 3 Critical) that asks
81
+ guardDenyAt: 2.5 # risk score that always denies
82
+ guardExfiltrationAt: 0.7 # "leaks secrets" probability that denies
83
+ guardTools: [bash, write, edit, apply_patch, web_fetch]
84
+ shieldTools: [web_fetch, read, bash]
85
+ triage: true
86
+ doneCheck: true
87
+ tool: true
88
+ trace: ~/.dsh/system-one/trace.jsonl # or off
89
+ ```
90
+
91
+ The key comes from the credential reference `VLLM_SR_API_KEY` (`llmKeyEnv`), which both systems use. A separate
92
+ System One key in `DECISION_API_KEY` (`apiKeyEnv`), as plugin 0.2 kept it, still wins for System One; a 0.2 key for
93
+ `vllm-sr/auto` keeps working too.
94
+ If the decision service cannot be reached, a guarded call falls back to `guardOnError` (default `allow`); the
95
+ harness's own sandbox and approvals still apply.
96
+
97
+ ## Measured
98
+
99
+ On our recorded runs, from one workstation with the network included:
100
+
101
+ | What | Result |
102
+ | --- | --- |
103
+ | A decision | p50 0.49 s, p90 0.52 s (53 guard decisions) |
104
+ | Guard | 35 of 36 right on our 36-command probe set: 16 of 16 risky commands stopped, 19 of 20 safe ones allowed |
105
+ | Shield | 22 of 22 right on our 22-passage probe set: 10 of 10 injections caught, 12 of 12 clean passages kept |
106
+ | Triage of 230 tickets | 121 s and 117,877 LLM prompt tokens, against 543 s and at least 510,986 for the LLM alone |
107
+ | UI screenshots | 5 of 5 broken screens found and boxed, no false alarms, 3.96 s for 12 |
108
+
109
+ The probe sets are ours and small: read them as a smoke test, not a benchmark.
110
+
111
+ ## Develop
112
+
113
+ ```bash
114
+ npm test # unit tests with a fake decision service and a fake key site
115
+ VLLM_SR_API_KEY=... node probes/guard-probe.mjs vllm-sr/d3-ultra # live calibration of the guard
116
+ VLLM_SR_API_KEY=... node probes/shield-probe.mjs vllm-sr/d3-ultra # live calibration of the shield
117
+ ```
118
+
119
+ A `v*` tag publishes the package to npm from GitHub Actions with trusted publishing, with no npm token in the
120
+ repository; see [RELEASING.md](https://github.com/Xunzhuo/dsh-system-one-plugin/blob/main/RELEASING.md).
121
+
122
+ ## Trademarks
123
+
124
+ DeepSeek Harness is a trademark of DeepSeek, named here only to identify the harness the plugin works with.
125
+ The plugin is not a DeepSeek product, and DeepSeek does not endorse System Duo.
126
+
127
+ ## License
128
+
129
+ Apache-2.0
@@ -0,0 +1,29 @@
1
+ # System Duo for DeepSeek Harness: System One (decision models) on the agent loop, and System Two, the free LLM
2
+ # vllm-sr/auto from vLLM Semantic Router, both at app.vllm-sr.ai with one key fetched on first use. A model chosen in
3
+ # the app's settings still wins, and a profile patch can replace either row.
4
+ - insert:
5
+ - id: system-one
6
+ name: '@vllm-sr/dsh'
7
+
8
+ - id: llm-pi-ai
9
+ config:
10
+ providers:
11
+ vllm-sr:
12
+ displayName: System Duo (vLLM Semantic Router)
13
+ apiKeyEnv: VLLM_SR_API_KEY
14
+ api: openai-completions
15
+ baseURL: https://app.vllm-sr.ai/v1
16
+ compat:
17
+ supportsDeveloperRole: false
18
+ maxTokensField: max_tokens
19
+ timeoutMs: 600000
20
+ models:
21
+ - id: vllm-sr/auto
22
+ name: vllm-sr/auto
23
+ contextWindow: 131072
24
+ maxTokens: 32768
25
+
26
+ - id: agent-default-model
27
+ config:
28
+ provider: vllm-sr
29
+ model: vllm-sr/auto
package/package.json CHANGED
@@ -1,6 +1,76 @@
1
1
  {
2
2
  "name": "@vllm-sr/dsh",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.1",
4
+ "description": "System Duo for DeepSeek Harness. Thinking, fast and slow. One key: System One decision models guard, shield, triage and check your agent around System Two (vllm-sr/auto), with one free app.vllm-sr.ai key.",
5
+ "keywords": [
6
+ "deepseek-harness",
7
+ "dsh",
8
+ "dsh-plugin",
9
+ "agent",
10
+ "decision-model",
11
+ "guardrails",
12
+ "prompt-injection",
13
+ "vllm-semantic-router",
14
+ "vllm-sr",
15
+ "system-duo",
16
+ "system-one"
17
+ ],
18
+ "author": "Xunzhuo Liu",
19
+ "license": "Apache-2.0",
20
+ "homepage": "https://github.com/Xunzhuo/dsh-system-one-plugin#readme",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/Xunzhuo/dsh-system-one-plugin.git"
24
+ },
25
+ "bugs": {
26
+ "url": "https://github.com/Xunzhuo/dsh-system-one-plugin/issues"
27
+ },
28
+ "type": "module",
29
+ "main": "src/index.js",
30
+ "exports": {
31
+ ".": "./src/index.js",
32
+ "./package.json": "./package.json"
33
+ },
34
+ "files": [
35
+ "src",
36
+ "cordis.patch.yml",
37
+ "README.md",
38
+ "LICENSE"
39
+ ],
40
+ "engines": {
41
+ "node": ">=24.9",
42
+ "dsh": ">=0.2.1-rc.5 <0.3.0"
43
+ },
44
+ "dsh": {
45
+ "bundle": {
46
+ "patch": "./cordis.patch.yml"
47
+ }
48
+ },
49
+ "peerDependencies": {
50
+ "@deepseek-ai/cordis": "^4.0.5",
51
+ "@deepseek-ai/dsh-llm": ">=0.2.1-rc.5 <0.3.0",
52
+ "@deepseek-ai/dsh-tools": ">=0.2.1-rc.5 <0.3.0",
53
+ "@deepseek-ai/schemastery": "^3.18.5"
54
+ },
55
+ "peerDependenciesMeta": {
56
+ "@deepseek-ai/cordis": {
57
+ "optional": true
58
+ },
59
+ "@deepseek-ai/dsh-llm": {
60
+ "optional": true
61
+ },
62
+ "@deepseek-ai/dsh-tools": {
63
+ "optional": true
64
+ },
65
+ "@deepseek-ai/schemastery": {
66
+ "optional": true
67
+ }
68
+ },
69
+ "publishConfig": {
70
+ "access": "public",
71
+ "provenance": true
72
+ },
73
+ "scripts": {
74
+ "test": "node --test test/*.test.js"
75
+ }
76
+ }
package/src/client.js ADDED
@@ -0,0 +1,225 @@
1
+ /**
2
+ * Decision API client. A decision model answers typed questions (choice, noul,
3
+ * score, box) about an input with calibrated probabilities, from one forward
4
+ * pass per question. Connections are reused: a fresh TLS handshake costs more
5
+ * than the decision itself.
6
+ */
7
+ import { readFileSync } from 'node:fs'
8
+ import http from 'node:http'
9
+ import https from 'node:https'
10
+ import { homedir } from 'node:os'
11
+ import { setTimeout as sleep } from 'node:timers/promises'
12
+
13
+ /** Inputs answered by one request: the top-level state plus `limits.max_states` more. */
14
+ export const ITEMS_PER_REQUEST = 9
15
+
16
+ export class DecisionError extends Error {
17
+ constructor(message, status = 0, code = undefined) {
18
+ super(message)
19
+ this.name = 'DecisionError'
20
+ this.status = status
21
+ this.code = code
22
+ }
23
+ }
24
+
25
+ function expandHome(path) {
26
+ return path?.startsWith('~/') ? homedir() + path.slice(1) : path
27
+ }
28
+
29
+ /**
30
+ * @param {object} options
31
+ * @param {string} options.baseURL
32
+ * @param {string} options.apiKeyEnv - environment variable holding the key
33
+ * @param {string} [options.apiKeyFile] - mode-600 file holding the key, read when the variable is unset
34
+ * @param {() => Promise<string | undefined>} [options.resolveKey] - the key from DeepSeek Harness's credential store, asked first
35
+ * @param {number} [options.maxConcurrency]
36
+ * @param {number} [options.timeoutMs]
37
+ * @param {number} [options.retries]
38
+ */
39
+ export function createDecisionClient(options) {
40
+ const baseURL = options.baseURL.replace(/\/+$/, '')
41
+ const maxConcurrency = options.maxConcurrency ?? 12
42
+ const timeoutMs = options.timeoutMs ?? 30000
43
+ const retries = options.retries ?? 3
44
+ const endpoint = new URL(baseURL)
45
+ const transport = endpoint.protocol === 'http:' ? http : https
46
+ // Agent steps are seconds apart; fetch's default pool would close the
47
+ // socket in between and pay a new TLS handshake on every decision.
48
+ const agent = new transport.Agent({ keepAlive: true, keepAliveMsecs: 15000, maxSockets: maxConcurrency, scheduling: 'lifo' })
49
+ let active = 0
50
+ const waiting = []
51
+
52
+ function send(path, method, payload, headers, signal) {
53
+ return new Promise((resolve, reject) => {
54
+ const request = transport.request(new URL(baseURL + path), { method, agent, headers, signal }, response => {
55
+ const chunks = []
56
+ response.on('data', chunk => chunks.push(chunk))
57
+ response.on('end', () => resolve({ status: response.statusCode ?? 0, headers: response.headers, text: Buffer.concat(chunks).toString('utf8') }))
58
+ response.on('error', reject)
59
+ })
60
+ request.on('error', reject)
61
+ request.end(payload)
62
+ })
63
+ }
64
+
65
+ async function apiKey() {
66
+ const stored = await options.resolveKey?.()
67
+ if (stored) return stored.trim()
68
+ const fromEnv = process.env[options.apiKeyEnv]
69
+ if (fromEnv) return fromEnv.trim()
70
+ if (options.apiKeyFile) {
71
+ try {
72
+ return readFileSync(expandHome(options.apiKeyFile), 'utf8').trim()
73
+ } catch {
74
+ return undefined
75
+ }
76
+ }
77
+ return undefined
78
+ }
79
+
80
+ async function acquire(signal) {
81
+ while (active >= maxConcurrency) {
82
+ signal?.throwIfAborted()
83
+ // A cancelled caller leaves the queue at once: a wakeup it took without taking the slot would be lost for good.
84
+ await new Promise((resolve, reject) => {
85
+ const wake = () => {
86
+ signal?.removeEventListener('abort', cancel)
87
+ resolve()
88
+ }
89
+ const cancel = () => {
90
+ const at = waiting.indexOf(wake)
91
+ if (at >= 0) waiting.splice(at, 1)
92
+ reject(signal.reason)
93
+ }
94
+ waiting.push(wake)
95
+ signal?.addEventListener('abort', cancel, { once: true })
96
+ })
97
+ }
98
+ active++
99
+ }
100
+
101
+ function release() {
102
+ active--
103
+ waiting.shift()?.()
104
+ }
105
+
106
+ async function post(path, body, signal, limits = {}) {
107
+ const deadlineMs = limits.timeoutMs ?? timeoutMs
108
+ const maxRetries = limits.retries ?? retries
109
+ const key = await apiKey()
110
+ if (!key) throw new DecisionError(`no System One key: set ${options.apiKeyEnv}, or get a free System Duo key at https://app.vllm-sr.ai`, 401, 'missing_api_key')
111
+ const payload = JSON.stringify(body)
112
+ const headers = {
113
+ authorization: `Bearer ${key}`,
114
+ 'content-type': 'application/json',
115
+ 'content-length': Buffer.byteLength(payload),
116
+ }
117
+ for (let attempt = 0; ; attempt++) {
118
+ const deadline = AbortSignal.timeout(deadlineMs)
119
+ let response
120
+ try {
121
+ response = await send(path, 'POST', payload, headers, signal ? AbortSignal.any([signal, deadline]) : deadline)
122
+ } catch (error) {
123
+ if (signal?.aborted) throw error
124
+ if (attempt < maxRetries) {
125
+ await sleep(300 * 2 ** attempt)
126
+ continue
127
+ }
128
+ throw new DecisionError(`Decision API unreachable: ${error.message}`, 0, 'network')
129
+ }
130
+ if (response.status >= 200 && response.status < 300) {
131
+ return { json: JSON.parse(response.text), requestId: response.headers['x-request-id'] }
132
+ }
133
+ let code
134
+ try {
135
+ code = JSON.parse(response.text).error?.code
136
+ } catch {
137
+ code = undefined
138
+ }
139
+ const retryable = response.status === 429 || response.status === 502 || response.status === 503
140
+ if (retryable && attempt < maxRetries) {
141
+ const after = Number(response.headers['retry-after'])
142
+ const wait = Number.isFinite(after) && after > 0 ? Math.min(after, 10) * 1000 : 400 * 2 ** attempt
143
+ await sleep(wait + Math.random() * 200)
144
+ continue
145
+ }
146
+ throw new DecisionError(`Decision API ${response.status}${code ? ` ${code}` : ''}`, response.status, code)
147
+ }
148
+ }
149
+
150
+ /**
151
+ * Ask questions about one input, or about several inputs at once.
152
+ * @param {object} request
153
+ * @param {string} request.model
154
+ * @param {object} request.questions - shared by every input
155
+ * @param {Array<{state: string, images?: string[]}>} request.inputs - at most {@link ITEMS_PER_REQUEST}
156
+ * @param {AbortSignal} [request.signal]
157
+ * @param {number} [request.timeoutMs] - per-call deadline (default: the client's)
158
+ * @param {number} [request.retries] - per-call retries (default: the client's)
159
+ * @returns {Promise<{answers: object[], ms: number, model: string, inputTokens: number, requestId?: string}>}
160
+ * answers in input order
161
+ */
162
+ async function ask({ model, questions, inputs, signal, timeoutMs: callTimeoutMs, retries: callRetries }) {
163
+ if (inputs.length === 0 || inputs.length > ITEMS_PER_REQUEST) {
164
+ throw new RangeError(`one request answers 1 to ${ITEMS_PER_REQUEST} inputs, got ${inputs.length}`)
165
+ }
166
+ const [first, ...rest] = inputs
167
+ const body = { model, state: first.state, questions }
168
+ if (first.images?.length) body.images = first.images
169
+ if (rest.length > 0) {
170
+ body.states = Object.fromEntries(rest.map((input, index) => [
171
+ `i${index + 1}`,
172
+ { state: input.state, questions, ...input.images?.length ? { images: input.images } : {} },
173
+ ]))
174
+ }
175
+ await acquire(signal)
176
+ const started = performance.now()
177
+ try {
178
+ const { json, requestId } = await post('/v1/decisions', body, signal, { timeoutMs: callTimeoutMs, retries: callRetries })
179
+ const answers = [json.answers, ...rest.map((_, index) => json.states?.[`i${index + 1}`]?.answers ?? {})]
180
+ let inputTokens = json.usage?.input_tokens ?? 0
181
+ for (const entry of Object.values(json.states ?? {})) inputTokens += entry.usage?.input_tokens ?? 0
182
+ return { answers, ms: performance.now() - started, model: json.model ?? model, inputTokens, requestId }
183
+ } finally {
184
+ release()
185
+ }
186
+ }
187
+
188
+ /** Open the connection ahead of the first decision; failures are ignored. */
189
+ function warm() {
190
+ send('/api/info', 'GET', undefined, {}, AbortSignal.timeout(timeoutMs)).catch(() => {})
191
+ }
192
+
193
+ return { ask, warm, hasKey: async () => Boolean(await apiKey()), close: () => agent.destroy() }
194
+ }
195
+
196
+ /** Probability that a noul answer is yes, or undefined when the question failed. */
197
+ export function yes(answer) {
198
+ return typeof answer?.noul === 'number' ? answer.noul : undefined
199
+ }
200
+
201
+ /** Compact, readable copy of one answer for traces and model-facing text. */
202
+ export function compactAnswer(answer) {
203
+ if (!answer || answer.error) return { error: answer?.error ?? 'missing', reason: answer?.reason }
204
+ const round = value => Math.round(value * 1000) / 1000
205
+ switch (answer.type) {
206
+ case 'choice':
207
+ return {
208
+ choice: answer.choice,
209
+ confidence: round(answer.confidence),
210
+ p: Object.fromEntries(Object.entries(answer.probabilities ?? {}).map(([k, v]) => [k, round(v)])),
211
+ }
212
+ case 'noul':
213
+ return { yes: round(answer.noul) }
214
+ case 'score':
215
+ return {
216
+ score: round(answer.score),
217
+ confidence: round(answer.confidence),
218
+ p: Object.fromEntries(Object.entries(answer.probabilities ?? {}).map(([k, v]) => [answer.legend?.[k] ?? k, round(v)])),
219
+ }
220
+ case 'box':
221
+ return { box: answer.box, confidence: round(answer.confidence) }
222
+ default:
223
+ return answer
224
+ }
225
+ }