@ahoo-wang/godex 0.0.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 ADDED
@@ -0,0 +1,472 @@
1
+ # Godex
2
+
3
+ OpenAI Responses API gateway — translates `/v1/responses` into upstream Chat Completions API calls, so **any LLM provider can drive Codex**.
4
+
5
+ [![Bun](https://img.shields.io/badge/runtime-bun-f9f1e0?logo=bun)](https://bun.sh)
6
+ [![TypeScript](https://img.shields.io/badge/lang-typescript-3178c6?logo=typescript)](https://www.typescriptlang.org/)
7
+
8
+ ## Architecture
9
+
10
+ ```mermaid
11
+ C4Context
12
+ title Godex — System Context
13
+
14
+ Person(user, "Developer / Codex CLI", "Sends Responses API requests<br/>via the OpenAI-compatible endpoint")
15
+ System(godex_svr, "Godex Server", "Translates Responses API → Chat Completions API<br/>Bun HTTP server on configurable port")
16
+ SystemDb(sessions, "Session Store", "Stores response history for<br/>previous_response_id chain resolution<br/>SQLite (persistent) or In-Memory")
17
+ System_Ext(zhipu, "Zhipu (智谱)", "Chat Completions API provider")
18
+ System_Ext(openai, "OpenAI", "Chat Completions API provider")
19
+ System_Ext(other, "Custom Provider", "Any Chat Completions<br/>compatible backend")
20
+
21
+ Rel(user, godex_svr, "POST /v1/responses, GET /v1/models, GET /health", "HTTP/SSE")
22
+ Rel(godex_svr, sessions, "save / resolve chains")
23
+ Rel(godex_svr, zhipu, "POST /chat/completions", "HTTPS")
24
+ Rel(godex_svr, openai, "POST /chat/completions", "HTTPS")
25
+ Rel(godex_svr, other, "POST /chat/completions", "HTTPS")
26
+ ```
27
+
28
+ ## Request Flow
29
+
30
+ ```mermaid
31
+ sequenceDiagram
32
+ actor C as Client (Codex CLI)
33
+ participant R as Router
34
+ participant AC as ApplicationContext
35
+ participant RC as ResponsesContext
36
+ participant MR as ModelResolver
37
+ participant SS as SessionStore
38
+ participant REG as Registrar
39
+ participant A as Adapter (DefaultAdapter)
40
+ participant PM as ProviderMapper
41
+ participant CC as ChatClient
42
+ participant UP as Upstream API
43
+
44
+ C->>R: POST /v1/responses
45
+ R->>RC: ResponsesContext.create(app, body)
46
+
47
+ activate RC
48
+ RC->>MR: resolve(model)
49
+ MR-->>RC: { provider, model }
50
+ RC->>RC: validate provider config
51
+
52
+ opt previous_response_id
53
+ RC->>SS: resolveChain(id)
54
+ SS-->>RC: session snapshot
55
+ end
56
+
57
+ RC->>REG: resolve(provider)
58
+ REG-->>RC: Provider instance
59
+ deactivate RC
60
+
61
+ alt stream = true
62
+ R->>A: adapter.stream(ctx)
63
+ activate A
64
+ A->>PM: request.map(ctx)
65
+ PM-->>A: upstream request
66
+ A->>CC: streamChat(req)
67
+ CC->>UP: POST (SSE)
68
+ UP-->>CC: SSE chunks
69
+ CC-->>A: ReadableStream<SSE>
70
+ A->>A: pipeTransform → ProviderEventToResponseTransformer
71
+ A->>A: pipeTransform → ResponseSessionPersistenceTransformer
72
+ A-->>R: ReadableStream<ResponseStreamEvent>
73
+ deactivate A
74
+ R->>R: pipeTransform → ResponseSseEncodeTransformer
75
+ R-->>C: SSE byte stream
76
+ else stream = false
77
+ R->>A: adapter.request(ctx)
78
+ activate A
79
+ A->>PM: request.map(ctx)
80
+ PM-->>A: upstream request
81
+ A->>CC: chat(req)
82
+ CC->>UP: POST
83
+ UP-->>CC: JSON response
84
+ CC-->>A: upstream response
85
+ A->>PM: response.map(ctx, res)
86
+ PM-->>A: ResponseObject
87
+ A->>SS: save(session)
88
+ A-->>R: ResponseObject
89
+ deactivate A
90
+ R-->>C: JSON response
91
+ end
92
+ ```
93
+
94
+ ## Component Model
95
+
96
+ ```mermaid
97
+ classDiagram
98
+ direction TB
99
+
100
+ class ApplicationContext {
101
+ +config: GodexConfig
102
+ +logger: Logger
103
+ +resolver: ModelResolver
104
+ +registrar: Registrar
105
+ +adapter: Adapter
106
+ +sessionStore: ResponseSessionStore
107
+ }
108
+
109
+ class ResponsesContext {
110
+ +app: ApplicationContext
111
+ +request: ResponseCreateRequest
112
+ +session: ResponseSessionSnapshot
113
+ +resolved: ResolvedModel
114
+ +provider: Provider
115
+ +responseId: string
116
+ +requestId: string
117
+ +logger: Logger
118
+ +create(app, body)$ Promise~ResponsesContext~
119
+ }
120
+
121
+ class ModelResolver {
122
+ -defaultProvider: string
123
+ -providerConfigs: Record
124
+ +resolve(model) ResolvedModel
125
+ }
126
+
127
+ class Registrar {
128
+ -factories: Map~string, ProviderFactory~
129
+ +registerFactory(name, factory)
130
+ +build(providers)
131
+ +resolve(name) Provider
132
+ +list() string[]
133
+ }
134
+
135
+ class Adapter {
136
+ <<interface>>
137
+ +request(ctx) Promise~ResponseObject~
138
+ +stream(ctx) Promise~ReadableStream~
139
+ }
140
+
141
+ class DefaultAdapter {
142
+ +request(ctx) Promise~ResponseObject~
143
+ +stream(ctx) Promise~ReadableStream~
144
+ }
145
+
146
+ class Provider {
147
+ <<interface>>
148
+ +name: string
149
+ +mapper: ProviderMapper
150
+ +chatClient: ChatClient
151
+ +capabilities: ProviderCapabilities
152
+ }
153
+
154
+ class ProviderMapper {
155
+ <<interface>>
156
+ +request: RequestMapper
157
+ +response: ResponseMapper
158
+ +stream: StreamMapper
159
+ }
160
+
161
+ class ChatClient {
162
+ <<interface>>
163
+ +chat(req) Promise~TRes~
164
+ +streamChat(req) Promise~ReadableStream~
165
+ }
166
+
167
+ class RequestMapper {
168
+ <<interface>>
169
+ +map(ctx) TReq
170
+ }
171
+
172
+ class ResponseMapper {
173
+ <<interface>>
174
+ +map(ctx, result) ResponseObject
175
+ }
176
+
177
+ class StreamMapper {
178
+ <<interface>>
179
+ +map(ctx, event) ResponseStreamEvent[]
180
+ +buildResponseObject(ctx, state) ResponseObject
181
+ }
182
+
183
+ class ResponseSessionStore {
184
+ <<interface>>
185
+ +get(id) StoredResponseSession
186
+ +save(session, opts)
187
+ +resolveChain(id, opts) ResponseSessionSnapshot
188
+ +delete(id)
189
+ +close()
190
+ }
191
+
192
+ class Router {
193
+ -routes: Route[]
194
+ +register(route)
195
+ +dispatch(req) Promise~Response~
196
+ }
197
+
198
+ ApplicationContext --> ResponsesContext : creates
199
+ ApplicationContext --> ModelResolver
200
+ ApplicationContext --> Registrar
201
+ ApplicationContext --> Adapter
202
+ ApplicationContext --> ResponseSessionStore
203
+ ResponsesContext --> Provider : uses
204
+ Provider --> ProviderMapper
205
+ Provider --> ChatClient
206
+ ProviderMapper --> RequestMapper
207
+ ProviderMapper --> ResponseMapper
208
+ ProviderMapper --> StreamMapper
209
+ Adapter <|.. DefaultAdapter
210
+ DefaultAdapter --> ProviderMapper : calls
211
+ DefaultAdapter --> ChatClient : calls
212
+ DefaultAdapter --> ResponseSessionStore : saves
213
+ Router --> ResponsesContext : dispatches to
214
+ ```
215
+
216
+ ## Stream Pipeline
217
+
218
+ ```mermaid
219
+ flowchart LR
220
+ subgraph upstream["Upstream Provider"]
221
+ SSE["SSE Chunks<br/>(JsonServerSentEvent)"]
222
+ end
223
+
224
+ subgraph godex["Godex Stream Pipeline"]
225
+ T1["ProviderEventTo<br/>ResponseTransformer"]
226
+ T2["ResponseSession<br/>PersistenceTransformer"]
227
+ T3["ResponseSse<br/>EncodeTransformer"]
228
+ end
229
+
230
+ subgraph client["Client"]
231
+ BYTES["SSE Bytes<br/>(text/event-stream)"]
232
+ end
233
+
234
+ SSE -->|"pipeThrough(TransformStream)"| T1
235
+ T1 -->|"per-event map()<br/>SSE chunk → ResponseStreamEvent[]"| T2
236
+ T2 -->|"accumulate StreamState<br/>intercept terminal event<br/>buildResponseObject()<br/>save session"| T3
237
+ T3 -->|"serialize to SSE wire format<br/>event: xxx\ndata: {...}\n\n"| BYTES
238
+
239
+ style upstream fill:#1a1a2e,stroke:#16213e,color:#e0e0e0
240
+ style godex fill:#0f3460,stroke:#16213e,color:#e0e0e0
241
+ style client fill:#1a1a2e,stroke:#16213e,color:#e0e0e0
242
+ ```
243
+
244
+ ### Transformer Roles
245
+
246
+ | Stage | Transformer | Input | Output | Side Effects |
247
+ |-------|------------|-------|--------|-------------|
248
+ | 1 | `ProviderEventToResponseTransformer` | `JsonServerSentEvent<TChunk>` | `ResponseStreamEvent` | Calls `StreamMapper.map()` per event |
249
+ | 2 | `ResponseSessionPersistenceTransformer` | `ResponseStreamEvent` | `ResponseStreamEvent` | Accumulates `StreamState`, on terminal event calls `buildResponseObject()` + saves session (skipped when `store=false`) |
250
+ | 3 | `ResponseSseEncodeTransformer` | `ResponseStreamEvent` | `Uint8Array` (SSE wire format) | Serializes to `event:` / `data:` lines |
251
+
252
+ ## Error Hierarchy
253
+
254
+ ```mermaid
255
+ classDiagram
256
+ direction TB
257
+
258
+ class GodexError {
259
+ +name: string
260
+ +code: string
261
+ +status: number
262
+ +context: object
263
+ +toLogEntry() object
264
+ }
265
+
266
+ class ServerError {
267
+ +status: 400-499
268
+ +context: object
269
+ }
270
+
271
+ class AdapterError {
272
+ +status: 400-499
273
+ +context: unsupported parameters / tools / input items
274
+ }
275
+
276
+ class ProviderError {
277
+ +status: 502
278
+ +context: upstream status / body / headers
279
+ }
280
+
281
+ class SessionError {
282
+ +status: 400-409
283
+ +context: chain metadata
284
+ }
285
+
286
+ GodexError <|-- ServerError
287
+ GodexError <|-- AdapterError
288
+ GodexError <|-- ProviderError
289
+ GodexError <|-- SessionError
290
+
291
+ note for GodexError "Base error with structured logging support.<br/>All errors carry domain codes (e.g. server.request.invalid_json)."
292
+ note for ProviderError "Wraps upstream HTTP failures:<br/>rate limits, timeouts, 5xx."
293
+ note for SessionError "Chain resolution failures:<br/>not found, cycles, depth exceeded."
294
+ ```
295
+
296
+ ## Project Structure
297
+
298
+ ```
299
+ src/
300
+ ├── cli/ Commander CLI (serve, config check, init)
301
+ ├── config/ godex.yaml schema, env interpolation, defaults
302
+ ├── context/ ApplicationContext (DI container), ResponsesContext (per-request)
303
+ ├── adapter/ Adapter interface, DefaultAdapter, stream transformers
304
+ │ ├── mapper/ RequestMapper / ResponseMapper / StreamMapper contracts
305
+ │ └── transformers/ ProviderEvent → Response → SSE encode pipeline
306
+ ├── providers/ Provider registry + builtin factories
307
+ │ └── zhipu/ Reference provider: mapper, chat-client, tools, messages
308
+ ├── resolver/ ModelResolver (model selector → provider + model)
309
+ ├── server/ Bun HTTP server, Router, routes (/v1/responses, /health, /v1/models)
310
+ ├── session/ ResponseSessionStore (Memory + SQLite), chain resolution
311
+ ├── error/ GodexError hierarchy with domain codes
312
+ ├── protocol/openai/ OpenAI-compatible type definitions
313
+ ├── logger/ Structured JSON logger
314
+ └── e2e/ End-to-end tests with mocked upstream
315
+ ```
316
+
317
+ ## Quick Start
318
+
319
+ ```bash
320
+ # Install dependencies
321
+ bun install
322
+
323
+ # Build standalone binary (current platform)
324
+ bun run build
325
+
326
+ # Create config interactively
327
+ bun run start -- init
328
+
329
+ # Start server (default port 5678)
330
+ bun run dev
331
+
332
+ # Or run the compiled binary directly
333
+ ./platforms/darwin-arm64/bin/godex serve
334
+ ```
335
+
336
+ ### godex.yaml
337
+
338
+ ```yaml
339
+ server:
340
+ port: 5678
341
+
342
+ default_provider: zhipu
343
+
344
+ providers:
345
+ zhipu:
346
+ api_key: ${ZHIPU_API_KEY}
347
+ base_url: https://open.bigmodel.cn/api/paas/v4
348
+ models:
349
+ "gpt-4o": glm-4.7 # model name mapping
350
+ "*": glm-5.1 # catch-all fallback
351
+
352
+ session:
353
+ backend: sqlite # or "memory"
354
+ sqlite:
355
+ path: ./data/sessions.db
356
+
357
+ logging:
358
+ level: info # trace | debug | info | warn | error
359
+ ```
360
+
361
+ ### Adding a Provider
362
+
363
+ Implement these interfaces in `src/providers/<name>/`:
364
+
365
+ | Interface | Purpose |
366
+ |-----------|---------|
367
+ | `Provider<TReq, TRes, TChunk>` | Bundles mapper + chatClient + capabilities |
368
+ | `ProviderMapper<TReq, TRes, TChunk>` | request / response / stream mapping functions |
369
+ | `ChatClient<TReq, TRes, TChunk>` | `chat()` and `streamChat()` HTTP calls |
370
+
371
+ Register the factory in `src/providers/builtin.ts`:
372
+
373
+ ```ts
374
+ registrar.registerFactory("myprovider", (config) =>
375
+ createMyProvider(config) as Provider<unknown, unknown, unknown>
376
+ );
377
+ ```
378
+
379
+ ## Usage
380
+
381
+ ```bash
382
+ # Install — no Bun required at runtime
383
+ npm install -g @ahoo-wang/godex
384
+
385
+ # Create config interactively
386
+ godex init
387
+
388
+ # Start the gateway
389
+ godex serve
390
+ ```
391
+
392
+ Godex ships as a **standalone native binary** with zero runtime dependencies. npm's `postinstall` automatically selects the correct binary for your platform. The only prerequisite is Node.js >= 18 (needed only during `npm install`).
393
+
394
+ Godex exposes an **OpenAI-compatible Responses API** at `http://localhost:5678` (port is configurable). Point any tool that speaks the OpenAI protocol at this endpoint:
395
+
396
+ ### With Codex CLI
397
+
398
+ ```bash
399
+ export OPENAI_BASE_URL=http://localhost:5678/v1
400
+ export OPENAI_API_KEY=any-value # not validated by Godex, must be set
401
+ codex
402
+ ```
403
+
404
+ ### With OpenAI SDK
405
+
406
+ ```ts
407
+ import OpenAI from "openai";
408
+
409
+ const client = new OpenAI({
410
+ baseURL: "http://localhost:5678/v1",
411
+ apiKey: "any-value", // passed through, not validated
412
+ });
413
+
414
+ const response = await client.responses.create({
415
+ model: "gpt-4o", // mapped to glm-4.7 via godex.yaml models table
416
+ input: "Hello!",
417
+ });
418
+ ```
419
+
420
+ ### Model selection
421
+
422
+ ```
423
+ model: "gpt-4o" → resolved via default_provider model mapping
424
+ model: "zhipu/glm-4.7" → explicit provider/model selector
425
+ model: "openai/gpt-4o" → routes to configured openai provider
426
+ ```
427
+
428
+ The `models` map in `godex.yaml` lets you translate standard model names into provider-native ones — no code changes needed in the client.
429
+
430
+ ### Health check
431
+
432
+ ```bash
433
+ curl http://localhost:5678/health
434
+ # {"status":"ok","providers":["zhipu"],"unsupported_providers":[]}
435
+ ```
436
+
437
+ ## Publishing
438
+
439
+ The main `@ahoo-wang/godex` npm package is a lightweight shell. Native binaries are shipped as platform-specific optional dependencies:
440
+
441
+ ```
442
+ @ahoo-wang/godex (wrapper package, 0 runtime deps)
443
+ ├── engines: { node: ">=18.0.0" } ← only for postinstall
444
+ ├── postinstall: scripts/install.cjs ← detects platform, links binary
445
+ └── optionalDependencies:
446
+ ├── @ahoo-wang/godex-darwin-arm64 ← macOS Apple Silicon
447
+ ├── @ahoo-wang/godex-darwin-x64 ← macOS Intel
448
+ ├── @ahoo-wang/godex-linux-x64 ← Linux x86_64
449
+ ├── @ahoo-wang/godex-linux-arm64 ← Linux ARM64
450
+ ├── @ahoo-wang/godex-win32-x64 ← Windows x86_64
451
+ └── @ahoo-wang/godex-win32-arm64 ← Windows ARM64
452
+
453
+ # Publishing flow:
454
+ # 1. Make the GitHub repository public, configure NPM_TOKEN, then push the release commit.
455
+ # 2. Create a GitHub Release tagged vX.Y.Z.
456
+ # 3. The Release workflow builds all platform binaries.
457
+ # 4. The Release workflow uploads binary archives and SHA256SUMS to Release Assets.
458
+ # 5. The Release workflow publishes platform packages first, then @ahoo-wang/godex.
459
+ ```
460
+
461
+ ## Commands
462
+
463
+ ```bash
464
+ bun run dev # Hot-reload dev server on port 13145
465
+ bun run build # Compile native binary for current platform
466
+ bun run compile:all # Cross-compile all 6 platforms locally
467
+ bun run test # Unit + integration tests
468
+ bun run test:e2e # E2E with mocked upstream
469
+ bun run typecheck # tsc --noEmit
470
+ bun run lint # Biome check
471
+ bun run ci # Full CI pipeline
472
+ ```
package/bin/godex ADDED
@@ -0,0 +1,50 @@
1
+ #!/usr/bin/env node
2
+ // Wrapper that execs the platform-specific native binary installed by postinstall.
3
+ // Uses ESM syntax because package.json has "type": "module".
4
+
5
+ import { spawnSync } from "node:child_process";
6
+ import { accessSync, constants } from "node:fs";
7
+ import { join, dirname } from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+
10
+ const __dirname = dirname(fileURLToPath(import.meta.url));
11
+
12
+ function findBinary() {
13
+ // Binary is copied here by postinstall
14
+ const nextToWrapper = join(__dirname, "godex-binary");
15
+ try {
16
+ accessSync(nextToWrapper, constants.X_OK);
17
+ return nextToWrapper;
18
+ } catch {
19
+ // not found, try dev fallback
20
+ }
21
+ // Dev fallback — when running from source without postinstall
22
+ try {
23
+ const devPath = join(__dirname, "..", "dist", "index.js");
24
+ accessSync(devPath);
25
+ return devPath;
26
+ } catch {
27
+ // not found
28
+ }
29
+ return null;
30
+ }
31
+
32
+ const binary = findBinary();
33
+ if (!binary) {
34
+ console.error(
35
+ "godex: binary not found. Re-run npm install or build from source.",
36
+ );
37
+ process.exit(1);
38
+ }
39
+
40
+ // If it's a .js file (dev fallback), spawn with bun
41
+ if (binary.endsWith(".js")) {
42
+ const result = spawnSync("bun", [binary, ...process.argv.slice(2)], {
43
+ stdio: "inherit",
44
+ });
45
+ process.exit(result.status ?? 1);
46
+ }
47
+
48
+ // Native binary — direct exec
49
+ const result = spawnSync(binary, process.argv.slice(2), { stdio: "inherit" });
50
+ process.exit(result.status ?? 1);
package/package.json ADDED
@@ -0,0 +1,67 @@
1
+ {
2
+ "name": "@ahoo-wang/godex",
3
+ "version": "0.0.1",
4
+ "description": "Make every model a Codex engine through an OpenAI-compatible Responses API gateway",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Ahoo-Wang/Godex.git"
9
+ },
10
+ "homepage": "https://github.com/Ahoo-Wang/Godex#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/Ahoo-Wang/Godex/issues"
13
+ },
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
17
+ "type": "module",
18
+ "bin": {
19
+ "godex": "bin/godex"
20
+ },
21
+ "files": [
22
+ "bin/godex",
23
+ "scripts/install.cjs"
24
+ ],
25
+ "scripts": {
26
+ "build": "bun run scripts/compile.ts",
27
+ "compile": "bun run scripts/compile.ts",
28
+ "compile:all": "bun run scripts/compile.ts --all",
29
+ "dev": "bun --hot src/index.ts --port 13145",
30
+ "start": "bun src/index.ts",
31
+ "lint": "biome check src",
32
+ "lint:fix": "biome check --write src",
33
+ "format": "biome format --write src",
34
+ "typecheck": "tsc --noEmit",
35
+ "test": "bun test --path-ignore-patterns 'src/e2e/**'",
36
+ "test:e2e": "bun test src/e2e",
37
+ "test:zhipu": "ZHIPU_LIVE_TESTS=1 bun test src/e2e/zhipu-live.test.ts",
38
+ "test:coverage": "bun test --path-ignore-patterns 'src/e2e/**' --coverage",
39
+ "check": "bun run typecheck && bun run lint && bun run test",
40
+ "ci": "bun run typecheck && biome ci src && bun run test && bun run test:e2e",
41
+ "postinstall": "node scripts/install.cjs"
42
+ },
43
+ "engines": {
44
+ "node": ">=18.0.0"
45
+ },
46
+ "optionalDependencies": {
47
+ "@ahoo-wang/godex-darwin-arm64": "0.0.1",
48
+ "@ahoo-wang/godex-darwin-x64": "0.0.1",
49
+ "@ahoo-wang/godex-linux-x64": "0.0.1",
50
+ "@ahoo-wang/godex-linux-arm64": "0.0.1",
51
+ "@ahoo-wang/godex-win32-x64": "0.0.1",
52
+ "@ahoo-wang/godex-win32-arm64": "0.0.1"
53
+ },
54
+ "devDependencies": {
55
+ "@biomejs/biome": "^2.4.15",
56
+ "@ahoo-wang/fetcher": "^3.16.5",
57
+ "@ahoo-wang/fetcher-decorator": "^3.16.5",
58
+ "@ahoo-wang/fetcher-eventstream": "^3.16.5",
59
+ "@clack/prompts": "^1.4.0",
60
+ "@types/bun": "^1.2.0",
61
+ "@types/js-yaml": "^4.0.9",
62
+ "commander": "^14.0.3",
63
+ "js-yaml": "^4.1.1",
64
+ "nanoid": "^5.1.11",
65
+ "typescript": "^5"
66
+ }
67
+ }
@@ -0,0 +1,83 @@
1
+ // Postinstall: links the platform-specific native binary to bin/godex-binary.
2
+ // npm installs the matching optional dependency before running this script,
3
+ // so the platform package is already in node_modules (production path).
4
+ // For local development (no published optional dep), checks platforms/ dir as fallback.
5
+ // If neither is available, skips gracefully — bin/godex wrapper falls back to dev mode.
6
+
7
+ "use strict";
8
+
9
+ const fs = require("fs");
10
+ const path = require("path");
11
+
12
+ function detectPlatform() {
13
+ const plat = process.platform; // "darwin" | "linux" | "win32"
14
+ const arch = process.arch; // "arm64" | "x64"
15
+ if (plat === "win32") return `win32-${arch}`;
16
+ if (plat === "darwin") return `darwin-${arch}`;
17
+ if (plat === "linux") return `linux-${arch}`;
18
+ return null;
19
+ }
20
+
21
+ function findBinary(pkgName, platform) {
22
+ const binaryName = platform.startsWith("win32") ? "godex.exe" : "godex";
23
+
24
+ // 1. Production: optional dep installed by npm
25
+ try {
26
+ const pkgRoot = path.dirname(
27
+ require.resolve(pkgName + "/package.json", {
28
+ paths: [path.join(__dirname, "..", "node_modules")],
29
+ }),
30
+ );
31
+ const binary = path.join(pkgRoot, "bin", binaryName);
32
+ if (fs.existsSync(binary)) return binary;
33
+ } catch (_) {
34
+ // optional dep not published / not installed
35
+ }
36
+
37
+ // 2. Dev fallback: binary already compiled locally in platforms/
38
+ const [os, arch] = platform.split("-");
39
+ const localBinary = path.join(
40
+ __dirname,
41
+ "..",
42
+ "platforms",
43
+ os + "-" + arch,
44
+ "bin",
45
+ binaryName,
46
+ );
47
+ if (fs.existsSync(localBinary)) return localBinary;
48
+
49
+ return null;
50
+ }
51
+
52
+ function link(src, dest) {
53
+ try {
54
+ fs.unlinkSync(dest);
55
+ } catch (_) {
56
+ // didn't exist
57
+ }
58
+ fs.copyFileSync(src, dest);
59
+ try {
60
+ fs.chmodSync(dest, 0o755);
61
+ } catch (_) {
62
+ // Windows doesn't need chmod
63
+ }
64
+ }
65
+
66
+ const platform = detectPlatform();
67
+ if (!platform) {
68
+ console.log("godex: skipping binary setup — unsupported platform", process.platform, process.arch);
69
+ process.exit(0);
70
+ }
71
+
72
+ const binary = findBinary("@ahoo-wang/godex-" + platform, platform);
73
+ if (!binary) {
74
+ console.log("godex: no prebuilt binary for", platform, "— dev mode, skipping");
75
+ process.exit(0);
76
+ }
77
+
78
+ const destDir = path.join(__dirname, "..", "bin");
79
+ if (!fs.existsSync(destDir)) fs.mkdirSync(destDir, { recursive: true });
80
+ const dest = path.join(destDir, "godex-binary");
81
+
82
+ link(binary, dest);
83
+ console.log("godex: installed native binary for", platform);