@volter/twin-openai 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.
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,168 @@
1
+ # @volter/twin-openai
2
+
3
+ A local, faithful **OpenAI API** twin your real `openai` SDK talks to unmodified — point the
4
+ SDK at the twin's `baseURL` and `chat.completions.create`, streaming, the Responses API,
5
+ `embeddings`, `models`, `moderations`, `files`, `batches`, fine-tuning jobs, and vector stores
6
+ all work. Built on the shared `@volter/twin` kernel (durable event/action log + projection);
7
+ no parallel side store.
8
+
9
+ ```ts
10
+ import OpenAI from 'openai';
11
+ import { createOpenAITwinServer } from '@volter/twin-openai';
12
+
13
+ const { port } = createOpenAITwinServer({});
14
+ const client = new OpenAI({ apiKey: 'sk-twin', baseURL: `http://127.0.0.1:${port}/v1` });
15
+ const res = await client.chat.completions.create({
16
+ model: 'gpt-4o',
17
+ messages: [{ role: 'user', content: 'hello' }],
18
+ });
19
+ // res.choices[0].message.content starts with "[twin-stub:…]" — a deterministic stub, clearly labeled.
20
+ ```
21
+
22
+ ## The generative-stub design (be honest)
23
+
24
+ The twin **cannot run the model** — there are no weights here. So `POST /v1/chat/completions`
25
+ and `POST /v1/responses` return a **deterministic STUB completion** that is unmistakably a twin
26
+ stub (it carries a `[twin-stub:<model>]` marker and echoes your prompt), and `POST /v1/embeddings`
27
+ returns **deterministic pseudo-vectors** (seeded from the input hash). They **never** pretend to
28
+ be real model output / real embedding values.
29
+
30
+ What **is** faithful is the **entire protocol envelope**:
31
+
32
+ - chat response shape — `{ id:'chatcmpl-…', object:'chat.completion', created, model, choices:[{index, message:{role:'assistant', content}, finish_reason}], usage:{prompt_tokens, completion_tokens, total_tokens}, system_fingerprint }`
33
+ - **streaming** via SSE — real `data: {…chat.completion.chunk with choices[].delta…}` chunks ending with `data: [DONE]` (role chunk → content/tool_call deltas → finish_reason chunk; driven through an injected sink — no real sockets in the handler)
34
+ - **tool / function calling** — `tool_calls` + `finish_reason:'tool_calls'` (and legacy `functions`)
35
+ - `n`, `max_tokens` / `max_completion_tokens`, `stop`, `temperature`/`top_p` accepted; **deterministic usage**
36
+ - **Responses API** — `POST /v1/responses` (`{ id:'resp_…', object:'response', output:[{type:'message', content:[{type:'output_text', text}]}], usage }`) + streaming events (`response.created` → `response.output_text.delta` → `response.completed` → `[DONE]`)
37
+ - **Embeddings** — `{ object:'list', data:[{object:'embedding', index, embedding:[…]}], model, usage }` with faithful, L2-normalized, deterministic vectors (length controlled by `dimensions`)
38
+
39
+ The genuinely **stateful + static** surface is real, not a stub:
40
+
41
+ - `GET /v1/models` (+ `/v1/models/:id`) — static catalog
42
+ - **Files** — `POST/GET/DELETE /v1/files` (+ list + `/content`), kernel-backed
43
+ - **Batches** — `POST/GET /v1/batches` (+ list + cancel)
44
+ - **Moderations** — `POST /v1/moderations` (deterministic keyword classifier; faithful shape)
45
+ - **Fine-tuning jobs** — create / retrieve / list / cancel / events
46
+ - **Vector stores** — create / retrieve / list / delete (+ file attach/list)
47
+ - **Images** — `POST /v1/images/generations` returns the faithful response shape with a placeholder URL
48
+
49
+ Vendor-shaped errors throughout: `400 invalid_request_error` (with `message`/`type`/`param`/`code`),
50
+ `404`, `405` (read-only guard). (Auth is faked — any bearer key is accepted, like the other twins;
51
+ real `401`/`429` are modeled as `todo` capabilities, not yet built.)
52
+
53
+ ## CLI
54
+
55
+ ```
56
+ world-openai serve [--port N] [--root DIR] [--read-only] # the API twin (SDK target)
57
+ world-openai conformance [--root DIR] # offline envelope checks
58
+ ```
59
+
60
+ (OpenAI is an API-first vendor with no meaningful product UI worth mirroring — see
61
+ ARCHITECTURE.md C1b — so this pack ships **no mirror**.)
62
+
63
+ ## Connector (pull / push)
64
+
65
+ `syncOpenAIFromReal` pulls real files / batches / fine-tuning jobs / vector stores into the
66
+ twin; `pushPendingOpenAIActions` pushes pending local writes (create / cancel / delete) to the
67
+ real API and confirms them. All vendor I/O is over an **injected client**
68
+ (`liveOpenAIExecute(apiKey)` live; a fake in tests) — the pack holds no key and imports no SDK
69
+ at runtime.
70
+
71
+ ## Coverage
72
+
73
+ The capability manifest (`openai-capabilities.ts`) enumerates the **real OpenAI API surface**
74
+ as the honest denominator; `verify()` proves each `done` against the local twin, offline +
75
+ deterministically. Run `bun scripts/twin-capabilities.ts openai` for the live numbers.
76
+
77
+ ### Done (proven, verifiable)
78
+ - **Chat Completions** — create + faithful envelope, validation, labeled stub, `n` choices,
79
+ `max_tokens`/`max_completion_tokens` cap, system/developer messages, multi-turn, content-part
80
+ input, `stop`, `temperature` accepted, deterministic usage, `system_fingerprint`,
81
+ `response_format` json_object/json_schema (valid JSON content), `logprobs`+`top_logprobs`
82
+ (per-token pseudo-logprobs whose tokens re-join to the text), `seed` (distinct seed → distinct
83
+ id), `logit_bias` (accepted+validated), predicted outputs (`prediction`), `store`+`metadata`
84
+ (stored completions: retrieve / list / messages / delete)
85
+ - **Streaming** — chunk sequence + `[DONE]`, content reconstruction, `finish_reason` chunk,
86
+ tool_call deltas, `stream_options.include_usage` final usage-only chunk
87
+ - **Tools** — `tool_calls` + `finish_reason:'tool_calls'`, legacy `functions`, no-tools → text,
88
+ `tool_choice` (none/required/named), `parallel_tool_calls`, strict schema-typed arguments
89
+ - **Responses API** — create + envelope, labeled stub, input-item array, validation, streaming,
90
+ stored-by-default retrieve/delete, `previous_response_id` chaining, input-items list
91
+ - **Embeddings** — list envelope, determinism, batch, `dimensions`, L2-normalized, validation,
92
+ `encoding_format:'base64'` (Float32 base64 string decoding to the float vector)
93
+ - **Models** — list (catalog + fine-tuned), retrieve (+404 `model_not_found`), delete a fine-tuned
94
+ model (base models refuse)
95
+ - **Moderations** — faithful shape, deterministic flagging, batch
96
+ - **Files** — upload / retrieve / list / content / delete, purpose-required
97
+ - **Uploads** — create → add parts → complete (assembles a real File from the parts) / cancel
98
+ - **Batches** — create / retrieve / list / cancel, validation, persistence
99
+ - **Fine-tuning** — create / retrieve+list / events / cancel / validation / checkpoints
100
+ - **Vector stores** — create / retrieve+list+delete / file attach+list / seed file_ids,
101
+ deterministic ranked search, file batches (bulk attach + retrieve + list batch files)
102
+ - **Assistants (beta)** — assistants CRUD, threads + messages CRUD, runs (immediate stub
103
+ completion) + run steps + cancel
104
+ - **Admin / org** — projects (create/retrieve/modify/list/archive), project API keys
105
+ (create with one-time synthetic secret / list / retrieve redacted / delete), usage + costs
106
+ reporting (`/v1/organization/usage/{completions,embeddings}` + `/v1/organization/costs`,
107
+ aggregated over REAL recorded usage rows — nothing hardcoded; empty with no traffic)
108
+ - **Chat audio** — `input_audio` content parts accepted (count toward prompt_tokens), and
109
+ `modalities:['text','audio']` → an assistant `audio` envelope (id/data/transcript/expires_at);
110
+ the bytes are a labeled stub (no real speech synthesis), the shape is faithful
111
+ - **Responses reasoning** — `reasoning.effort` (minimal/low/medium/high) → a faithful reasoning
112
+ output item (labeled-stub summary) + `usage.output_tokens_details.reasoning_tokens`
113
+ - **Audio** — transcriptions (json/verbose_json/text), translations, text-to-speech (labeled stubs)
114
+ - **Images** — generations shape (placeholder), validation, edits + variations (placeholder shape)
115
+ - **Errors / protocol** — 404, `invalid_request_error` envelope, read-only 405 guard, modeled
116
+ auth (`401` on a missing/invalid credential when a request carries an auth surface; trusted
117
+ in-process + real-SDK calls pass), rate-limit `429` (deterministic opt-in trigger header →
118
+ vendor envelope + `Retry-After` + `x-ratelimit-*`), `Idempotency-Key` dedup (re-issue replays
119
+ the same response/id; a new key → a new result), cursor pagination (`after`/`limit` +
120
+ `has_more`/`first_id`/`last_id`)
121
+ - **Connector** — read surface, pull+map (offline), push+confirm (offline), unsupported-op fails,
122
+ full bi-directional sync (push-then-pull, idempotent)
123
+ - **Conformance** — offline envelope harness
124
+
125
+ ### Planned (todo — covered by default, not yet built)
126
+ - **Evals API** — create/run/list evals + eval runs + output items
127
+ - **Containers API** — containers + container files (code-interpreter sandboxes)
128
+ - **Background responses** — `background:true` → queued status + poll + cancel
129
+ - **Fine-tuning** — job pause / resume
130
+ - **Webhooks** — event signature verification (signing-secret HMAC)
131
+
132
+ ### Out of scope (the honest carve-outs)
133
+ - **`openai.chat.inference`** — *real model inference (generation from model weights).* The twin
134
+ returns a deterministic stub; the protocol envelope is faithful.
135
+ - **`openai.embeddings.real_vectors`** — *real embedding values.* The twin returns deterministic
136
+ pseudo-vectors; the shape/dimensions/determinism are faithful.
137
+ - **`openai.images.real_pixels`** — *real generated image bytes.* The response shape is faithful;
138
+ the URL is a placeholder.
139
+ - **`openai.files.real_bytes`** — *arbitrary binary blob storage.* Metadata + supplied text
140
+ content are faithful; the twin is not a binary object store.
141
+ - **`openai.responses.tools`** — *hosted built-in tools (web_search / computer_use /
142
+ code_interpreter).* These require live model + infrastructure side effects that cannot be
143
+ reproduced offline without fabricating output; user-defined function tools ARE modeled.
144
+ - **`openai.audio.realtime`** — *Realtime API (WebSocket sessions).* A live bidirectional audio
145
+ socket to a running speech model — both the transport and the inference are irreproducible in
146
+ the offline, HTTP `verify()` harness.
147
+
148
+ Everything else is covered by default and is either done or planned.
149
+
150
+ ## Rate budget — the fail-closed backstop on live calls
151
+
152
+ `liveOpenAIExecute` is the **one place** this pack issues a live request, so every call it makes is charged
153
+ against a persistent, fail-closed spend ledger **before** the request goes out. Past the ceiling, or
154
+ while a `Retry-After`/429 cooldown is armed, it **throws instead of calling**. The ledger is keyed by
155
+ vendor and a hash of the credential (limits are per credential, so it is deliberately *not*
156
+ cwd-scoped) and persists across processes, so a fresh process does not get a fresh allowance; a
157
+ corrupt ledger counts as a **full** window rather than zero spend. There is no option to disable it,
158
+ and no value you can pass for `budget` that yields an unguarded client — an injected budget is
159
+ validated by *method identity*, so a subclass or a `Proxy` that replaces `checkBudget` is refused.
160
+
161
+ The declared numbers: **60 weighted units / 60s at weight 2 = 30 calls/minute — exactly the kernel's austere fallback**, because OpenAI publishes *no* scalar per-key request limit (limits are per org/project, per model, per tier, and live only on the account's limits page). The one documented scalar that can bind this pack is Vector Store ingestion at 300 requests/minute per store. The declaration therefore buys **resolution, not headroom**: inference paths cost 5, vector-store ingestion 4, and nothing is cheaper than the fallback would price it.
162
+
163
+ The mechanism is **shared and vendor-agnostic** — it lives in the kernel (`@volter/twin` →
164
+ `control-plane/src/rateBudget.ts`); what lives here in [`src/openai-budget.ts`](src/openai-budget.ts) is this vendor's
165
+ **declaration** (window, ceiling, per-endpoint weights, and a `reason` citing the limits above) plus
166
+ the vendor-bound `OpenAIBudget`. The rule is ratified as
167
+ [ARCHITECTURE.md](../../../ARCHITECTURE.md) **D8**, and the kernel module's header documents what the
168
+ guard does *not* guarantee — read that before trusting it.
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "@volter/twin-openai",
3
+ "version": "0.1.0",
4
+ "description": "Local OpenAI twin \u2014 a faithful, stateful local OpenAI API your real `openai` SDK talks to unmodified. The model is stubbed (deterministic) and embeddings are deterministic pseudo-vectors, but the protocol envelope (chat completions/streaming/tool_calls, the Responses API, embeddings, models, files, batches, moderations, fine-tuning, vector stores) is vendor-faithful. Built on @volter/twin.",
5
+ "keywords": [
6
+ "twin",
7
+ "local",
8
+ "mock",
9
+ "mirror",
10
+ "simulator",
11
+ "fixtures",
12
+ "testing",
13
+ "sdk",
14
+ "api",
15
+ "localstack",
16
+ "openai",
17
+ "gpt",
18
+ "llm"
19
+ ],
20
+ "author": "Volter (https://github.com/volter-ai)",
21
+ "license": "Apache-2.0",
22
+ "files": [
23
+ "src",
24
+ "client",
25
+ "test-fixtures",
26
+ "README.md",
27
+ "LICENSE",
28
+ "!**/*.test.ts",
29
+ "!**/*.test.tsx"
30
+ ],
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/volter-ai/twin.git",
34
+ "directory": "packages/twin/openai"
35
+ },
36
+ "homepage": "https://github.com/volter-ai/twin/tree/main/packages/twin/openai#readme",
37
+ "type": "module",
38
+ "exports": {
39
+ ".": "./src/index.ts"
40
+ },
41
+ "bin": {
42
+ "world-openai": "src/cli.ts"
43
+ },
44
+ "scripts": {
45
+ "test": "bun test src/*.test.ts",
46
+ "typecheck": "tsc --noEmit"
47
+ },
48
+ "peerDependencies": {
49
+ "@volter/twin": "0.1.0"
50
+ },
51
+ "devDependencies": {
52
+ "@volter/twin": "workspace:*",
53
+ "@volter/twin-tooling": "workspace:*",
54
+ "openai": "^4.104.0",
55
+ "@types/bun": "^1.2.20",
56
+ "@types/node": "^24.0.0",
57
+ "typescript": "^5.9.0"
58
+ },
59
+ "engines": {
60
+ "bun": ">=1.2.0"
61
+ }
62
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env bun
2
+ import { keepProcessAlive } from '@volter/twin/lifecycle';
3
+ // world-openai CLI: serve the OpenAI API twin or run conformance. OpenAI is an API-first
4
+ // vendor with no meaningful product UI worth mirroring (ARCHITECTURE.md C1b), so this pack
5
+ // ships no mirror.
6
+ import { hasFlag, optionValue } from '@volter/twin/args';
7
+ import { createOpenAITwinServer } from './openai-server.ts';
8
+
9
+ const [cmd, ...rest] = process.argv.slice(2);
10
+ const port = Number(optionValue(rest, '--port', '0')) || undefined;
11
+ const root = optionValue(rest, '--root') || undefined;
12
+ const readOnly = hasFlag(rest, '--read-only'); // a twin accepts writes unless started read-only
13
+
14
+ if (cmd === 'serve') {
15
+ const s = createOpenAITwinServer({ readOnly, ...(root ? { root } : {}), ...(port ? { port } : {}) });
16
+ process.stdout.write(`openai twin (chat/responses/embeddings output is a deterministic stub)${readOnly ? ' [read-only]' : ''} at http://127.0.0.1:${s.port}\n`);
17
+ await keepProcessAlive();
18
+ } else if (cmd === 'conformance') {
19
+ // dev-only; lazy so the bin runs without @volter/twin-tooling
20
+ const { checkOpenAIConformance } = await import('./openai-conformance.ts');
21
+ const report = await checkOpenAIConformance({ ...(root ? { root } : {}) });
22
+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
23
+ if (!report.ok) process.exitCode = 1;
24
+ } else {
25
+ process.stdout.write('Usage: world-openai serve|conformance [--port N] [--root DIR] [--read-only]\n');
26
+ }
package/src/index.ts ADDED
@@ -0,0 +1,108 @@
1
+ // @volter/twin-openai — the OpenAI twin (one vendor, one package), built on the shared
2
+ // @volter/twin kernel. The OpenAI API: a vendor-faithful protocol envelope (chat
3
+ // completions/streaming/tool_calls, the Responses API, embeddings), a static models catalog,
4
+ // deterministic moderations, and STATEFUL files / batches / fine-tuning jobs / vector stores —
5
+ // over an event/action log. (OpenAI is an API-first vendor with no meaningful product UI worth
6
+ // mirroring — ARCHITECTURE.md C1b — so this pack ships no mirror.)
7
+ //
8
+ // THE HONEST CARVE-OUTS: the twin cannot run the model, so POST /v1/chat/completions and
9
+ // /v1/responses return a DETERMINISTIC STUB completion (clearly labeled), and /v1/embeddings
10
+ // returns DETERMINISTIC pseudo-vectors — never pretending to be real inference. Everything
11
+ // around them — the wire protocol — is faithful. (Conformance + capability tooling live in
12
+ // @volter/twin-tooling, a dev dependency — NOT re-exported here, per E2.)
13
+ export { handleOpenAITwinRequest, streamChat, streamResponse } from './openai-twin.ts';
14
+ export type { OpenAIRequest, OpenAIResponseEnvelope } from './openai-twin.ts';
15
+ export { createOpenAITwinFetch, createOpenAITwinServer } from './openai-server.ts';
16
+ export type { OpenAITwinFetchOptions } from './openai-server.ts';
17
+ export { OPENAI_MODELS, findModel } from './openai-models.ts';
18
+ export type { OpenAIModel } from './openai-models.ts';
19
+ export {
20
+ countPromptTokens, estimateTokens, stubAssistantText, stubToolCall, contentToText, lastUserText,
21
+ pseudoEmbedding, moderateText, MODERATION_CATEGORIES,
22
+ } from './openai-stub.ts';
23
+ export type { ModerationResult } from './openai-stub.ts';
24
+ export type {
25
+ ChatMessageParam, ChatToolCall, ChatCompletion, ChatChoice, ChatUsage,
26
+ OpenAIResponse, EmbeddingResponse, Embedding, OpenAIError, SseEvent, SseSink,
27
+ } from './openai-types.ts';
28
+ export {
29
+ openaiRequestForAction,
30
+ liveOpenAIExecute,
31
+ mapFile,
32
+ mapBatch,
33
+ mapFineTune,
34
+ mapVectorStore,
35
+ pullOpenAIState,
36
+ pushOpenAIAction,
37
+ pushPendingOpenAIActions,
38
+ syncOpenAIFromReal,
39
+ fullSyncOpenAI,
40
+ } from './openai-connector.ts';
41
+ export type { OpenAIExecute, LiveOpenAIOptions } from './openai-connector.ts';
42
+ // The client-side rate budget — the fail-closed backstop `liveOpenAIExecute` routes every live
43
+ // request through. The MECHANISM is the kernel's shared, vendor-agnostic `RateBudget`; what lives
44
+ // here is OpenAI's DECLARATION (window/ceiling/per-endpoint weights) plus the vendor-bound
45
+ // bindings. Exported so an operator can inspect spend (`snapshot`) and so a caller can catch
46
+ // `OpenAIBudgetError` by type; there is deliberately no export that disables the guard.
47
+ export {
48
+ OPENAI_BUDGET_CEILING,
49
+ OPENAI_BUDGET_MAX_RETRY_AFTER_S,
50
+ OPENAI_BUDGET_WINDOW_MS,
51
+ OPENAI_CALL_WEIGHTS,
52
+ OPENAI_RATE_BUDGET,
53
+ OpenAIBudget,
54
+ OpenAIBudgetError,
55
+ openaiBudgetPath,
56
+ openaiCallWeight,
57
+ } from './openai-budget.ts';
58
+ export type { OpenAIBudgetErrorKind, OpenAIBudgetOptions, OpenAIBudgetReservation, OpenAIBudgetSnapshot } from './openai-budget.ts';
59
+ export {
60
+ verifyOpenAIWebhook,
61
+ computeOpenAIWebhookSignature,
62
+ buildSignedOpenAIWebhook,
63
+ OpenAIWebhookVerificationError,
64
+ OPENAI_WEBHOOK_EVENT_TYPES,
65
+ } from './openai-webhooks.ts';
66
+ export type { OpenAIWebhookEvent } from './openai-webhooks.ts';
67
+
68
+ // Registry descriptor: the pack self-describes so tooling can discover it.
69
+ import type { TwinPack } from '@volter/twin';
70
+ import { OPENAI_RATE_BUDGET as RATE_BUDGET } from './openai-budget.ts';
71
+ export const pack: TwinPack = {
72
+ vendor: 'openai',
73
+ // The SAME object openai-budget.ts declares at module load — one source of truth, so registering
74
+ // the pack and importing the connector can never arm two different ceilings.
75
+ rateBudget: RATE_BUDGET,
76
+ transport: 'rest',
77
+ archetype: 'generative',
78
+ bin: 'world-openai',
79
+ resources: ['file', 'batch', 'fine_tuning_job', 'vector_store', 'vector_store_file', 'response'],
80
+ specSource: 'OpenAI API (envelope-faithful; model output is a deterministic stub, embeddings are deterministic pseudo-vectors)',
81
+ description: 'OpenAI API twin — faithful protocol envelope (chat completions/streaming/tool_calls, Responses API, embeddings), models, moderations, stateful files/batches/fine-tuning/vector stores; generative output is a labeled stub.',
82
+ // Adoption + interception, all in the pack's one home (TWIN-PACK-CONTRACT back-migration
83
+ // 2026-08-31; the bare `openai` stem and both SDK names moved off the central maps unchanged).
84
+ // The stems are the bare OPENAI_* pair plus the credential-var shapes real apps use beside it
85
+ // (AP_OPENAI_*, OPENAI_MODERATION_*).
86
+ adoption: {
87
+ // OpenAI's official Python library and Agents SDK. THE DISTRIBUTION IS THE CLAIM: `openai` stays
88
+ // this pack's even when a caller points it at DeepSeek, xAI, OpenRouter, Perplexity, an AI Gateway
89
+ // or an Azure OpenAI endpoint - those packs claim the ENDPOINT ENV that routes it, never this name.
90
+ // `tiktoken` is deliberately UNCLAIMED: it is a local tokenizer that makes no API call at all.
91
+ pypi: ['openai', 'openai-agents'],
92
+ sdks: ['openai', '@ai-sdk/openai'],
93
+ // 'REWORKDPLATFORMOPENAI' — AgentGPT names its key REWORKD_PLATFORM_OPENAI_API_KEY, the same
94
+ // app-prefixed shape as APOPENAI (ladder classification 2026-09-02). Deliberately NOT
95
+ // 'OPENAIOAUTH': postiz's OPENAI_OAUTH_CLIENT_ID is the client id its own MCP OAuth SERVER
96
+ // accepts from the ChatGPT connector — inbound, no api.openai.com call — so it is ruled
97
+ // not-a-vendor in the packless registry instead.
98
+ envStems: ['OPENAI', 'APOPENAI', 'OPENAIMODERATION', 'REWORKDPLATFORMOPENAI'],
99
+ },
100
+ // The whole REST surface the `openai` SDK talks to uses one base, https://api.openai.com — the
101
+ // same default the pack's own connector pins (openai-connector.ts).
102
+ hosts: [{ host: 'api.openai.com' }],
103
+ // The SDK calls the same-origin '/v1/…' and loads from api.openai.com — the dev proxy
104
+ // forwards '/v1/' to the twin and strips the absolute host so calls come back same-origin.
105
+ browserRouting: { apiPathPrefix: '/v1/', loaderHost: 'https://api.openai.com' },
106
+ };
107
+ export { createOpenAIScenarioEngine, loadOpenAIScenarioDocument, openaiScenarioAdapter, realizeOpenAIRespond } from './openai-scenario.ts';
108
+ export type { OpenAIScenarioEngine, OpenAIScenarioRequest, OpenAIScenarioRespond } from './openai-scenario.ts';