@volter/twin-deepseek 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 (42) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +198 -0
  3. package/dist/src/cli.d.ts +2 -0
  4. package/dist/src/cli.js +28 -0
  5. package/dist/src/deepseek-budget.d.ts +51 -0
  6. package/dist/src/deepseek-budget.js +152 -0
  7. package/dist/src/deepseek-cache.d.ts +56 -0
  8. package/dist/src/deepseek-cache.js +151 -0
  9. package/dist/src/deepseek-capabilities.d.ts +4 -0
  10. package/dist/src/deepseek-capabilities.js +1520 -0
  11. package/dist/src/deepseek-conformance.d.ts +14 -0
  12. package/dist/src/deepseek-conformance.js +473 -0
  13. package/dist/src/deepseek-connector.d.ts +168 -0
  14. package/dist/src/deepseek-connector.js +386 -0
  15. package/dist/src/deepseek-models.d.ts +30 -0
  16. package/dist/src/deepseek-models.js +38 -0
  17. package/dist/src/deepseek-scenario.d.ts +55 -0
  18. package/dist/src/deepseek-scenario.js +170 -0
  19. package/dist/src/deepseek-server.d.ts +16 -0
  20. package/dist/src/deepseek-server.js +191 -0
  21. package/dist/src/deepseek-stub.d.ts +75 -0
  22. package/dist/src/deepseek-stub.js +191 -0
  23. package/dist/src/deepseek-twin.d.ts +77 -0
  24. package/dist/src/deepseek-twin.js +1103 -0
  25. package/dist/src/deepseek-types.d.ts +172 -0
  26. package/dist/src/deepseek-types.js +26 -0
  27. package/dist/src/index.d.ts +15 -0
  28. package/dist/src/index.js +93 -0
  29. package/package.json +68 -0
  30. package/src/cli.ts +27 -0
  31. package/src/deepseek-budget.ts +178 -0
  32. package/src/deepseek-cache.ts +159 -0
  33. package/src/deepseek-capabilities.ts +1443 -0
  34. package/src/deepseek-conformance.ts +512 -0
  35. package/src/deepseek-connector.ts +440 -0
  36. package/src/deepseek-models.ts +65 -0
  37. package/src/deepseek-scenario.ts +188 -0
  38. package/src/deepseek-server.ts +201 -0
  39. package/src/deepseek-stub.ts +200 -0
  40. package/src/deepseek-twin.ts +1163 -0
  41. package/src/deepseek-types.ts +201 -0
  42. package/src/index.ts +133 -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,198 @@
1
+ # @volter/twin-deepseek
2
+
3
+ > **Legacy connector helpers:** this package still has callable helpers using the retired v1
4
+ > `syncPull` API. Those paths require migration before use on the current kernel;
5
+ > older helper descriptions below do not establish current compatibility. Check the
6
+ > [generated index](../../../generated/INDEX.md) for protocol standing and use the
7
+ > [shared model](../../../docs/concepts/the-model.md) for current state semantics.
8
+
9
+ A local, faithful **DeepSeek Platform API** twin your real `@ai-sdk/deepseek` talks to
10
+ unmodified — point the provider at the twin's `baseURL` and `doGenerate`, `doStream`, `files()`,
11
+ `GET /models` and `GET /user/balance` all work. Built on the shared `@volter/world-core` kernel (durable
12
+ event/action log + projection); no parallel side store.
13
+
14
+ ```ts
15
+ import { createDeepSeek } from '@ai-sdk/deepseek';
16
+ import { createDeepSeekTwinServer } from '@volter/twin-deepseek';
17
+
18
+ const { port } = createDeepSeekTwinServer({});
19
+ // NOTE: no `/v1`. DeepSeek's base_url has no version segment, and the SDK appends
20
+ // `/chat/completions` to whatever you give it.
21
+ const deepseek = createDeepSeek({ apiKey: 'sk-twin', baseURL: `http://127.0.0.1:${port}` });
22
+
23
+ const result = await deepseek('deepseek-v4-flash').doGenerate({
24
+ prompt: [{ role: 'user', content: [{ type: 'text', text: 'hello' }] }],
25
+ });
26
+ // The text part starts with "[twin-stub:…]" — a deterministic stub, clearly labeled.
27
+ // A `reasoning` part precedes it (V4 models think by default), and
28
+ // result.providerMetadata.deepseek carries promptCacheHitTokens / promptCacheMissTokens.
29
+ ```
30
+
31
+ The beta surface is a base-URL suffix, exactly as on the real vendor — it unlocks assistant-prefix
32
+ completion and strict tool calls, and it is where FIM completion lives:
33
+
34
+ ```ts
35
+ const beta = createDeepSeek({ apiKey: 'sk-twin', baseURL: `http://127.0.0.1:${port}/beta` });
36
+ ```
37
+
38
+ ## DeepSeek is not OpenAI — and the REFUSALS are what this twin is for
39
+
40
+ DeepSeek exposes an *OpenAI-compatible* surface, and treating "compatible" as "identical" is how a
41
+ DeepSeek twin gets built wrong: the response shapes are the easy half, and what actually
42
+ distinguishes the vendor is **what it refuses**. Every divergence below is modeled and pinned by a
43
+ capability with a failable negative verify, grounded in
44
+ [`@ai-sdk/deepseek@3.0.37`](https://www.npmjs.com/package/@ai-sdk/deepseek) read as source and
45
+ [api-docs.deepseek.com](https://api-docs.deepseek.com/), both read 2026-08-31.
46
+
47
+ | | DeepSeek | OpenAI |
48
+ |---|---|---|
49
+ | base path | **`https://api.deepseek.com/chat/completions`** — no version segment | `https://api.openai.com/v1/chat/completions` |
50
+ | bad parameter | **422** "Your request contains invalid parameters" | 400 |
51
+ | malformed body | 400 "Invalid request body format" | 400 |
52
+ | out of credit | **402** "You have run out of balance" | (no 402) |
53
+ | documented statuses | 400 / 401 / **402** / **422** / 429 / 500 / 503 — **no 404** | 400 / 401 / 403 / 404 / 429 / 5xx |
54
+ | usage cache fields | **`prompt_cache_hit_tokens` / `prompt_cache_miss_tokens`** | `prompt_tokens_details.cached_tokens` |
55
+ | reasoning | **`reasoning_content`** on the message and the delta | `reasoning` on o-series responses only |
56
+ | finish reasons | `stop`, `length`, `content_filter`, `tool_calls`, **`insufficient_system_resource`** | no `insufficient_system_resource` |
57
+ | end-user id | **`user_id`** (`^[a-zA-Z0-9_-]+$`, ≤512) | `user` |
58
+ | structured output (chat) | `text`, `json_object` — **no `json_schema` on `/chat/completions`** (its Responses API's `text.format` does take one) | `text`, `json_object`, `json_schema` |
59
+ | not parameters at all | **`n`, `seed`, `logit_bias`, `top_k`, `user`, `max_completion_tokens`, `service_tier`, `parallel_tool_calls`, `functions`** — each a 422 by name | all accepted |
60
+ | deprecated-but-accepted | `frequency_penalty`, `presence_penalty` — **no effect, never an error** | still honoured |
61
+ | ignored-but-accepted | `temperature`, `top_p` while thinking is on — **no effect, never an error** | honoured |
62
+ | beta-only | assistant `prefix: true`, `strict: true` tools, FIM `/beta/completions` | n/a |
63
+ | tools + history | **400** unless every prior assistant turn carries back `reasoning_content` | n/a |
64
+ | model row | `{id, object, owned_by}` — **no `created`** | includes `created` |
65
+ | Files API | **images only** (JPEG/PNG/GIF/WebP, ≤64 MiB), `purpose: user_data` | any purpose incl. `batch`, `assistants` |
66
+ | second surface | an **Anthropic-compatible** API at `/anthropic` | n/a |
67
+ | third surface | a **Responses API** at `/responses` with its own protocol (input/output items, semantic SSE) | `/v1/responses` |
68
+
69
+ The inverse mistake is modeled too: a twin that *rejected* what DeepSeek deprecates-but-accepts
70
+ would be just as unfaithful, so `deepseek.chat.deprecated_params_accepted` and
71
+ `deepseek.chat.temperature_ignored_while_thinking` assert those requests still return **200** with
72
+ byte-identical content.
73
+
74
+ ## The context cache is real state, not a fabricated number
75
+
76
+ Every DeepSeek completion reports how many input tokens hit its KV cache. A twin has two options:
77
+ invent a split (a lie the caller cannot detect), or keep the ledger. This twin keeps the ledger, in
78
+ the same append-only kernel log as everything else (`deepseek-cache.ts`):
79
+
80
+ - after serving a request the twin records two **cache prefix units** — the caller's messages
81
+ (user-input end) and those plus the assistant turn (model-output end), which is exactly where the
82
+ vendor documents its own units being cut;
83
+ - a later request hits on the longest recorded unit that is a full prefix of its own message list,
84
+ and those tokens are `prompt_cache_hit_tokens`.
85
+
86
+ So a genuine conversation continuation genuinely reports a hit, an unrelated prompt genuinely
87
+ reports a full miss, and `hit + miss === prompt_tokens` is structural rather than clamped. What is
88
+ **not** modeled is filed rather than faked: the vendor also cuts units at "fixed token intervals"
89
+ inside long inputs but publishes no interval (`deepseek.cache.interval_units`, todo), and its cache
90
+ auto-clears "within hours to days", which the twin does not do yet (`deepseek.cache.expiry`, a
91
+ **todo** — the kernel's world clock is deterministic by construction and is explicitly the seam TTL
92
+ logic reads at serve time, so this is unbuilt rather than unbuildable).
93
+
94
+ ## The generative-stub design (be honest)
95
+
96
+ A twin cannot run the model, and that is an **invariant, not a gap**: a realism upgrade that costs
97
+ determinism is not an upgrade. So the generated strings are deterministic, clearly labeled stubs —
98
+ `[twin-stub:<model>]` in the content, in `reasoning_content`, and in the FIM continuation — and
99
+ everything around them is vendor-faithful: the response envelope, the SSE chunk sequence (reasoning
100
+ deltas before text deltas, an opt-in empty-choices usage tail), `tool_calls`, `finish_reason`, the
101
+ KV-cache usage split, and the `fp_…_kvcache`-shaped `system_fingerprint`.
102
+
103
+ The whole serve path is a pure function of (request, stored state): the ids, the fingerprint, the
104
+ cache split and the logprob values are all derived, never clocked or randomised, so a replay is
105
+ byte-identical (`deepseek.usage.serve_path_determinism`).
106
+
107
+ ## Scenario scripting (twin-only)
108
+
109
+ When a flow under test needs specific model output, script it: a JSON handler file in the world dir
110
+ (`handlers/deepseek.json`), run by the ONE kernel scenario engine with this pack's adapter.
111
+
112
+ ```jsonc
113
+ { "handlers": [
114
+ { "on": { "userTextIncludes": "summarize", "hasTool": "search_docs" },
115
+ "respond": { "text": "Scripted summary.", "reasoning": "Scripted chain of thought." } },
116
+ { "on": { "thinkingEquals": "disabled" }, "respond": { "text": "Fast path." } },
117
+ { "on": { "userTextIncludes": "broke" }, "respond": { "error": { "type": "insufficient_balance" } } }
118
+ ] }
119
+ ```
120
+
121
+ Matchers: `modelEquals`, `userTextIncludes`, `anyTextIncludes`, `hasTool`, `toolResultFor`,
122
+ `lastMessageIsToolResult`, `thinkingEquals`, `nthCall`. Scriptable failures map onto DeepSeek's own
123
+ statuses: `rate_limit_exceeded` (429), `insufficient_balance` (402), `internal_server_error` (500),
124
+ `server_overloaded` (503). Load is **strict and loud** — a mis-typed rule throws at startup rather
125
+ than silently falling back to the stub. Scenario support is twin-only scaffolding, so it is
126
+ deliberately **absent from the capability manifest** and gated by `deepseek-scenario.test.ts`
127
+ instead.
128
+
129
+ Read doors (read-only): `GET /twin` (the manifest, explaining the handler grammar) and
130
+ `GET /twin/scenario` (handlers, matches, recent misses).
131
+
132
+ ## CLI
133
+
134
+ ```bash
135
+ world-deepseek serve [--port N] [--root DIR] [--read-only] [--scenario FILE]
136
+ world-deepseek conformance [--root DIR]
137
+ ```
138
+
139
+ ## Connector (pull / push)
140
+
141
+ `pull` mirrors the real account over an **injected** executor — models, files and the singleton user
142
+ balance — and is idempotent (a re-pull of identical state appends nothing). A refused pull **throws**
143
+ rather than folding an empty account over real observed state. The pulled balance is load-bearing: a
144
+ drained account makes the twin answer 402 exactly as the real one does.
145
+
146
+ `push` sends local deletes of **pulled** files and confirms them. Two things it deliberately will
147
+ not do: it refuses `file.create` by name (real DeepSeek's `POST /files` is multipart carrying image
148
+ bytes the twin does not store), and it refuses to address the real account by the twin's own minted
149
+ id. The context-cache ledger is twin-internal and is skipped by name, reported separately from real
150
+ gaps rather than mixed into them.
151
+
152
+ Every live call goes through **one guarded client** with a persistent, fail-closed spend ledger
153
+ (`deepseek-budget.ts`). DeepSeek publishes **no scalar rate limit** — only per-model concurrency
154
+ ceilings, which bound calls in flight rather than per minute — so the declaration is pinned at the
155
+ kernel fallback (30 calls/minute) and buys resolution downward only; that is stated in its `reason`
156
+ rather than dressed up as a vendor fact.
157
+
158
+ ## Coverage
159
+
160
+ **Partial and honest.** The capability manifest is the *real DeepSeek surface* as the denominator,
161
+ enumerated top-down from the docs nav and cross-checked against the SDK's own schemas — not a list
162
+ of what was built. The measurement lives in the repo-root coverage table (README.md /
163
+ ../../../docs/contributing/conformance.md, regenerated by `bun scripts/twin-capabilities.ts --write-docs`); run
164
+ `bun scripts/manifest-baseline-one.ts deepseek` for this pack alone.
165
+
166
+ A note on the ratio: this pack reads higher than a brand-new twin usually does, and that is a fact
167
+ about the vendor rather than a thin denominator. DeepSeek's entire published API is five endpoints
168
+ (`/chat/completions`, `/beta/completions`, `/models`, `/user/balance`, `/files`) plus an
169
+ Anthropic-compatible mirror — there is no Stripe-sized resource tree to be 12% of. The remaining
170
+ `todo`s are real surface: the whole **Responses API** (`POST /responses` — a first-class entry in
171
+ DeepSeek's own reference nav, and a different protocol from chat completions: input items in, output
172
+ items out, semantic SSE, a built-in server-side `web_search` tool, and a `text.format` that DOES
173
+ take a json_schema), the whole Anthropic-compatible API, image/vision inputs, FIM streaming,
174
+ strict-mode schema enforcement, storage quotas, and the connector gaps filed in `pull-audit.json`.
175
+
176
+ ### No UI mirror
177
+
178
+ DeepSeek is an API-first vendor: an integrator POSTs `/chat/completions` from
179
+ code, and platform.deepseek.com is a keys/billing/usage console — incidental tooling, not where the
180
+ work happens. So this pack ships no `client/` mirror and declares no UI capabilities.
181
+
182
+ ### What this twin does not run, and what is planned
183
+
184
+ A local twin runs no model weights, so the completion is a deterministic labeled stub under a
185
+ faithful envelope; the chain of thought is the same, served in the faithful `reasoning_content`
186
+ field at the faithful stream position, and the beta fill-in-the-middle endpoint likewise. Log
187
+ probabilities are an output of the forward pass: on `/chat/completions` the twin serves the faithful
188
+ two-channel block with deterministic derived values, and on `/beta/completions` it leaves the
189
+ block's four arrays empty rather than synthesising per-token numbers for text it did not generate —
190
+ nothing asserts the numbers mean anything. Concurrency ceilings are a property of the vendor's
191
+ serving fleet; a single-process local twin has nothing to contend for, and DeepSeek publishes no
192
+ per-minute rate a client-side budget could reproduce.
193
+
194
+ Planned: `deepseek.files.binary_content` — the twin records upload metadata and byte counts
195
+ faithfully but stores no bytes, and the connector refuses to push a file create rather than
196
+ fabricate a multipart body. Also `deepseek.usage.real_tokenizer` (a BPE tokenizer is a data file
197
+ that runs offline and is deterministic) and `deepseek.cache.expiry` (the kernel's world clock is
198
+ deterministic by construction and is explicitly the seam TTL logic reads at serve time).
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/env node
2
+ import { keepProcessAlive } from '@volter/world-core/lifecycle';
3
+ // world-deepseek CLI: serve the DeepSeek API twin or run conformance. DeepSeek is an API-first vendor —
4
+ // its console is a keys/usage/playground dev console, not where the work happens
5
+ // (docs/contributing/architecture.md C1b) — so this pack ships no mirror.
6
+ import { hasFlag, optionValue } from '@volter/world-core/args';
7
+ import { createDeepSeekTwinServer } from "./deepseek-server.js";
8
+ const [cmd, ...rest] = process.argv.slice(2);
9
+ const port = Number(optionValue(rest, '--port', '0')) || undefined;
10
+ const root = optionValue(rest, '--root') || undefined;
11
+ const readOnly = hasFlag(rest, '--read-only'); // a twin accepts writes unless started read-only
12
+ const scenario = optionValue(rest, '--scenario') || undefined; // scripted completions (JSON file)
13
+ if (cmd === 'serve') {
14
+ const s = await createDeepSeekTwinServer({ readOnly, ...(root ? { root } : {}), ...(port ? { port } : {}), ...(scenario ? { scenarioPath: scenario } : {}) });
15
+ process.stdout.write(`deepseek twin (DeepSeek Platform API, no /v1 segment; model output is a deterministic stub)${readOnly ? ' [read-only]' : ''}${scenario ? ` [scenario: ${scenario}]` : ''} at http://127.0.0.1:${s.port}\n`);
16
+ await keepProcessAlive();
17
+ }
18
+ else if (cmd === 'conformance') {
19
+ // dev-only; lazy so the bin runs without @volter/world-tooling
20
+ const { checkDeepSeekConformance } = await import("./deepseek-conformance.js");
21
+ const report = await checkDeepSeekConformance({ ...(root ? { root } : {}) });
22
+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
23
+ if (!report.ok)
24
+ process.exitCode = 1;
25
+ }
26
+ else {
27
+ process.stdout.write('Usage: world-deepseek serve|conformance [--port N] [--root DIR] [--read-only] [--scenario FILE]\n');
28
+ }
@@ -0,0 +1,51 @@
1
+ import { RateBudget, type RateBudgetDeclaration, type RateBudgetOptions, type RateBudgetReservation, type RateBudgetSnapshot } from '@volter/world-core';
2
+ /** Rolling window, in ms. Spend older than this is pruned. */
3
+ export declare const DEEPSEEK_BUDGET_WINDOW_MS = 60000;
4
+ /**
5
+ * Weighted units allowed inside one window. 60/60s at `defaultWeight` 2 = 30 calls a minute —
6
+ * EXACTLY the kernel's undeclared fallback, because DeepSeek publishes no scalar that would justify
7
+ * more. See the header.
8
+ */
9
+ export declare const DEEPSEEK_BUDGET_CEILING = 60;
10
+ /** Seconds. A `retry-after` above this means the key is throttled hard — fail loudly, don't sleep. */
11
+ export declare const DEEPSEEK_BUDGET_MAX_RETRY_AFTER_S = 300;
12
+ /** Per-call cost, keyed by `"<METHOD> <path>"`. See the header for what is documented vs. judged. */
13
+ export declare const DEEPSEEK_CALL_WEIGHTS: {
14
+ /** `/chat/completions`, `/beta/chat/completions`, `/beta/completions` — TOKEN-metered and
15
+ * token-billed, so one call spends far more of an account's real allowance than a list poll.
16
+ * At 60/6 that is at most 10 inference calls a window. */
17
+ readonly inference: 6;
18
+ /** Everything else: files list/upload/retrieve/delete, models, user balance. */
19
+ readonly other: 2;
20
+ };
21
+ /** THE PACK'S DECLARATION — pure data, the only DeepSeek-specific thing in the whole budget. */
22
+ export declare const DEEPSEEK_RATE_BUDGET: RateBudgetDeclaration;
23
+ /**
24
+ * Price one call. The key is `"<METHOD> <path>"` with the query string split off, so a rule can
25
+ * price by method (a write is not a read) without the kernel knowing anything about DeepSeek. An
26
+ * unclassified endpoint still costs `defaultWeight` — nothing is ever free.
27
+ */
28
+ export declare function deepseekCallWeight(method: string, path: string): number;
29
+ /** Where DeepSeek's ledger lives. Token-keyed and cwd-independent by default (DeepSeek's limits are per
30
+ * ORGANIZATION, i.e. per key, so a cwd-scoped ledger would hand the same key a fresh allowance in
31
+ * every checkout, worktree and CI matrix leg); pass `root` for world-scoped accounting. */
32
+ export declare function deepseekBudgetPath(opts?: {
33
+ root?: string;
34
+ token?: string;
35
+ } | string): string;
36
+ /** Construction options for DeepSeek's budget. The vendor is fixed; everything else may only TIGHTEN. */
37
+ export type DeepSeekBudgetOptions = Omit<RateBudgetOptions, 'vendor'>;
38
+ /**
39
+ * DeepSeek's budget — the shared kernel guard bound to this vendor's declaration. A real subclass, not
40
+ * an alias, so `budget instanceof DeepSeekBudget` in `liveDeepSeekExecute` means "a budget that accounts
41
+ * against DEEPSEEK's ledger under DEEPSEEK's ceiling".
42
+ */
43
+ export declare class DeepSeekBudget extends RateBudget {
44
+ constructor(opts?: DeepSeekBudgetOptions);
45
+ }
46
+ /** The typed refusal. One error class shared with every other vendor's budget; `err.vendor` says
47
+ * which one refused, and `err.kind` says why. */
48
+ export { RateBudgetError as DeepSeekBudgetError } from '@volter/world-core';
49
+ export type { RateBudgetErrorKind as DeepSeekBudgetErrorKind } from '@volter/world-core';
50
+ export type DeepSeekBudgetReservation = RateBudgetReservation;
51
+ export type DeepSeekBudgetSnapshot = RateBudgetSnapshot;
@@ -0,0 +1,152 @@
1
+ // DeepSeek's CLIENT-SIDE RATE BUDGET — the pack's DECLARATION (the numbers) plus the thin typed
2
+ // bindings `liveDeepSeekExecute` uses. The MECHANISM — the durable token-keyed ledger, the rolling
3
+ // window, reserve-under-lock, the `Retry-After`/429 cooldown, fail-CLOSED on a corrupt ledger —
4
+ // lives ONCE in the vendor-agnostic kernel (`@volter/world-core` → `rateBudget.ts`). Read that module's
5
+ // header for the full rationale AND for the honest list of what the guard does not guarantee.
6
+ //
7
+ // ── WHY THIS EXISTS ─────────────────────────────────────────────────────────────────────────
8
+ // A real ~4.5-DAY vendor lockout (Figma, 2026-07-25) happened because raw API calls were made
9
+ // outside the pack's connector — no cache, no batching, no ceiling. Discipline only binds the code
10
+ // that follows it; a BUDGET binds the code that does not.
11
+ //
12
+ // ── HOW THE CEILING WAS CHOSEN (live-read, 2026-08-31) ──────────────────────────────────────
13
+ // https://api-docs.deepseek.com/quick_start/rate_limit (read 2026-08-31) publishes NO scalar
14
+ // per-minute or per-day request allowance at all. What it publishes is a CONCURRENCY table —
15
+ // deepseek-v4-pro 500, deepseek-v4-flash 2500, deepseek-v4-flash-vision-exp 2500 simultaneous
16
+ // connections per account — plus the note that "if you need higher concurrency, you can submit a
17
+ // capacity expansion request". Concurrency is not a rate: it bounds how many calls are in flight,
18
+ // not how many are made per minute, so nothing on that page can be turned into a window ceiling.
19
+ // (This figure was live-fetched for THIS build. The copied-exemplar hazard ADDING_A_TWIN.md §0.5
20
+ // warns about is real: the pack this one was cloned from asserted GroqCloud's eight-dimension
21
+ // RPM/RPD/TPM/ASH scheme, which DeepSeek does not have at all.)
22
+ //
23
+ // So — exactly as ADDING_A_TWIN.md directs when a vendor publishes no scalar limit ("say exactly
24
+ // that in `reason` and stay at or under the fallback") — this declaration is pinned at the kernel's
25
+ // undeclared fallback in every dimension: window 60s, ceiling 60, defaultWeight 2, i.e. 30
26
+ // calls/minute, EXACTLY `DEFAULT_RATE_BUDGET`, with no endpoint priced cheaper than the fallback
27
+ // would price it. What the declaration buys is RESOLUTION, and it buys it DOWNWARD only.
28
+ //
29
+ // It bounds the 60s AVERAGE; it does not pace (the kernel refuses, it never sleeps). The backstop
30
+ // for a sub-second burst is the cooldown: a `retry-after` read off a real 429 turns into a
31
+ // persisted refusal.
32
+ //
33
+ // ── HOW THE WEIGHTS WERE CHOSEN (and what is a judgement call) ───────────────────────────────
34
+ // • `/chat/completions`, `/beta/chat/completions` and `/beta/completions` cost 6. DeepSeek prices
35
+ // and meters these by TOKENS, not requests (api-docs.deepseek.com/quick_start/pricing bills
36
+ // input cache-hit / cache-miss / output tokens), so one inference request consumes far more of
37
+ // an account's real allowance than a file-list poll. 60/6 = at most 10 inference calls a window.
38
+ // That factor is a judgement call, not a vendor figure — it is deliberately the STRICT
39
+ // direction, which needs no vendor justification; being looser would, and there is none to have.
40
+ // • Everything else (files, models, balance) costs 2 — the fallback's own default.
41
+ //
42
+ // ── AN HONEST NOTE ON THE INFERENCE RULE ────────────────────────────────────────────────────
43
+ // This pack's connector pulls models, files and the account balance; it NEVER issues live
44
+ // inference, because a twin does not run the model anywhere — local or remote (CLAUDE.md,
45
+ // serve-path determinism). `liveDeepSeekExecute`'s path allowlist refuses `/chat/completions`
46
+ // outright. So the `inference: 6` rule is DEFENCE IN DEPTH, not a live pricing path, and the pack
47
+ // claims exactly that: `deepseek.rate_limits.inference_costs_more` asserts the pure pricing
48
+ // function, `deepseek.rate_limits.executor_path_allowlist` asserts the refusal, and no capability
49
+ // claims a live inference call was ever budgeted.
50
+ import { declareRateBudget, rateBudgetPath, rateBudgetWeight, RateBudget, } from '@volter/world-core';
51
+ const VENDOR = 'deepseek';
52
+ /** Rolling window, in ms. Spend older than this is pruned. */
53
+ export const DEEPSEEK_BUDGET_WINDOW_MS = 60_000;
54
+ /**
55
+ * Weighted units allowed inside one window. 60/60s at `defaultWeight` 2 = 30 calls a minute —
56
+ * EXACTLY the kernel's undeclared fallback, because DeepSeek publishes no scalar that would justify
57
+ * more. See the header.
58
+ */
59
+ export const DEEPSEEK_BUDGET_CEILING = 60;
60
+ /** Seconds. A `retry-after` above this means the key is throttled hard — fail loudly, don't sleep. */
61
+ export const DEEPSEEK_BUDGET_MAX_RETRY_AFTER_S = 300;
62
+ /** Per-call cost, keyed by `"<METHOD> <path>"`. See the header for what is documented vs. judged. */
63
+ export const DEEPSEEK_CALL_WEIGHTS = {
64
+ /** `/chat/completions`, `/beta/chat/completions`, `/beta/completions` — TOKEN-metered and
65
+ * token-billed, so one call spends far more of an account's real allowance than a list poll.
66
+ * At 60/6 that is at most 10 inference calls a window. */
67
+ inference: 6,
68
+ /** Everything else: files list/upload/retrieve/delete, models, user balance. */
69
+ other: 2,
70
+ };
71
+ /** THE PACK'S DECLARATION — pure data, the only DeepSeek-specific thing in the whole budget. */
72
+ export const DEEPSEEK_RATE_BUDGET = {
73
+ windowMs: DEEPSEEK_BUDGET_WINDOW_MS,
74
+ ceiling: DEEPSEEK_BUDGET_CEILING,
75
+ defaultWeight: DEEPSEEK_CALL_WEIGHTS.other,
76
+ maxRetryAfterSeconds: DEEPSEEK_BUDGET_MAX_RETRY_AFTER_S,
77
+ rules: [
78
+ // Anchored on DeepSeek's REAL paths — there is no `/v1` segment on this vendor. The optional
79
+ // `/beta` prefix is part of the pattern because the beta base URL reaches the SAME priced
80
+ // inference endpoints; a rule that missed it would price a beta chat call as a 2-unit read.
81
+ { match: '^POST (/beta)?/chat/completions$', weight: DEEPSEEK_CALL_WEIGHTS.inference },
82
+ { match: '^POST /beta/completions$', weight: DEEPSEEK_CALL_WEIGHTS.inference },
83
+ ],
84
+ reason: 'DeepSeek publishes NO scalar request-rate limit at all (api-docs.deepseek.com/quick_start/rate_limit, ' +
85
+ 'read 2026-08-31). The only figures on that page are CONCURRENCY limits — deepseek-v4-pro 500, ' +
86
+ 'deepseek-v4-flash 2500, deepseek-v4-flash-vision-exp 2500 simultaneous connections per account, ' +
87
+ 'with a capacity-expansion request available for more — and concurrency bounds calls in flight, ' +
88
+ 'not calls per minute, so it cannot be turned into a window ceiling. Because no published figure ' +
89
+ 'justifies going higher, the ceiling is pinned at the kernel fallback in every dimension: 60 units ' +
90
+ '/ 60s at defaultWeight 2 = 30 calls/min, identical to DEFAULT_RATE_BUDGET. The declaration buys ' +
91
+ 'resolution DOWNWARD, never headroom: inference (POST /chat/completions, POST /beta/chat/completions, ' +
92
+ 'POST /beta/completions) costs 6, so at most 10 land in a window, because DeepSeek bills those ' +
93
+ 'endpoints by token (input cache-hit / cache-miss / output) rather than by request. That factor is ' +
94
+ 'a judgement call in the strict direction, not a vendor figure. The window bounds the 60s AVERAGE ' +
95
+ 'and does not pace; a `retry-after` read off a real 429 is the persisted cooldown backstop.',
96
+ };
97
+ // Declared at module load, so merely importing this module (which `deepseek-connector.ts` does) is
98
+ // enough to arm the real ceiling.
99
+ declareRateBudget(VENDOR, DEEPSEEK_RATE_BUDGET);
100
+ /**
101
+ * Price one call. The key is `"<METHOD> <path>"` with the query string split off, so a rule can
102
+ * price by method (a write is not a read) without the kernel knowing anything about DeepSeek. An
103
+ * unclassified endpoint still costs `defaultWeight` — nothing is ever free.
104
+ */
105
+ export function deepseekCallWeight(method, path) {
106
+ const { bare, query } = splitQuery(path);
107
+ // UPPER-CASE the method: `fetch` normalizes a known lowercase method before sending, so
108
+ // `execute('post', …)` really does issue a POST and must be priced as one.
109
+ return rateBudgetWeight(VENDOR, `${String(method).toUpperCase()} ${bare}`, query);
110
+ }
111
+ /**
112
+ * `/chat/completions?a=1` -> `{ bare: '/chat/completions', query: { a: '1' } }`. Rules match the path;
113
+ * `whenQuery*` the query. NORMALIZED, because the anchored rules are otherwise trivially evaded:
114
+ * `fetch` upper-cases a known method before sending, so `execute('post', …)` issues a real WRITE
115
+ * that a `^POST ` rule would price as a read; and a trailing slash makes a path miss a `$` anchor
116
+ * while most routers treat it as the same endpoint.
117
+ */
118
+ function splitQuery(path) {
119
+ const at = path.indexOf('?');
120
+ const query = {};
121
+ if (at !== -1)
122
+ for (const [k, v] of new URLSearchParams(path.slice(at + 1)))
123
+ query[k] = v;
124
+ // Collapse REPEATED slashes as well as a trailing one: `//chat/completions` reaches the same
125
+ // endpoint on most routers but misses a `^POST (/beta)?/chat/completions$` rule, which would
126
+ // price an inference call as a 2-unit read.
127
+ const raw = (at === -1 ? path : path.slice(0, at)).replace(/\/{2,}/g, '/');
128
+ const bare = raw.length > 1 && raw.endsWith('/') ? raw.replace(/\/+$/, '') : raw;
129
+ return { bare, query };
130
+ }
131
+ /** Where DeepSeek's ledger lives. Token-keyed and cwd-independent by default (DeepSeek's limits are per
132
+ * ORGANIZATION, i.e. per key, so a cwd-scoped ledger would hand the same key a fresh allowance in
133
+ * every checkout, worktree and CI matrix leg); pass `root` for world-scoped accounting. */
134
+ export function deepseekBudgetPath(opts = {}) {
135
+ const o = typeof opts === 'string' ? { root: opts } : opts;
136
+ // VENDOR spread LAST: a loosely-typed `{ vendor: 'other', … }` slipping through (TypeScript's
137
+ // excess-property check only catches object literals) must not redirect this pack's ledger.
138
+ return rateBudgetPath({ ...o, vendor: VENDOR });
139
+ }
140
+ /**
141
+ * DeepSeek's budget — the shared kernel guard bound to this vendor's declaration. A real subclass, not
142
+ * an alias, so `budget instanceof DeepSeekBudget` in `liveDeepSeekExecute` means "a budget that accounts
143
+ * against DEEPSEEK's ledger under DEEPSEEK's ceiling".
144
+ */
145
+ export class DeepSeekBudget extends RateBudget {
146
+ constructor(opts = {}) {
147
+ super({ ...opts, vendor: VENDOR });
148
+ }
149
+ }
150
+ /** The typed refusal. One error class shared with every other vendor's budget; `err.vendor` says
151
+ * which one refused, and `err.kind` says why. */
152
+ export { RateBudgetError as DeepSeekBudgetError } from '@volter/world-core';