xonecas.io
79113
Ma

mini-coding-agent / commit 4b5c4c4

fix: polish around chatgpt as a builtin provider

xonecas2026-10-20 4b5c4c416a3f2ff61994b13ebee7c1225758c084 parent 0c6e4ce

8 files changed

README.md+20−4
@@ -23,6 +23,7 @@ it with `python3 tools/gen_models_dev.py`.
2323 mini # interactive TUI
2424 mini -p '<prompt>' # one turn, print the reply, exit
2525 mini -c <file> # overlay a config file for this run
26+ mini login # sign in with ChatGPT to use your plan
2627
2728 Arguments:
2829
@@ -150,7 +151,7 @@ Keys:
150151
151152 | Key | Default | Meaning |
152153 |---|---|---|
153-| `provider` | unset | provider id; built-ins are `opencode` and `opencode-go`, or a `customProviders` id |
154+| `provider` | unset | provider id; built-ins are `opencode`, `opencode-go` and `openai` (after `mini login`), or a `customProviders` id |
154155 | `model` | unset | model id |
155156 | `thinkingEffort` | unset | one of `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`; unset sends no reasoning parameter and clamps to what the model accepts |
156157 | `theme` | `tokyonight` | TUI palette: `tokyonight`, `oxocarbon`, or `kanagawa`. Read at startup; there is no live reload |
@@ -198,9 +199,24 @@ so one provider may mix APIs and base URLs:
198199
199200 ## Environment
200201
201-The built-in providers read `OPENCODE_API_KEY`. Custom providers read the first
202-present variable in their `envKeys`. A provider without a key is listed but
203-fails at request time.
202+The built-in providers are named, keyed and described by the embedded models.dev
203+document; the agent itself only knows how each one authenticates. `opencode` and
204+`opencode-go` read the first present variable in their `env` list
205+(`OPENCODE_API_KEY`). A provider without a key is listed but fails at request
206+time.
207+
208+## Sign in with ChatGPT
209+
210+`mini login` runs the Sign in with ChatGPT flow and writes
211+`$XDG_CONFIG_HOME/mini-coding-agent/auth.json` (0600). It is the credential for
212+the `openai` provider, which then appears in `/provider` next to the keyed ones;
213+set `provider` to `openai` and pick any model from `/model`. The record is
214+refreshed under one lock per request, so a rotating refresh token is never
215+raced. A record that cannot be refreshed stops the turn with `sign-in expired;
216+run mini login` instead of sending an unauthenticated request.
217+
218+The account decides what is available: the model list comes from the provider
219+and models the account hides are never offered.
204220
205221 ## Sessions
206222
src/agent.zig+9−5
@@ -171,6 +171,15 @@ pub fn runTurn(opts: Options, messages: *std.ArrayList(message_mod.Message), int
171171 };
172172
173173 if (cancelled(opts, listener)) return;
174+ // An OAuth bearer expires, so it is renewed per step, not per session. A
175+ // record that cannot be renewed stops the turn before it is persisted.
176+ var wire_model = model.*;
177+ if (wire_model.oauth) {
178+ wire_model.api_key = auth.token(opts.cancel) orelse {
179+ listener.emit(.{ .err = "sign-in expired; run `mini login`" });
180+ return;
181+ };
182+ }
174183 listener.emit(.{ .phase = .{ .phase = .preparing } });
175184 opts.session.appendRequest(scratch, .{
176185 .provider = model.provider,
@@ -186,11 +195,6 @@ pub fn runTurn(opts: Options, messages: *std.ArrayList(message_mod.Message), int
186195
187196 if (cancelled(opts, listener)) return;
188197 listener.emit(.{ .phase = .{ .phase = .waiting_model } });
189- // An OAuth bearer expires, so it is renewed per step, not per session.
190- var wire_model = model.*;
191- if (wire_model.oauth) {
192- if (auth.token(opts.cancel)) |bearer| wire_model.api_key = bearer;
193- }
194198 var stream_ctx = StreamCtx{ .listener = listener };
195199 const assistant = opts.a.create(message_mod.AssistantMessage) catch {
196200 listener.emit(.{ .err = "out of memory" });
src/api/openai_responses.zig+1−1
@@ -23,7 +23,7 @@ const Body = struct {
2323 store: bool = false,
2424 instructions: ?[]const u8 = null,
2525 max_output_tokens: ?u64 = null,
26- reasoning: ?struct { effort: []const u8 } = null,
26+ reasoning: ?struct { effort: []const u8, summary: []const u8 = "concise" } = null,
2727 input: []const InputItem,
2828 tools: ?api.Tools = null,
2929 };
src/models.zig+84−28
@@ -28,23 +28,20 @@ pub const Model = struct {
2828 oauth: bool = false,
2929 };
3030
31+/// How a provider proves who the user is. Everything else about it — name,
32+/// environment keys, API root, models — comes from the models.dev document.
33+const Credential = enum { env, chatgpt };
34+
3135 const Builtin = struct {
3236 id: []const u8,
33- env_keys: []const []const u8,
34- session_header: ?[]const u8,
37+ credential: Credential,
38+ session_header: ?[]const u8 = null,
3539 };
3640
3741 const builtins = [_]Builtin{
38- .{
39- .id = "opencode-go",
40- .env_keys = &.{"OPENCODE_API_KEY"},
41- .session_header = "x-opencode-session",
42- },
43- .{
44- .id = "opencode",
45- .env_keys = &.{"OPENCODE_API_KEY"},
46- .session_header = "x-opencode-session",
47- },
42+ .{ .id = "opencode", .credential = .env, .session_header = "x-opencode-session" },
43+ .{ .id = "opencode-go", .credential = .env, .session_header = "x-opencode-session" },
44+ .{ .id = "openai", .credential = .chatgpt },
4845 };
4946
5047 const ladder = [_][]const u8{ "off", "minimal", "low", "medium", "high", "xhigh", "max" };
@@ -127,17 +124,25 @@ pub fn resolveNamed(a: std.mem.Allocator, cfg: *const config.Config, provider_id
127124 err.* = "model metadata unavailable";
128125 return null;
129126 };
127+ const p = db.provider(provider_id) orelse {
128+ err.* = unknownProvider(a, provider_id);
129+ return null;
130+ };
130131 const info = db.info(provider_id, model_id) orelse {
131132 err.* = unknownModel(a, model_id, provider_id);
132133 return null;
133134 };
135+ if (b.credential == .chatgpt and !auth.available(a)) {
136+ err.* = notSignedIn(a, provider_id);
137+ return null;
138+ }
134139 return Model{
135140 .id = model_id,
136141 .name = info.name,
137142 .api = info.api,
138143 .provider = provider_id,
139144 .base_url = info.base_url,
140- .api_key = firstEnv(b.env_keys),
145+ .api_key = if (b.credential == .env) firstEnv(p.env) else null,
141146 .effort = clampEffort(info.reasoning, info.effort, cfg.thinking_effort),
142147 .supports_images = info.images,
143148 .context_window = info.context,
@@ -147,6 +152,7 @@ pub fn resolveNamed(a: std.mem.Allocator, cfg: *const config.Config, provider_id
147152 .cost_output = info.cost_output,
148153 .cost_cache_read = info.cost_cache_read,
149154 .session_header = b.session_header,
155+ .oauth = b.credential == .chatgpt,
150156 };
151157 }
152158
@@ -154,8 +160,7 @@ pub fn resolveNamed(a: std.mem.Allocator, cfg: *const config.Config, provider_id
154160 for (p.models) |m| {
155161 if (!std.mem.eql(u8, m.id, model_id)) continue;
156162 if (m.oauth and !auth.available(a)) {
157- err.* = std.fmt.allocPrint(a, "provider \"{s}\" is not signed in; run `mini login`", .{provider_id}) catch
158- "not signed in; run `mini login`";
163+ err.* = notSignedIn(a, provider_id);
159164 return null;
160165 }
161166 return Model{
@@ -181,7 +186,7 @@ pub fn resolveNamed(a: std.mem.Allocator, cfg: *const config.Config, provider_id
181186 return null;
182187 }
183188
184- err.* = std.fmt.allocPrint(a, "unknown provider \"{s}\"", .{provider_id}) catch "unknown provider";
189+ err.* = unknownProvider(a, provider_id);
185190 return null;
186191 }
187192
@@ -193,15 +198,31 @@ fn headerPairs(a: std.mem.Allocator, headers: ?std.json.ArrayHashMap([]const u8)
193198 return out.toOwnedSlice(a) catch &.{};
194199 }
195200
196-const ProviderEntry = struct { id: []const u8, name: []const u8, key_present: bool };
201+const ProviderEntry = struct { id: []const u8, name: []const u8, ready: bool };
202+
203+/// A built-in provider is usable when its credential is on hand: the first of
204+/// the provider's own environment keys, or the sign-in with ChatGPT record.
205+fn usable(b: Builtin, a: std.mem.Allocator, p: modelsdev.Provider) bool {
206+ return switch (b.credential) {
207+ .env => firstEnv(p.env) != null,
208+ .chatgpt => auth.available(a),
209+ };
210+}
197211
198212 pub fn providers(a: std.mem.Allocator, cfg: *const config.Config) []ProviderEntry {
199213 var out: std.ArrayList(ProviderEntry) = .empty;
214+ var db: ?modelsdev.Db = modelsdev.Db.open(a) catch null;
200215 for (builtins) |b| {
201- out.append(a, .{ .id = b.id, .name = b.id, .key_present = firstEnv(b.env_keys) != null }) catch {};
216+ // Name, environment keys and every model fact come from the document.
217+ const p = (if (db) |*d| d.provider(b.id) else null) orelse continue;
218+ out.append(a, .{
219+ .id = b.id,
220+ .name = if (p.name.len > 0) p.name else b.id,
221+ .ready = usable(b, a, p),
222+ }) catch {};
202223 }
203224 for (cfg.custom_providers) |p| {
204- out.append(a, .{ .id = p.id, .name = p.name orelse p.id, .key_present = p.envKeys.len == 0 or firstEnv(p.envKeys) != null }) catch {};
225+ out.append(a, .{ .id = p.id, .name = p.name orelse p.id, .ready = p.envKeys.len == 0 or firstEnv(p.envKeys) != null }) catch {};
205226 }
206227 return out.toOwnedSlice(a) catch &.{};
207228 }
@@ -220,28 +241,54 @@ pub fn listing(
220241 if (custom(cfg, provider_id)) |p| return customListing(a, p);
221242 const b = builtin(provider_id) orelse return error.UnknownProvider;
222243 var db = modelsdev.Db.open(a) catch return error.ModelMetadataUnavailable;
244+ const p = db.provider(provider_id) orelse return error.UnknownProvider;
223245 const base = db.baseUrl(provider_id) orelse return error.UnknownProvider;
224- const key = firstEnv(b.env_keys) orelse return error.MissingApiKey;
246+ const key = switch (b.credential) {
247+ .env => firstEnv(p.env) orelse return error.MissingApiKey,
248+ .chatgpt => auth.token(cancel) orelse return error.NotSignedIn,
249+ };
225250
226251 const url = try std.fmt.allocPrint(a, "{s}/models", .{base});
227252 const authorization = try std.fmt.allocPrint(a, "Bearer {s}", .{key});
228253 const body = try http.get(a, url, &.{.{ .name = "Authorization", .value = authorization }}, cancel);
229254
230- const List = struct {
231- data: []const struct { id: []const u8 },
232- };
233- const parsed = try std.json.parseFromSliceLeaky(List, a, body, .{ .ignore_unknown_fields = true });
234-
255+ const parsed = try std.json.parseFromSliceLeaky(Listed, a, body, .{ .ignore_unknown_fields = true });
235256 var out: std.ArrayList(Entry) = .empty;
236- for (parsed.data) |model| {
237- const info = db.info(provider_id, model.id) orelse continue;
238- try out.append(a, .{ .id = model.id, .name = info.name });
257+ for (parsed.items()) |item| {
258+ const id = item.offer() orelse continue;
259+ const info = db.info(provider_id, id) orelse continue;
260+ try out.append(a, .{ .id = id, .name = info.name });
239261 }
240262 const items = try out.toOwnedSlice(a);
241263 std.mem.sort(Entry, items, {}, entryLess);
242264 return items;
243265 }
244266
267+/// Providers decide the shape of their model list: OpenAI-compatible gateways
268+/// answer `data[].id`, the ChatGPT plan answers `models[].slug` with a
269+/// `visibility` that hides internal models.
270+const Listed = struct {
271+ data: ?[]const Item = null,
272+ models: ?[]const Item = null,
273+
274+ const Item = struct {
275+ id: ?[]const u8 = null,
276+ slug: ?[]const u8 = null,
277+ visibility: ?[]const u8 = null,
278+
279+ fn offer(self: Item) ?[]const u8 {
280+ if (self.visibility) |v| {
281+ if (!std.mem.eql(u8, v, "list")) return null;
282+ }
283+ return self.id orelse self.slug;
284+ }
285+ };
286+
287+ fn items(self: Listed) []const Item {
288+ return self.data orelse self.models orelse &.{};
289+ }
290+};
291+
245292 fn entryLess(_: void, a: Entry, b: Entry) bool {
246293 return std.mem.order(u8, a.id, b.id) == .lt;
247294 }
@@ -290,3 +337,12 @@ pub fn clampNamed(a: std.mem.Allocator, cfg: *const config.Config, provider_id:
290337 fn unknownModel(a: std.mem.Allocator, model_id: []const u8, provider_id: []const u8) []const u8 {
291338 return std.fmt.allocPrint(a, "unknown model \"{s}\" for provider \"{s}\"", .{ model_id, provider_id }) catch "unknown model";
292339 }
340+
341+fn unknownProvider(a: std.mem.Allocator, provider_id: []const u8) []const u8 {
342+ return std.fmt.allocPrint(a, "unknown provider \"{s}\"", .{provider_id}) catch "unknown provider";
343+}
344+
345+fn notSignedIn(a: std.mem.Allocator, provider_id: []const u8) []const u8 {
346+ return std.fmt.allocPrint(a, "provider \"{s}\" is not signed in; run `mini login`", .{provider_id}) catch
347+ "not signed in; run `mini login`";
348+}
src/models_dev.json+1−1
@@ -1 +1 @@
1-{"opencode":{"id":"opencode","env":["OPENCODE_API_KEY"],"npm":"@ai-sdk/openai-compatible","api":"https://opencode.ai/inference/openai/v1","name":"OpenCode","doc":"https://opencode.ai/v2/docs/console/models/","models":{"ling-3.0-flash-fin-free":{"id":"ling-3.0-flash-fin-free","name":"Ling 3.0 Flash Fin Free","description":"Finance-enhanced model for financial research, multi-step investment workflows, and long-horizon planning and execution","family":"ling","attachment":false,"reasoning":true,"re …
1+{"opencode":{"id":"opencode","env":["OPENCODE_API_KEY"],"npm":"@ai-sdk/openai-compatible","api":"https://opencode.ai/inference/openai/v1","name":"OpenCode","doc":"https://opencode.ai/v2/docs/console/models/","models":{"muse-spark-1.3":{"id":"muse-spark-1.3","name":"Muse Spark 1.3","description":"Muse Spark 1.3 is a multimodal reasoning model from Meta for long-running agentic, multi-agent, and coding workflows. It improves long-horizon agent collaboration, instruction following, and coding effic …
src/models_dev.zig+9−1
@@ -50,9 +50,11 @@ const Model = struct {
5050 provider: ?Package = null,
5151 };
5252
53-const Provider = struct {
53+pub const Provider = struct {
5454 api: []const u8 = "",
5555 npm: []const u8 = "",
56+ name: []const u8 = "",
57+ env: []const []const u8 = &.{},
5658 models: std.json.ArrayHashMap(Model) = .{},
5759 };
5860
@@ -72,6 +74,12 @@ pub const Db = struct {
7274 return .{ .a = a, .file = try std.json.parseFromSliceLeaky(File, a, raw, .{ .ignore_unknown_fields = true }) };
7375 }
7476
77+ /// The provider's record: its name, environment keys and metadata all live
78+ /// in the document, never in the agent.
79+ pub fn provider(self: Db, provider_id: []const u8) ?Provider {
80+ return self.file.map.get(provider_id);
81+ }
82+
7583 /// The provider's API root, where its model list lives. A provider's `api`
7684 /// is the base URL of its default wire; when it carries a wire directory
7785 /// the list sits one level up (`.../openai/v1` -> `.../v1`).
src/tui/tui.zig+1−1
@@ -844,7 +844,7 @@ const Tui = struct {
844844 var ids: std.ArrayList([]const u8) = .empty;
845845 var names: std.ArrayList([]const u8) = .empty;
846846 for (entries) |p| {
847- if (!p.key_present) continue;
847+ if (!p.ready) continue;
848848 ids.append(self.a, p.id) catch {};
849849 names.append(self.a, p.name) catch {};
850850 }
tools/gen_models_dev.py+9−2
@@ -13,7 +13,11 @@ import urllib.request
1313
1414 MODELS_DEV = "https://models.dev/api.json"
1515
16-PROVIDERS = ["opencode", "opencode-go"]
16+PROVIDERS = ["opencode", "opencode-go", "openai"]
17+
18+# models.dev omits `api` where the AI SDK default applies. Storing it here keeps
19+# the agent free of per-provider facts: it only ever reads the document.
20+API_DEFAULTS = {"openai": "https://api.openai.com/v1"}
1721
1822
1923 def main():
@@ -26,7 +30,10 @@ def main():
2630 for pid in PROVIDERS:
2731 if pid not in data:
2832 sys.exit("models.dev: provider %r missing" % pid)
29- kept[pid] = data[pid]
33+ provider = dict(data[pid])
34+ if not provider.get("api") and pid in API_DEFAULTS:
35+ provider["api"] = API_DEFAULTS[pid]
36+ kept[pid] = provider
3037
3138 with open(out, "w") as f:
3239 json.dump(kept, f, separators=(",", ":"))