@leoustc/service-llm 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,77 +1,195 @@
1
- # @leoustc/service-llm
1
+ # service-llm
2
2
 
3
- Expose an OpenAI Codex subscription through OpenAI-compatible HTTP APIs and MCP.
3
+ Use your ChatGPT Codex subscription through OpenAI-compatible HTTP APIs or MCP.
4
4
 
5
- The service never executes model tool calls. It can return tool-call output to a client, which remains responsible for deciding whether to execute it.
5
+ `service-llm` supports Chat Completions, Responses, SSE streaming, function calls, and an MCP `ask` tool. It returns model tool calls but never executes them.
6
6
 
7
7
  ## Requirements
8
8
 
9
9
  - Node.js 22.19 or newer
10
- - A ChatGPT Plus or Pro account with Codex access
10
+ - A ChatGPT account with Codex access
11
11
 
12
- ## Install and log in
12
+ ## Install
13
13
 
14
14
  ```sh
15
15
  npm install --global @leoustc/service-llm
16
+ ```
17
+
18
+ ## Log in
19
+
20
+ ```sh
16
21
  service-llm login
17
22
  ```
18
23
 
19
- For a headless machine, use the device-code flow:
24
+ For a headless or remote machine:
20
25
 
21
26
  ```sh
22
27
  service-llm login --device-code
23
28
  ```
24
29
 
25
- OAuth credentials are stored at `~/.service-llm/auth.json` with owner-only permissions.
30
+ Credentials are stored securely at `~/.service-llm/auth.json`. The available Codex models are recorded at `~/.service-llm/models.json`.
31
+
32
+ If you start the service before logging in, the first model request returns a device code and verification URL. Complete the browser login, then retry the request.
33
+
34
+ ## Choose a model
35
+
36
+ List supported models and show the current default:
37
+
38
+ ```sh
39
+ service-llm model
40
+ ```
41
+
42
+ The default is marked with `*`. Set a different default with:
43
+
44
+ ```sh
45
+ service-llm model set gpt-5.4-mini
46
+ ```
47
+
48
+ An explicit valid `model` in an API request overrides this default for that request.
49
+
50
+ ## Start the server
51
+
52
+ ```sh
53
+ service-llm serve
54
+ ```
55
+
56
+ The server listens on `127.0.0.1:7060` by default.
57
+
58
+ At startup it prints the version, listening URL, authentication state, default model, supported-model count, endpoint URLs, and debug status. API key values and OAuth credentials are never displayed.
59
+
60
+ Choose a different address or port:
61
+
62
+ ```sh
63
+ service-llm serve --host 0.0.0.0 --port 8080
64
+ ```
65
+
66
+ Protect the API with one or more client keys:
26
67
 
27
- If an API request arrives before login, the service starts a device-code login and returns HTTP 200 with `status: "ok"`, a friendly instruction, `device_code`, and `verification_uri`. Complete authentication in the browser, then retry the request.
68
+ ```sh
69
+ service-llm serve --api-key secret-one,secret-two
70
+ ```
71
+
72
+ Clients may send a key through either header:
73
+
74
+ ```http
75
+ Authorization: Bearer secret-one
76
+ ```
77
+
78
+ ```http
79
+ X-API-Key: secret-one
80
+ ```
81
+
82
+ Do not expose the server on a public interface without authentication and appropriate network controls.
83
+
84
+ ## Chat Completions
85
+
86
+ ```sh
87
+ curl http://127.0.0.1:7060/v1/chat/completions \
88
+ -H 'Content-Type: application/json' \
89
+ -d '{
90
+ "model": "gpt-5.4",
91
+ "messages": [
92
+ {"role": "user", "content": "Write a short story."}
93
+ ]
94
+ }'
95
+ ```
96
+
97
+ Add `"stream": true` to receive OpenAI-compatible SSE chunks.
28
98
 
29
- ## Start the service
99
+ ## Responses API
30
100
 
31
101
  ```sh
32
- service-llm --port 7060 --api-key secret-one,secret-two
102
+ curl http://127.0.0.1:7060/v1/responses \
103
+ -H 'Content-Type: application/json' \
104
+ -d '{
105
+ "model": "gpt-5.4",
106
+ "input": "Write a short story."
107
+ }'
33
108
  ```
34
109
 
35
- The default bind address is `127.0.0.1`. Use `--host 0.0.0.0` to listen on all interfaces. If no API keys are supplied, endpoints are unauthenticated.
110
+ Add `"stream": true` to receive typed Responses SSE events.
36
111
 
37
- Clients can authenticate with either `Authorization: Bearer <key>` or `X-API-Key: <key>`.
112
+ ## Function calls
38
113
 
39
- From a source checkout, build and run with request/response debug logging enabled:
114
+ Supply OpenAI-compatible tools and `tool_choice`. The model may return a function call, but `service-llm` will not execute it.
40
115
 
41
116
  ```sh
42
- make run
43
- make run PORT=8080 HOST=0.0.0.0 API_KEYS=secret-one,secret-two
117
+ curl http://127.0.0.1:7060/v1/responses \
118
+ -H 'Content-Type: application/json' \
119
+ -d '{
120
+ "model": "gpt-5.4",
121
+ "input": "Write a short story and submit it with save_story.",
122
+ "tools": [{
123
+ "type": "function",
124
+ "name": "save_story",
125
+ "description": "Save a generated story",
126
+ "parameters": {
127
+ "type": "object",
128
+ "properties": {
129
+ "title": {"type": "string"},
130
+ "story": {"type": "string"}
131
+ },
132
+ "required": ["title", "story"]
133
+ }
134
+ }],
135
+ "tool_choice": "required"
136
+ }'
44
137
  ```
45
138
 
46
- Debug output includes request bodies, JSON responses, and individual SSE events. Authentication headers are redacted. Because prompts and model output are logged, do not enable debug logging around sensitive content.
139
+ ## MCP
47
140
 
48
- Install the current checkout to `~/.bin` without root permissions:
141
+ Connect an MCP client to:
142
+
143
+ ```text
144
+ http://127.0.0.1:7060/mcp
145
+ ```
146
+
147
+ The server provides one tool:
148
+
149
+ - `ask`: accepts `prompt` and optional `model`, `tools`, and `tool_choice` arguments.
150
+
151
+ Example JSON-RPC request:
49
152
 
50
153
  ```sh
51
- make install
52
- service-llm --help
154
+ curl http://127.0.0.1:7060/mcp \
155
+ -H 'Content-Type: application/json' \
156
+ -d '{
157
+ "jsonrpc": "2.0",
158
+ "id": 1,
159
+ "method": "tools/call",
160
+ "params": {
161
+ "name": "ask",
162
+ "arguments": {"prompt": "Write a short story."}
163
+ }
164
+ }'
53
165
  ```
54
166
 
55
- If necessary, add it to your shell path with `export PATH="$HOME/.bin:$PATH"`. Run `make uninstall` to remove the symlink.
167
+ ## Model selection
56
168
 
57
- ## Endpoints
169
+ Specify a model with the request's `model` field. If it is omitted or unavailable, the service uses your configured default. On first login, the lowest-cost available model is selected with low reasoning effort. Responses always report the model actually used.
58
170
 
59
- - `GET /health`
60
- - `POST /v1/chat/completions`, including `stream: true` SSE responses
61
- - `POST /v1/responses`, including typed SSE responses
62
- - `POST /mcp`, providing the MCP `ask` tool. `ask` accepts a prompt plus optional `model`, `tools`, and `tool_choice`, and returns model tool calls without executing them.
171
+ ## Debug logging
63
172
 
64
- The default model is `gpt-5.4`. A different Codex model can be selected with the request's `model` field.
173
+ Enable request, response, and SSE logs with:
65
174
 
66
- ## Development
175
+ ```sh
176
+ DEBUG=service-llm service-llm serve
177
+ ```
178
+
179
+ Authentication headers are redacted. Prompts and model output are not redacted, so avoid debug logging for sensitive requests.
180
+
181
+ ## Health check
67
182
 
68
183
  ```sh
69
- make build
70
- make test
71
- make pack
72
- make publish
73
- make clean
184
+ curl http://127.0.0.1:7060/health
185
+ ```
186
+
187
+ Expected response:
188
+
189
+ ```json
190
+ {"status":"ok"}
74
191
  ```
75
192
 
76
- Each test run also saves its complete output under `test/logs/` using a timestamped filename.
77
- The suite sends the live `Write a short story.` prompt through Chat Completions, Responses, and MCP `ask`. Override the HTTP request model with `make test TEST_MODEL=gpt-5.4-mini`.
193
+ ## License
194
+
195
+ Apache License 2.0. See [LICENSE](LICENSE).
package/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.2.1
package/dist/auth.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { chmod, mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
+ import { randomUUID } from "node:crypto";
2
3
  import { homedir } from "node:os";
3
4
  import { dirname, join } from "node:path";
4
5
  import {
@@ -6,16 +7,77 @@ import {
6
7
  loginOpenAICodexDeviceCode,
7
8
  refreshOpenAICodexToken,
8
9
  } from "@earendil-works/pi-ai/oauth";
10
+ import { getModels } from "@earendil-works/pi-ai/compat";
9
11
 
10
12
  export const authPath = join(homedir(), ".service-llm", "auth.json");
13
+ export const modelsPath = join(homedir(), ".service-llm", "models.json");
11
14
  let pendingDeviceLogin;
15
+ let refreshPromise;
16
+ let writeQueue = Promise.resolve();
17
+
18
+ function smallestModel(models) {
19
+ return [...models].sort((left, right) => {
20
+ const leftCost = (left.cost?.input ?? Infinity) + (left.cost?.output ?? Infinity);
21
+ const rightCost = (right.cost?.input ?? Infinity) + (right.cost?.output ?? Infinity);
22
+ return leftCost - rightCost || left.id.localeCompare(right.id);
23
+ })[0];
24
+ }
25
+
26
+ async function saveModelCatalog() {
27
+ const models = getModels("openai-codex");
28
+ const fallback = smallestModel(models);
29
+ if (!fallback) throw new Error("No OpenAI Codex models are available");
30
+ let previousDefault;
31
+ try {
32
+ previousDefault = JSON.parse(await readFile(modelsPath, "utf8")).default_model;
33
+ } catch (error) {
34
+ if (error?.code !== "ENOENT") console.error(`Unable to preserve model selection: ${error.message}`);
35
+ }
36
+ const availableIds = new Set(models.map((model) => model.id));
37
+ const catalog = {
38
+ updated_at: new Date().toISOString(),
39
+ default_model: availableIds.has(previousDefault) ? previousDefault : fallback.id,
40
+ default_reasoning_effort: "low",
41
+ models: models.map((model) => ({ id: model.id, name: model.name })),
42
+ };
43
+ await writeSecureJson(modelsPath, catalog);
44
+ return catalog;
45
+ }
46
+
47
+ export async function listModels() {
48
+ try {
49
+ return JSON.parse(await readFile(modelsPath, "utf8"));
50
+ } catch (error) {
51
+ if (error?.code !== "ENOENT") throw new Error(`Unable to read ${modelsPath}: ${error.message}`);
52
+ return saveModelCatalog();
53
+ }
54
+ }
55
+
56
+ export async function setDefaultModel(modelId) {
57
+ const catalog = await listModels();
58
+ if (!catalog.models.some((model) => model.id === modelId)) {
59
+ throw new Error(`Unsupported model: ${modelId}. Run 'service-llm model' to list supported models.`);
60
+ }
61
+ catalog.default_model = modelId;
62
+ catalog.updated_at = new Date().toISOString();
63
+ await writeSecureJson(modelsPath, catalog);
64
+ return catalog;
65
+ }
66
+
67
+ async function writeSecureJson(path, data) {
68
+ const operation = writeQueue.then(async () => {
69
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
70
+ const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
71
+ await writeFile(temporaryPath, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 });
72
+ await rename(temporaryPath, path);
73
+ await chmod(path, 0o600);
74
+ });
75
+ writeQueue = operation.catch(() => {});
76
+ return operation;
77
+ }
12
78
 
13
79
  async function saveAuth(data) {
14
- await mkdir(dirname(authPath), { recursive: true, mode: 0o700 });
15
- const temporaryPath = `${authPath}.${process.pid}.tmp`;
16
- await writeFile(temporaryPath, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 });
17
- await rename(temporaryPath, authPath);
18
- await chmod(authPath, 0o600);
80
+ await writeSecureJson(authPath, data);
19
81
  }
20
82
 
21
83
  async function readAuth() {
@@ -46,7 +108,9 @@ export async function login({ deviceCode = false } = {}) {
46
108
  const data = await readAuth();
47
109
  data["openai-codex"] = { type: "oauth", ...credentials };
48
110
  await saveAuth(data);
111
+ const catalog = await saveModelCatalog();
49
112
  console.error(`Authentication saved to ${authPath}`);
113
+ console.error(`Loaded ${catalog.models.length} models; default is ${catalog.default_model} with low reasoning`);
50
114
  }
51
115
 
52
116
  export class DeviceLoginRequiredError extends Error {
@@ -86,6 +150,7 @@ async function beginDeviceLogin() {
86
150
  const data = await readAuth();
87
151
  data["openai-codex"] = { type: "oauth", ...credentials };
88
152
  await saveAuth(data);
153
+ await saveModelCatalog();
89
154
  console.error(`Authentication completed and saved to ${authPath}`);
90
155
  })
91
156
  .catch((error) => {
@@ -107,9 +172,21 @@ export async function getAccessToken() {
107
172
  }
108
173
 
109
174
  if (Date.now() >= credentials.expires - 60_000) {
110
- credentials = { type: "oauth", ...(await refreshOpenAICodexToken(credentials.refresh)) };
111
- data["openai-codex"] = credentials;
112
- await saveAuth(data);
175
+ if (!refreshPromise) {
176
+ refreshPromise = (async () => {
177
+ const latest = await readAuth();
178
+ const latestCredentials = latest["openai-codex"];
179
+ if (!latestCredentials?.refresh) throw new Error("Stored OpenAI Codex refresh token is missing; log in again");
180
+ if (latestCredentials?.access && Date.now() < latestCredentials.expires - 60_000) return latestCredentials;
181
+ const refreshed = { type: "oauth", ...(await refreshOpenAICodexToken(latestCredentials.refresh)) };
182
+ latest["openai-codex"] = refreshed;
183
+ await saveAuth(latest);
184
+ return refreshed;
185
+ })().finally(() => {
186
+ refreshPromise = undefined;
187
+ });
188
+ }
189
+ credentials = await refreshPromise;
113
190
  }
114
191
  return credentials.access;
115
192
  }
package/dist/backend.js CHANGED
@@ -1,20 +1,75 @@
1
- import { getModel, stream } from "@earendil-works/pi-ai/compat";
2
- import { getAccessToken } from "./auth.js";
1
+ import { readFile } from "node:fs/promises";
2
+ import { getModel, getModels, stream } from "@earendil-works/pi-ai/compat";
3
+ import { getAccessToken, modelsPath } from "./auth.js";
3
4
 
4
- export const defaultModel = "gpt-5.4";
5
+ const zeroUsage = {
6
+ input: 0,
7
+ output: 0,
8
+ cacheRead: 0,
9
+ cacheWrite: 0,
10
+ totalTokens: 0,
11
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
12
+ };
13
+
14
+ function smallestBuiltinModel() {
15
+ return [...getModels("openai-codex")].sort((left, right) => {
16
+ const leftCost = (left.cost?.input ?? Infinity) + (left.cost?.output ?? Infinity);
17
+ const rightCost = (right.cost?.input ?? Infinity) + (right.cost?.output ?? Infinity);
18
+ return leftCost - rightCost || left.id.localeCompare(right.id);
19
+ })[0];
20
+ }
21
+
22
+ export const defaultModel = smallestBuiltinModel()?.id ?? "gpt-5.4-mini";
23
+
24
+ async function configuredModels() {
25
+ try {
26
+ const catalog = JSON.parse(await readFile(modelsPath, "utf8"));
27
+ return {
28
+ ids: new Set(catalog.models.map((model) => model.id)),
29
+ defaultModel: catalog.default_model,
30
+ reasoningEffort: catalog.default_reasoning_effort ?? "low",
31
+ };
32
+ } catch (error) {
33
+ if (error?.code !== "ENOENT") console.error(`Unable to read ${modelsPath}: ${error.message}`);
34
+ const models = getModels("openai-codex");
35
+ return { ids: new Set(models.map((model) => model.id)), defaultModel, reasoningEffort: "low" };
36
+ }
37
+ }
38
+
39
+ export async function resolveModel(requestedModel) {
40
+ const catalog = await configuredModels();
41
+ const selectedId = requestedModel && catalog.ids.has(requestedModel) ? requestedModel : catalog.defaultModel;
42
+ const model = getModel("openai-codex", selectedId);
43
+ if (!model) throw new Error("No usable OpenAI Codex model is available");
44
+ return { model, requestedModel, fallback: Boolean(requestedModel && requestedModel !== selectedId), reasoningEffort: catalog.reasoningEffort };
45
+ }
5
46
 
6
47
  function textFromContent(content) {
7
48
  if (typeof content === "string") return content;
8
49
  if (!Array.isArray(content)) return "";
9
50
  return content
10
- .filter((part) => part?.type === "text" || part?.type === "input_text")
51
+ .filter((part) => ["text", "input_text", "output_text"].includes(part?.type))
11
52
  .map((part) => part.text ?? "")
12
53
  .join("\n");
13
54
  }
14
55
 
15
- export function messagesFromChat(messages = []) {
56
+ function assistantMessage(content, model) {
57
+ return {
58
+ role: "assistant",
59
+ content,
60
+ api: "openai-codex-responses",
61
+ provider: "openai-codex",
62
+ model,
63
+ usage: structuredClone(zeroUsage),
64
+ stopReason: content.some((part) => part.type === "toolCall") ? "toolUse" : "stop",
65
+ timestamp: Date.now(),
66
+ };
67
+ }
68
+
69
+ export function messagesFromChat(messages = [], model = defaultModel) {
16
70
  let systemPrompt;
17
71
  const result = [];
72
+ const toolNames = new Map();
18
73
  for (const message of messages) {
19
74
  const text = textFromContent(message.content);
20
75
  if (message.role === "system" || message.role === "developer") {
@@ -22,14 +77,27 @@ export function messagesFromChat(messages = []) {
22
77
  } else if (message.role === "user") {
23
78
  result.push({ role: "user", content: text, timestamp: Date.now() });
24
79
  } else if (message.role === "assistant") {
80
+ const content = text ? [{ type: "text", text }] : [];
81
+ for (const call of message.tool_calls ?? []) {
82
+ const fn = call.function;
83
+ if (!call.id || !fn?.name) continue;
84
+ let args;
85
+ try {
86
+ args = typeof fn.arguments === "string" ? JSON.parse(fn.arguments) : (fn.arguments ?? {});
87
+ } catch {
88
+ args = { raw: fn.arguments };
89
+ }
90
+ content.push({ type: "toolCall", id: call.id, name: fn.name, arguments: args });
91
+ toolNames.set(call.id, fn.name);
92
+ }
93
+ result.push(assistantMessage(content, model));
94
+ } else if (message.role === "tool") {
25
95
  result.push({
26
- role: "assistant",
96
+ role: "toolResult",
97
+ toolCallId: message.tool_call_id,
98
+ toolName: message.name ?? toolNames.get(message.tool_call_id) ?? "tool",
27
99
  content: [{ type: "text", text }],
28
- api: "openai-codex-responses",
29
- provider: "openai-codex",
30
- model: defaultModel,
31
- usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
32
- stopReason: "stop",
100
+ isError: false,
33
101
  timestamp: Date.now(),
34
102
  });
35
103
  }
@@ -37,35 +105,63 @@ export function messagesFromChat(messages = []) {
37
105
  return { systemPrompt, messages: result };
38
106
  }
39
107
 
40
- export function messagesFromResponses(input) {
41
- if (typeof input === "string") {
42
- return { messages: [{ role: "user", content: input, timestamp: Date.now() }] };
108
+ export function messagesFromResponses(input, model = defaultModel) {
109
+ if (typeof input === "string") return { messages: [{ role: "user", content: input, timestamp: Date.now() }] };
110
+ if (!Array.isArray(input)) return { messages: [] };
111
+
112
+ const result = [];
113
+ const toolNames = new Map();
114
+ let systemPrompt;
115
+ for (const item of input) {
116
+ if (item.type === "function_call") {
117
+ let args;
118
+ try {
119
+ args = typeof item.arguments === "string" ? JSON.parse(item.arguments) : (item.arguments ?? {});
120
+ } catch {
121
+ args = { raw: item.arguments };
122
+ }
123
+ const callId = item.call_id ?? item.id;
124
+ toolNames.set(callId, item.name);
125
+ result.push(assistantMessage([{ type: "toolCall", id: callId, name: item.name, arguments: args }], model));
126
+ } else if (item.type === "function_call_output") {
127
+ result.push({
128
+ role: "toolResult",
129
+ toolCallId: item.call_id,
130
+ toolName: toolNames.get(item.call_id) ?? "tool",
131
+ content: [{ type: "text", text: textFromContent(item.output) || String(item.output ?? "") }],
132
+ isError: false,
133
+ timestamp: Date.now(),
134
+ });
135
+ } else {
136
+ const converted = messagesFromChat([item], model);
137
+ if (converted.systemPrompt) systemPrompt = systemPrompt ? `${systemPrompt}\n\n${converted.systemPrompt}` : converted.systemPrompt;
138
+ result.push(...converted.messages);
139
+ }
43
140
  }
44
- return messagesFromChat(Array.isArray(input) ? input : []);
141
+ return { systemPrompt, messages: result };
45
142
  }
46
143
 
47
144
  function toolsFromOpenAI(tools) {
48
145
  if (!Array.isArray(tools)) return undefined;
49
146
  return tools.flatMap((tool) => {
50
147
  const fn = tool.type === "function" ? (tool.function ?? tool) : null;
51
- return fn?.name
52
- ? [{ name: fn.name, description: fn.description ?? "", parameters: fn.parameters ?? { type: "object", properties: {} } }]
53
- : [];
148
+ return fn?.name ? [{ name: fn.name, description: fn.description ?? "", parameters: fn.parameters ?? { type: "object", properties: {} } }] : [];
54
149
  });
55
150
  }
56
151
 
57
- export async function createCompletionStream({ context, model = defaultModel, tools, toolChoice, signal }) {
58
- const selectedModel = getModel("openai-codex", model) ?? getModel("openai-codex", defaultModel);
59
- if (!selectedModel) throw new Error(`Unknown Codex model: ${model}`);
152
+ export async function createCompletionStream({ context, model, tools, toolChoice, signal }) {
153
+ const resolved = await resolveModel(model);
60
154
  const apiKey = await getAccessToken();
61
- return stream(selectedModel, { ...context, tools: toolsFromOpenAI(tools) }, {
155
+ const events = stream(resolved.model, { ...context, tools: toolsFromOpenAI(tools) }, {
62
156
  apiKey,
63
157
  signal,
158
+ reasoningEffort: resolved.reasoningEffort,
64
159
  onPayload(payload) {
65
160
  if (!toolChoice || !payload || typeof payload !== "object") return payload;
66
161
  return { ...payload, tool_choice: toolChoice };
67
162
  },
68
163
  });
164
+ return { events, model: resolved.model.id, fallback: resolved.fallback, requestedModel: resolved.requestedModel };
69
165
  }
70
166
 
71
167
  export function contentFromMessage(message) {
package/dist/cli.js CHANGED
@@ -1,16 +1,41 @@
1
1
  #!/usr/bin/env node
2
- import { login } from "./auth.js";
2
+ import { listModels, login, setDefaultModel } from "./auth.js";
3
3
  import { startServer } from "./http.js";
4
4
 
5
5
  function usage() {
6
6
  console.error(`Usage:
7
7
  service-llm login [--device-code]
8
- service-llm [--port 7060] [--host 127.0.0.1] [--api-key key1,key2]`);
8
+ service-llm model [list]
9
+ service-llm model set <model-id>
10
+ service-llm serve [--port 7060] [--host 127.0.0.1] [--api-key key1,key2]`);
11
+ }
12
+
13
+ async function modelCommand(args) {
14
+ if (!args[1] || args[1] === "list") {
15
+ const catalog = await listModels();
16
+ console.log(`Supported Codex models (${catalog.models.length}):`);
17
+ for (const model of catalog.models) {
18
+ console.log(`${model.id === catalog.default_model ? "*" : " "} ${model.id}${model.name ? ` — ${model.name}` : ""}`);
19
+ }
20
+ console.log(`\n* default (${catalog.default_reasoning_effort ?? "low"} reasoning)`);
21
+ return;
22
+ }
23
+ if (args[1] === "set") {
24
+ const modelId = args[2];
25
+ if (!modelId || args[3]) throw new Error("Usage: service-llm model set <model-id>");
26
+ await setDefaultModel(modelId);
27
+ console.log(`Default model set to ${modelId}`);
28
+ return;
29
+ }
30
+ throw new Error("Usage: service-llm model [list|set <model-id>]");
9
31
  }
10
32
 
11
33
  function valueAfter(args, names, fallback) {
12
34
  const index = args.findIndex((arg) => names.includes(arg));
13
- return index < 0 ? fallback : args[index + 1];
35
+ if (index < 0) return fallback;
36
+ const value = args[index + 1];
37
+ if (!value || value.startsWith("-")) throw new Error(`${args[index]} requires a value`);
38
+ return value;
14
39
  }
15
40
 
16
41
  const args = process.argv.slice(2);
@@ -18,9 +43,15 @@ if (args.includes("--help") || args.includes("-h")) {
18
43
  usage();
19
44
  } else if (args[0] === "login") {
20
45
  await login({ deviceCode: args.includes("--device-code") });
21
- } else {
22
- const port = Number(valueAfter(args, ["--port"], "7060"));
46
+ } else if (args[0] === "model") {
47
+ await modelCommand(args);
48
+ } else if (args[0] === "serve") {
49
+ const serveArgs = args.slice(1);
50
+ const port = Number(valueAfter(serveArgs, ["--port"], "7060"));
23
51
  if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("--port must be between 1 and 65535");
24
- const apiKeyValue = valueAfter(args, ["--api-key", "-api_key"], process.env.SERVICE_LLM_API_KEYS ?? "");
25
- startServer({ port, host: valueAfter(args, ["--host"], "127.0.0.1"), apiKeys: apiKeyValue.split(",").map((key) => key.trim()) });
52
+ const apiKeyValue = valueAfter(serveArgs, ["--api-key", "-api_key"], process.env.SERVICE_LLM_API_KEYS ?? "");
53
+ startServer({ port, host: valueAfter(serveArgs, ["--host"], "127.0.0.1"), apiKeys: apiKeyValue.split(",").map((key) => key.trim()) });
54
+ } else {
55
+ usage();
56
+ process.exitCode = args.length ? 1 : 0;
26
57
  }
package/dist/http.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { createServer } from "node:http";
2
2
  import { randomUUID } from "node:crypto";
3
- import { DeviceLoginRequiredError } from "./auth.js";
3
+ import { DeviceLoginRequiredError, listModels } from "./auth.js";
4
+ import { version } from "./version.js";
4
5
  import {
5
6
  contentFromMessage,
6
7
  createCompletionStream,
@@ -47,9 +48,9 @@ function isAuthorized(request, apiKeys) {
47
48
  return typeof token === "string" && apiKeys.has(token);
48
49
  }
49
50
 
50
- function sse(response, event) {
51
+ function sse(response, event, named = false) {
51
52
  debug("response SSE", event);
52
- response.write(`data: ${JSON.stringify(event)}\n\n`);
53
+ response.write(`${named && event.type ? `event: ${event.type}\n` : ""}data: ${JSON.stringify(event)}\n\n`);
53
54
  }
54
55
 
55
56
  async function collect(streamResult) {
@@ -64,18 +65,23 @@ async function collect(streamResult) {
64
65
 
65
66
  async function chatCompletions(request, response, body) {
66
67
  const id = `chatcmpl-${randomUUID().replaceAll("-", "")}`;
67
- const model = body.model || defaultModel;
68
- const streamResult = await createCompletionStream({
69
- context: messagesFromChat(body.messages), model, tools: body.tools, toolChoice: body.tool_choice,
68
+ const completion = await createCompletionStream({
69
+ context: messagesFromChat(body.messages, body.model), model: body.model, tools: body.tools, toolChoice: body.tool_choice,
70
70
  });
71
+ const { events: streamResult, model } = completion;
71
72
  if (body.stream) {
72
73
  response.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache", connection: "keep-alive" });
73
74
  sse(response, { id, object: "chat.completion.chunk", created: Math.floor(Date.now() / 1000), model, choices: [{ index: 0, delta: { role: "assistant" }, finish_reason: null }] });
74
- for await (const event of streamResult) {
75
- if (event.type === "text_delta") sse(response, { id, object: "chat.completion.chunk", created: Math.floor(Date.now() / 1000), model, choices: [{ index: 0, delta: { content: event.delta }, finish_reason: null }] });
76
- if (event.type === "toolcall_end") sse(response, { id, object: "chat.completion.chunk", created: Math.floor(Date.now() / 1000), model, choices: [{ index: 0, delta: { tool_calls: [{ index: event.contentIndex, id: event.toolCall.id, type: "function", function: { name: event.toolCall.name, arguments: JSON.stringify(event.toolCall.arguments) } }] }, finish_reason: null }] });
77
- if (event.type === "done") sse(response, { id, object: "chat.completion.chunk", created: Math.floor(Date.now() / 1000), model, choices: [{ index: 0, delta: {}, finish_reason: event.reason === "toolUse" ? "tool_calls" : event.reason }] });
78
- if (event.type === "error") throw new Error(event.error.errorMessage ?? "Model request failed");
75
+ let toolIndex = 0;
76
+ try {
77
+ for await (const event of streamResult) {
78
+ if (event.type === "text_delta") sse(response, { id, object: "chat.completion.chunk", created: Math.floor(Date.now() / 1000), model, choices: [{ index: 0, delta: { content: event.delta }, finish_reason: null }] });
79
+ if (event.type === "toolcall_end") sse(response, { id, object: "chat.completion.chunk", created: Math.floor(Date.now() / 1000), model, choices: [{ index: 0, delta: { tool_calls: [{ index: toolIndex++, id: event.toolCall.id, type: "function", function: { name: event.toolCall.name, arguments: JSON.stringify(event.toolCall.arguments) } }] }, finish_reason: null }] });
80
+ if (event.type === "done") sse(response, { id, object: "chat.completion.chunk", created: Math.floor(Date.now() / 1000), model, choices: [{ index: 0, delta: {}, finish_reason: event.reason === "toolUse" ? "tool_calls" : event.reason }] });
81
+ if (event.type === "error") throw new Error(event.error.errorMessage ?? "Model request failed");
82
+ }
83
+ } catch (error) {
84
+ sse(response, { error: { message: error.message ?? String(error), type: "service_error" } });
79
85
  }
80
86
  debug("response SSE", "[DONE]");
81
87
  response.end("data: [DONE]\n\n");
@@ -96,19 +102,47 @@ function responseObject(id, model, message, status = "completed") {
96
102
 
97
103
  async function responses(request, response, body) {
98
104
  const id = `resp_${randomUUID().replaceAll("-", "")}`;
99
- const model = body.model || defaultModel;
100
- const streamResult = await createCompletionStream({ context: messagesFromResponses(body.input), model, tools: body.tools, toolChoice: body.tool_choice });
105
+ const completion = await createCompletionStream({ context: messagesFromResponses(body.input, body.model), model: body.model, tools: body.tools, toolChoice: body.tool_choice });
106
+ const { events: streamResult, model } = completion;
101
107
  if (body.stream) {
102
108
  response.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache", connection: "keep-alive" });
103
109
  const created = { id, object: "response", created_at: Math.floor(Date.now() / 1000), status: "in_progress", model, output: [] };
104
- sse(response, { type: "response.created", response: created });
110
+ sse(response, { type: "response.created", sequence_number: 0, response: created }, true);
105
111
  let sequenceNumber = 0;
106
112
  let outputIndex = 0;
107
- for await (const event of streamResult) {
108
- if (event.type === "text_delta") sse(response, { type: "response.output_text.delta", sequence_number: sequenceNumber++, output_index: 0, content_index: 0, delta: event.delta });
109
- if (event.type === "toolcall_end") sse(response, { type: "response.output_item.done", sequence_number: sequenceNumber++, output_index: outputIndex++, item: { type: "function_call", id: event.toolCall.id, call_id: event.toolCall.id, name: event.toolCall.name, arguments: JSON.stringify(event.toolCall.arguments), status: "completed" } });
110
- if (event.type === "done") sse(response, { type: "response.completed", sequence_number: sequenceNumber++, response: responseObject(id, model, event.message) });
111
- if (event.type === "error") throw new Error(event.error.errorMessage ?? "Model request failed");
113
+ let textStarted = false;
114
+ let text = "";
115
+ let textItem;
116
+ try {
117
+ for await (const event of streamResult) {
118
+ if (event.type === "text_delta") {
119
+ if (!textStarted) {
120
+ textStarted = true;
121
+ textItem = { id: `msg_${randomUUID().replaceAll("-", "")}`, type: "message", status: "in_progress", role: "assistant", content: [] };
122
+ sse(response, { type: "response.output_item.added", sequence_number: ++sequenceNumber, output_index: outputIndex, item: textItem }, true);
123
+ sse(response, { type: "response.content_part.added", sequence_number: ++sequenceNumber, output_index: outputIndex, item_id: textItem.id, content_index: 0, part: { type: "output_text", text: "", annotations: [] } }, true);
124
+ }
125
+ text += event.delta;
126
+ sse(response, { type: "response.output_text.delta", sequence_number: ++sequenceNumber, output_index: outputIndex, item_id: textItem.id, content_index: 0, delta: event.delta }, true);
127
+ }
128
+ if (event.type === "toolcall_end") {
129
+ const item = { type: "function_call", id: event.toolCall.id, call_id: event.toolCall.id, name: event.toolCall.name, arguments: JSON.stringify(event.toolCall.arguments), status: "completed" };
130
+ sse(response, { type: "response.output_item.added", sequence_number: ++sequenceNumber, output_index, item: { ...item, status: "in_progress", arguments: "" } }, true);
131
+ sse(response, { type: "response.function_call_arguments.done", sequence_number: ++sequenceNumber, output_index, item_id: item.id, arguments: item.arguments }, true);
132
+ sse(response, { type: "response.output_item.done", sequence_number: ++sequenceNumber, output_index: outputIndex++, item }, true);
133
+ }
134
+ if (event.type === "done") {
135
+ if (textStarted) {
136
+ sse(response, { type: "response.output_text.done", sequence_number: ++sequenceNumber, output_index, item_id: textItem.id, content_index: 0, text }, true);
137
+ sse(response, { type: "response.content_part.done", sequence_number: ++sequenceNumber, output_index, item_id: textItem.id, content_index: 0, part: { type: "output_text", text, annotations: [] } }, true);
138
+ sse(response, { type: "response.output_item.done", sequence_number: ++sequenceNumber, output_index: outputIndex++, item: { ...textItem, status: "completed", content: [{ type: "output_text", text, annotations: [] }] } }, true);
139
+ }
140
+ sse(response, { type: "response.completed", sequence_number: ++sequenceNumber, response: responseObject(id, model, event.message) }, true);
141
+ }
142
+ if (event.type === "error") throw new Error(event.error.errorMessage ?? "Model request failed");
143
+ }
144
+ } catch (error) {
145
+ sse(response, { type: "error", sequence_number: ++sequenceNumber, error: { message: error.message ?? String(error), type: "service_error" } }, true);
112
146
  }
113
147
  debug("response SSE", "<stream closed>");
114
148
  response.end();
@@ -118,19 +152,19 @@ async function responses(request, response, body) {
118
152
  }
119
153
 
120
154
  async function ask({ prompt, model = defaultModel, tools, toolChoice }) {
121
- const streamResult = await createCompletionStream({
155
+ const completion = await createCompletionStream({
122
156
  context: messagesFromResponses(prompt),
123
157
  model,
124
158
  tools,
125
159
  toolChoice,
126
160
  });
127
- const message = await collect(streamResult);
128
- return { text: contentFromMessage(message), toolCalls: toolCallsFromMessage(message), model };
161
+ const message = await collect(completion.events);
162
+ return { text: contentFromMessage(message), toolCalls: toolCallsFromMessage(message), model: completion.model };
129
163
  }
130
164
 
131
165
  async function mcp(response, body) {
132
166
  const base = { jsonrpc: "2.0", id: body.id };
133
- if (body.method === "initialize") return sendJson(response, 200, { ...base, result: { protocolVersion: body.params?.protocolVersion ?? "2025-03-26", capabilities: { tools: {} }, serverInfo: { name: "service-llm", version: "0.1.0" } } });
167
+ if (body.method === "initialize") return sendJson(response, 200, { ...base, result: { protocolVersion: body.params?.protocolVersion ?? "2025-03-26", capabilities: { tools: {} }, serverInfo: { name: "service-llm", version } } });
134
168
  if (body.method === "notifications/initialized") return response.writeHead(202).end();
135
169
  if (body.method === "ping") return sendJson(response, 200, { ...base, result: {} });
136
170
  if (body.method === "tools/list") return sendJson(response, 200, { ...base, result: { tools: [{ name: "ask", description: "Ask a Codex model a question and optionally allow it to return function tool calls. Tool calls are never executed.", inputSchema: { type: "object", properties: { prompt: { type: "string" }, model: { type: "string" }, tools: { type: "array", items: { type: "object" } }, tool_choice: {} }, required: ["prompt"], additionalProperties: false } }] } });
@@ -197,9 +231,27 @@ export function startServer({ port = 7060, host = "127.0.0.1", apiKeys = [] } =
197
231
  sendJson(response, error.status ?? 500, { error: { message: error.message ?? String(error), type: "service_error" } });
198
232
  }
199
233
  });
200
- server.listen(port, host, () => {
201
- console.error(`service-llm listening on http://${host}:${port}`);
202
- if (debugEnabled) console.error("[service-llm] DEBUG logging enabled");
234
+ server.listen(port, host, async () => {
235
+ const baseUrl = `http://${host}:${port}`;
236
+ console.error(`service-llm v${version}`);
237
+ console.error(`Listening: ${baseUrl}`);
238
+ console.error(`Client authentication: ${allowedKeys.size ? `enabled (${allowedKeys.size} key${allowedKeys.size === 1 ? "" : "s"})` : "disabled"}`);
239
+ try {
240
+ const catalog = await listModels();
241
+ console.error(`Default model: ${catalog.default_model} (${catalog.default_reasoning_effort ?? "low"} reasoning)`);
242
+ console.error(`Supported models: ${catalog.models.length} (run 'service-llm model' to list)`);
243
+ } catch (error) {
244
+ console.error(`Model catalog: unavailable (${error.message ?? String(error)})`);
245
+ }
246
+ console.error("Endpoints:");
247
+ console.error(` Health: ${baseUrl}/health`);
248
+ console.error(` Chat Completions: ${baseUrl}/v1/chat/completions`);
249
+ console.error(` Responses: ${baseUrl}/v1/responses`);
250
+ console.error(` MCP: ${baseUrl}/mcp`);
251
+ console.error(`Debug logging: ${debugEnabled ? "enabled" : "disabled"}`);
252
+ if (!allowedKeys.size && !["127.0.0.1", "localhost", "::1"].includes(host)) {
253
+ console.error("WARNING: The service is listening beyond localhost without client authentication.");
254
+ }
203
255
  });
204
256
  return server;
205
257
  }
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
- export { authPath, getAccessToken, login } from "./auth.js";
1
+ export { authPath, getAccessToken, listModels, login, modelsPath, setDefaultModel } from "./auth.js";
2
2
  export { defaultModel } from "./backend.js";
3
3
  export { startServer } from "./http.js";
4
+ export { version } from "./version.js";
@@ -0,0 +1,3 @@
1
+ import { readFileSync } from "node:fs";
2
+
3
+ export const version = readFileSync(new URL("../VERSION", import.meta.url), "utf8").trim();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@leoustc/service-llm",
3
- "version": "0.1.0",
4
- "description": "Expose a Codex subscription through OpenAI-compatible and MCP endpoints.",
3
+ "version": "0.2.1",
4
+ "description": "Standalone CLI service exposing a Codex subscription through OpenAI-compatible and MCP endpoints.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
7
7
  "bin": {
@@ -11,7 +11,8 @@
11
11
  ".": "./dist/index.js"
12
12
  },
13
13
  "files": [
14
- "dist"
14
+ "dist",
15
+ "VERSION"
15
16
  ],
16
17
  "scripts": {
17
18
  "build": "node ./scripts/build.mjs",
@@ -27,5 +28,5 @@
27
28
  "publishConfig": {
28
29
  "access": "public"
29
30
  },
30
- "license": "MIT"
31
+ "license": "Apache-2.0"
31
32
  }