@tiens.nguyen/gu-cli 1.0.912 → 1.0.913
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/free-model.mjs +145 -16
- package/gu-repl.mjs +12 -8
- package/package.json +1 -1
package/free-model.mjs
CHANGED
|
@@ -51,15 +51,63 @@ const sameServer = (a, b) => {
|
|
|
51
51
|
};
|
|
52
52
|
|
|
53
53
|
/** Is this coder URL the free model's? */
|
|
54
|
-
export const isFreeServer = (state, url) =>
|
|
54
|
+
export const isFreeServer = (state, url) =>
|
|
55
|
+
Boolean(state?.url) && (sameServer(state.url, url) || (Array.isArray(state.urls) && state.urls.some((u) => sameServer(u, url))));
|
|
55
56
|
|
|
56
57
|
/** The state as of `now`: a new month starts at zero spent. */
|
|
57
58
|
export function current(state, now = new Date()) {
|
|
58
59
|
if (!state) return null;
|
|
59
60
|
const p = periodKey(now);
|
|
60
|
-
|
|
61
|
+
if (state.period === p) return state;
|
|
62
|
+
const providers = Object.fromEntries(Object.entries(state.providers ?? {}).map(([u, v]) => [u, { ...v, spentMicro: 0 }]));
|
|
63
|
+
return { ...state, period: p, spentMicro: 0, providers };
|
|
61
64
|
}
|
|
62
65
|
|
|
66
|
+
/**
|
|
67
|
+
* Which allowance a turn on `url` draws from (GH #445): an extra provider's own, or the primary's. The state is
|
|
68
|
+
* `current()` already. → { extra: url | null, label, allowanceMicro, spentMicro }
|
|
69
|
+
*/
|
|
70
|
+
export function slotFor(state, url) {
|
|
71
|
+
const key = Object.keys(state?.providers ?? {}).find((u) => sameServer(u, url));
|
|
72
|
+
if (key) {
|
|
73
|
+
const v = state.providers[key];
|
|
74
|
+
return { extra: key, label: v.label || safeHost(key), allowanceMicro: whole(v.allowanceMicro), spentMicro: whole(v.spentMicro) };
|
|
75
|
+
}
|
|
76
|
+
return { extra: null, label: "", allowanceMicro: whole(state?.allowanceMicro), spentMicro: whole(state?.spentMicro) };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const safeHost = (u) => {
|
|
80
|
+
try {
|
|
81
|
+
return new URL(u).hostname;
|
|
82
|
+
} catch {
|
|
83
|
+
return String(u);
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Every provider of a preset, the primary first (GH #444): [{ baseUrl, apiKey, keyId, models: [{ id, price }] }].
|
|
89
|
+
* An older server sends only the primary.
|
|
90
|
+
*/
|
|
91
|
+
export function presetProviders(preset) {
|
|
92
|
+
const extras = Array.isArray(preset?.extraProviders) ? preset.extraProviders.filter((p) => p && typeof p.baseUrl === "string") : [];
|
|
93
|
+
return [
|
|
94
|
+
{ baseUrl: preset.baseUrl, apiKey: preset.apiKey || "", keyId: preset.keyId, models: presetModels(preset) },
|
|
95
|
+
...extras.map((p) => ({
|
|
96
|
+
baseUrl: p.baseUrl,
|
|
97
|
+
// "" = this provider's allowance is used up: the service does not hand out its key (nothing to add or change)
|
|
98
|
+
apiKey: p.apiKey || "",
|
|
99
|
+
keyId: p.keyId,
|
|
100
|
+
label: p.label || "",
|
|
101
|
+
allowanceMicro: whole(p.allowanceMicro),
|
|
102
|
+
spentMicro: whole(p.spentMicro),
|
|
103
|
+
models: presetModels({ model: p.models?.[0]?.id, price: p.models?.[0]?.price, models: p.models }),
|
|
104
|
+
})),
|
|
105
|
+
];
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Did the service hand out the primary provider's key? (Not when ITS allowance is used up.) */
|
|
109
|
+
export const hasPrimaryKey = (preset) => Boolean(preset?.apiKey);
|
|
110
|
+
|
|
63
111
|
/** The models the preset offers: [{ id, price }], default first. An older server sends just `model` + `price`. */
|
|
64
112
|
export function presetModels(preset) {
|
|
65
113
|
const list = Array.isArray(preset?.models) ? preset.models.filter((m) => m && typeof m.id === "string" && m.id) : [];
|
|
@@ -70,6 +118,10 @@ export function presetModels(preset) {
|
|
|
70
118
|
* The price a turn on `model` is charged at: that model's own, else the DEAREST of the list — a model the
|
|
71
119
|
* server did not list is never charged as free or cheap.
|
|
72
120
|
*/
|
|
121
|
+
export function allPresetModels(preset) {
|
|
122
|
+
return presetProviders(preset).flatMap((p) => p.models);
|
|
123
|
+
}
|
|
124
|
+
|
|
73
125
|
export function priceForModel(state, model) {
|
|
74
126
|
const m = state?.models ?? {};
|
|
75
127
|
if (model && m[model]) return m[model];
|
|
@@ -82,10 +134,15 @@ export function priceForModel(state, model) {
|
|
|
82
134
|
}
|
|
83
135
|
|
|
84
136
|
/** After a turn on the free model (on `model`, one of its list): the new state. */
|
|
85
|
-
export function addTurn(state, usage, now = new Date(), model = "") {
|
|
137
|
+
export function addTurn(state, usage, now = new Date(), model = "", url = "") {
|
|
86
138
|
const s = current(state, now);
|
|
87
139
|
if (!s) return null;
|
|
88
|
-
|
|
140
|
+
const cost = turnCostMicro(usage, priceForModel(s, model));
|
|
141
|
+
const slot = url ? slotFor(s, url) : null;
|
|
142
|
+
if (slot?.extra) {
|
|
143
|
+
return { ...s, providers: { ...s.providers, [slot.extra]: { ...s.providers[slot.extra], spentMicro: slot.spentMicro + cost } } };
|
|
144
|
+
}
|
|
145
|
+
return { ...s, spentMicro: whole(s.spentMicro) + cost };
|
|
89
146
|
}
|
|
90
147
|
|
|
91
148
|
/** After the service answered the preset: what gu keeps (never the key itself). */
|
|
@@ -97,7 +154,18 @@ export function stateFromPreset(preset, prev, now = new Date()) {
|
|
|
97
154
|
model: preset.model,
|
|
98
155
|
keyId: preset.keyId,
|
|
99
156
|
price: preset.price,
|
|
100
|
-
models: Object.fromEntries(
|
|
157
|
+
models: Object.fromEntries(allPresetModels(preset).map((m) => [m.id, m.price])),
|
|
158
|
+
// Every provider's endpoint: a turn on any of them is the free model's (#444).
|
|
159
|
+
urls: presetProviders(preset).map((p) => p.baseUrl),
|
|
160
|
+
// Each provider's key fingerprint, so a rotated key on any of them is noticed.
|
|
161
|
+
keyIds: Object.fromEntries(presetProviders(preset).map((p) => [p.baseUrl, p.keyId])),
|
|
162
|
+
// Each extra provider's OWN allowance and spend (#445): the higher of ours and the service's, like the primary's.
|
|
163
|
+
providers: Object.fromEntries(
|
|
164
|
+
presetProviders(preset).slice(1).map((p) => {
|
|
165
|
+
const before = prev && prev.period === periodKey(now) ? whole(prev.providers?.[p.baseUrl]?.spentMicro) : 0;
|
|
166
|
+
return [p.baseUrl, { label: p.label, allowanceMicro: p.allowanceMicro, spentMicro: Math.max(before, p.spentMicro) }];
|
|
167
|
+
})
|
|
168
|
+
),
|
|
101
169
|
period: p,
|
|
102
170
|
allowanceMicro: whole(preset.allowanceMicro),
|
|
103
171
|
// The higher of ours and the service's: a reinstall cannot reset it, another computer's use counts.
|
|
@@ -110,26 +178,31 @@ const usd = (micro) => `$${(whole(micro) / 1e6).toFixed(2)}`;
|
|
|
110
178
|
/**
|
|
111
179
|
* The line to show, or null. `over` is the refusal itself; warn/low are shown once per level.
|
|
112
180
|
*/
|
|
113
|
-
export function notice(state, now = new Date()) {
|
|
181
|
+
export function notice(state, now = new Date(), url = "") {
|
|
114
182
|
const s = current(state, now);
|
|
115
|
-
if (!s
|
|
116
|
-
const
|
|
117
|
-
|
|
183
|
+
if (!s) return null;
|
|
184
|
+
const slot = slotFor(s, url);
|
|
185
|
+
if (!slot.allowanceMicro) return null;
|
|
186
|
+
const level = levelFor(slot.spentMicro, slot.allowanceMicro);
|
|
187
|
+
const pct = Math.min(100, Math.floor((100 * slot.spentMicro) / slot.allowanceMicro));
|
|
188
|
+
const name = slot.extra ? slot.label : "free model";
|
|
189
|
+
const Name = slot.extra ? slot.label : "Free model";
|
|
118
190
|
if (level === "over") {
|
|
119
|
-
|
|
191
|
+
const other = slot.extra ? " — or another free model with /model —" : "";
|
|
192
|
+
return { level, text: `Your ${name} allowance for this month (${usd(slot.allowanceMicro)}) is used up. Add your own model key with /model${other} — or a local one with Ollama — to keep going; it renews on the 1st.` };
|
|
120
193
|
}
|
|
121
|
-
if (level === "low") return { level, text:
|
|
122
|
-
if (level === "warn") return { level, text:
|
|
194
|
+
if (level === "low") return { level, text: `${Name}: ${pct}% of this month's ${usd(slot.allowanceMicro)} used — almost gone. Add your own key with /model before it ends.` };
|
|
195
|
+
if (level === "warn") return { level, text: `${Name}: ${pct}% of this month's ${usd(slot.allowanceMicro)} used.` };
|
|
123
196
|
return { level, text: null };
|
|
124
197
|
}
|
|
125
198
|
|
|
126
199
|
/**
|
|
127
200
|
* Is a NEW turn on this coder refused? Only at the START of a turn — never mid-turn — and only when
|
|
128
|
-
* the coder IS the free model. → the sentence, or null.
|
|
201
|
+
* the coder IS the free model (any provider; each has its own allowance). → the sentence, or null.
|
|
129
202
|
*/
|
|
130
203
|
export function blockReason(state, coderUrl, now = new Date()) {
|
|
131
204
|
if (!isFreeServer(state, coderUrl)) return null;
|
|
132
|
-
const n = notice(state, now);
|
|
205
|
+
const n = notice(state, now, coderUrl);
|
|
133
206
|
return n?.level === "over" ? n.text : null;
|
|
134
207
|
}
|
|
135
208
|
|
|
@@ -175,7 +248,8 @@ export async function fetchPreset({ hostedBase, token, fetchImpl = fetch, timeou
|
|
|
175
248
|
const r = await call(fetchImpl, `${String(hostedBase).replace(/\/+$/, "")}/api/billing/cli-token/model-preset`, {
|
|
176
249
|
headers: { Authorization: `Bearer ${String(token).trim()}` },
|
|
177
250
|
}, timeoutMs);
|
|
178
|
-
|
|
251
|
+
// The primary's key is "" when ITS allowance is used up but another provider's is not (GH #445): still a preset.
|
|
252
|
+
if (r.ok && typeof r.body.baseUrl === "string" && typeof r.body.apiKey === "string" && (r.body.apiKey || r.body.over === true)) {
|
|
179
253
|
return { ok: true, preset: r.body };
|
|
180
254
|
}
|
|
181
255
|
if (r.status === 0) return { ok: false, why: "offline", error: "could not reach the gu service." };
|
|
@@ -189,7 +263,11 @@ export async function reportSpend({ hostedBase, token, state, fetchImpl = fetch,
|
|
|
189
263
|
const r = await call(fetchImpl, `${String(hostedBase).replace(/\/+$/, "")}/api/billing/cli-token/model-usage`, {
|
|
190
264
|
method: "POST",
|
|
191
265
|
headers: { Authorization: `Bearer ${String(token).trim()}`, "Content-Type": "application/json" },
|
|
192
|
-
body: JSON.stringify({
|
|
266
|
+
body: JSON.stringify({
|
|
267
|
+
period: state.period,
|
|
268
|
+
spentMicro: whole(state.spentMicro),
|
|
269
|
+
extras: Object.entries(state.providers ?? {}).map(([baseUrl, v]) => ({ baseUrl, spentMicro: whole(v.spentMicro) })),
|
|
270
|
+
}),
|
|
193
271
|
}, timeoutMs);
|
|
194
272
|
return r.ok && Number.isFinite(Number(r.body.spentMicro)) ? Number(r.body.spentMicro) : null;
|
|
195
273
|
}
|
|
@@ -202,6 +280,17 @@ export async function reportSpend({ hostedBase, token, state, fetchImpl = fetch,
|
|
|
202
280
|
* → { ok: true, rowId, keyAdded } | { ok: false, why }
|
|
203
281
|
*/
|
|
204
282
|
export async function applyPreset(preset, api, { rotateOnly = false } = {}) {
|
|
283
|
+
// The primary's allowance is used up (its key withheld): nothing to add or switch for it; the other providers still apply.
|
|
284
|
+
if (!preset.apiKey) {
|
|
285
|
+
let added = false;
|
|
286
|
+
for (const p of presetProviders(preset).slice(1)) {
|
|
287
|
+
if (!p.apiKey) continue;
|
|
288
|
+
const r = await applyExtraProvider(p, api);
|
|
289
|
+
if (!r.ok) return r;
|
|
290
|
+
added = added || r.keyAdded;
|
|
291
|
+
}
|
|
292
|
+
return { ok: true, rowId: "", keyAdded: added };
|
|
293
|
+
}
|
|
205
294
|
const settings = await api.settings();
|
|
206
295
|
if (!settings) return { ok: false, why: "couldn't read this account's settings from the local API" };
|
|
207
296
|
const rows = Array.isArray(settings.agentCodingBackends) ? settings.agentCodingBackends : [];
|
|
@@ -247,5 +336,45 @@ export async function applyPreset(preset, api, { rotateOnly = false } = {}) {
|
|
|
247
336
|
keyAdded = true;
|
|
248
337
|
}
|
|
249
338
|
if (!(await api.setDefaultKey(row.id, keyId))) return { ok: false, why: "couldn't make the key that server's default" };
|
|
339
|
+
// The other providers (#444): a server row and a key each. They never change the coder or the agent model.
|
|
340
|
+
for (const extraProvider of presetProviders(preset).slice(1)) {
|
|
341
|
+
if (!extraProvider.apiKey) continue; // that provider's allowance is used up
|
|
342
|
+
const r = await applyExtraProvider(extraProvider, api);
|
|
343
|
+
if (!r.ok) return r;
|
|
344
|
+
keyAdded = keyAdded || r.keyAdded;
|
|
345
|
+
}
|
|
250
346
|
return { ok: true, rowId: row.id, keyAdded };
|
|
251
347
|
}
|
|
348
|
+
|
|
349
|
+
async function applyExtraProvider(p, api) {
|
|
350
|
+
const ids = p.models.map((m) => m.id);
|
|
351
|
+
const settings = await api.settings();
|
|
352
|
+
if (!settings) return { ok: false, why: "couldn't read this account's settings from the local API" };
|
|
353
|
+
const rows = Array.isArray(settings.agentCodingBackends) ? settings.agentCodingBackends : [];
|
|
354
|
+
const mine = rows.find((r) => r && sameServer(r.url, p.baseUrl));
|
|
355
|
+
if (!mine) {
|
|
356
|
+
const next = [...rows, { kind: "openai", url: p.baseUrl, defaultModel: ids[0], models: ids.slice(1), enabled: true }];
|
|
357
|
+
if (!(await api.saveSettings({ agentCodingBackends: next }))) return { ok: false, why: "the local API refused the settings" };
|
|
358
|
+
} else {
|
|
359
|
+
const def = mine.defaultModel || ids[0];
|
|
360
|
+
const list = [...new Set([...(mine.models ?? []), ...ids])].filter((m) => m !== def);
|
|
361
|
+
if (JSON.stringify([...list].sort()) !== JSON.stringify([...(mine.models ?? [])].sort())) {
|
|
362
|
+
const next = rows.map((r) => (r === mine ? { ...r, models: list, enabled: true } : r));
|
|
363
|
+
if (!(await api.saveSettings({ agentCodingBackends: next }))) return { ok: false, why: "the local API refused the settings" };
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
const fresh = (await api.settings()) ?? {};
|
|
367
|
+
const row = (fresh.agentCodingBackends ?? []).find((r) => r && sameServer(r.url, p.baseUrl));
|
|
368
|
+
if (!row?.id) return { ok: false, why: "the server row was not saved" };
|
|
369
|
+
const keys = (await api.keys()) ?? [];
|
|
370
|
+
const named = keys.find((k) => k?.backendId === row.id && k?.name === `${FREE_KEY_NAME} ${p.keyId}`);
|
|
371
|
+
let keyId = named?.id ?? "";
|
|
372
|
+
let keyAdded = false;
|
|
373
|
+
if (!keyId) {
|
|
374
|
+
keyId = await api.addKey(`${FREE_KEY_NAME} ${p.keyId}`, p.apiKey, row.id);
|
|
375
|
+
if (!keyId) return { ok: false, why: "the local API refused the key" };
|
|
376
|
+
keyAdded = true;
|
|
377
|
+
}
|
|
378
|
+
if (!(await api.setDefaultKey(row.id, keyId))) return { ok: false, why: "couldn't make the key that server's default" };
|
|
379
|
+
return { ok: true, keyAdded };
|
|
380
|
+
}
|
package/gu-repl.mjs
CHANGED
|
@@ -8925,9 +8925,12 @@ async function setUpFreeModel({ token, announce = false } = {}) {
|
|
|
8925
8925
|
return false;
|
|
8926
8926
|
}
|
|
8927
8927
|
const first = !freeModel || freeModel.url !== got.preset.baseUrl;
|
|
8928
|
-
|
|
8929
|
-
|
|
8930
|
-
const
|
|
8928
|
+
// A rotated key on ANY provider (the primary's, or an extra one's) counts (GH #444).
|
|
8929
|
+
const keysNow = JSON.stringify(Object.fromEntries(fm.presetProviders(got.preset).map((p) => [p.baseUrl, p.keyId])));
|
|
8930
|
+
const keysThen = JSON.stringify(freeModel?.keyIds ?? Object.fromEntries([[freeModel?.url, freeModel?.keyId]]));
|
|
8931
|
+
const keyChanged = !first && keysNow !== keysThen;
|
|
8932
|
+
// The owner added or removed a model or a provider: the server rows' lists follow (what the person is on stays).
|
|
8933
|
+
const ids = (p) => fm.allPresetModels(p).map((m) => m.id).join(",");
|
|
8931
8934
|
const listChanged = !first && !keyChanged && Object.keys(freeModel.models ?? {}).join(",") !== ids(got.preset);
|
|
8932
8935
|
if (!first && !keyChanged && !listChanged) {
|
|
8933
8936
|
freeModel = fm.stateFromPreset(got.preset, freeModel);
|
|
@@ -8941,7 +8944,7 @@ async function setUpFreeModel({ token, announce = false } = {}) {
|
|
|
8941
8944
|
}
|
|
8942
8945
|
freeModel = fm.stateFromPreset(got.preset, freeModel);
|
|
8943
8946
|
fm.writeState(freeModelDir(), freeModel);
|
|
8944
|
-
if (first) {
|
|
8947
|
+
if (first && fm.hasPrimaryKey(got.preset)) {
|
|
8945
8948
|
await refreshAfterPresetApply(null, { model: got.preset.model, url: got.preset.baseUrl }, { coder: true });
|
|
8946
8949
|
console.log(GUTTER + accent(`✓ ${got.preset.model} is now your agent model and your coding model.`) +
|
|
8947
8950
|
dim(" Free use renews each month; /model switches back to your own."));
|
|
@@ -8974,11 +8977,12 @@ async function noteFreeModelTurn(inputTokens, breakdown, outputTokens, coder) {
|
|
|
8974
8977
|
const fm = await import("./free-model.mjs");
|
|
8975
8978
|
if (!freeModel || !fm.isFreeServer(freeModel, coder?.url) || !(inputTokens > 0)) return;
|
|
8976
8979
|
const cache = readTurnCache(breakdown) ?? { cached: 0, cacheReported: false };
|
|
8977
|
-
freeModel = fm.addTurn(freeModel, { input: inputTokens, cached: cache.cached, cacheReported: cache.cacheReported, output: outputTokens ?? 0 }, new Date(), coder?.model);
|
|
8980
|
+
freeModel = fm.addTurn(freeModel, { input: inputTokens, cached: cache.cached, cacheReported: cache.cacheReported, output: outputTokens ?? 0 }, new Date(), coder?.model, coder?.url);
|
|
8978
8981
|
fm.writeState(freeModelDir(), freeModel);
|
|
8979
|
-
const n = fm.notice(freeModel);
|
|
8980
|
-
|
|
8981
|
-
|
|
8982
|
+
const n = fm.notice(freeModel, new Date(), coder?.url);
|
|
8983
|
+
const noticeKey = `${freeModel.period}:${fm.slotFor(freeModel, coder?.url).extra ?? "main"}:${n?.level}`;
|
|
8984
|
+
if (n?.text && freeModelNoticed !== noticeKey) {
|
|
8985
|
+
freeModelNoticed = noticeKey;
|
|
8982
8986
|
console.log(GUTTER + (n.level === "ok" ? dim(n.text) : yellow(n.text)) + "\n");
|
|
8983
8987
|
}
|
|
8984
8988
|
const ct = await import("./cli-token.mjs");
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tiens.nguyen/gu-cli",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.913",
|
|
4
4
|
"description": "gu: the coding agent in your terminal. It reads your repo, makes the change and runs the tests, with your own models (Ollama or any OpenAI-compatible provider). Free installs keep the agent, its API and its database on your machine. macOS, Linux and Windows.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|