@tiens.nguyen/gu-cli 1.0.909 → 1.0.910
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/cli-token.mjs +7 -1
- package/free-model.mjs +214 -0
- package/gonext_agent_chat.py +9 -1
- package/gu-repl.mjs +112 -1
- package/package.json +2 -1
package/cli-token.mjs
CHANGED
|
@@ -556,7 +556,13 @@ export async function redeemVoucher({ mode, apiBase, hostedBase, token, device,
|
|
|
556
556
|
: res.status === 404 ? "This gu service does not take vouchers yet." : `The gu service answered HTTP ${res.status}.`;
|
|
557
557
|
return { ok: false, why: typeof data?.why === "string" ? data.why : `http-${res.status}`, error };
|
|
558
558
|
}
|
|
559
|
-
return {
|
|
559
|
+
return {
|
|
560
|
+
ok: true,
|
|
561
|
+
days: Number(data?.days ?? 0),
|
|
562
|
+
token: typeof data?.token === "string" ? data.token : "",
|
|
563
|
+
// #557: a free-model code carries a monthly allowance, not days.
|
|
564
|
+
...(data?.kind === "model-tokens" ? { kind: "model-tokens", centsPerMonth: Number(data.centsPerMonth ?? 0), months: Number(data.months ?? 0) } : {}),
|
|
565
|
+
};
|
|
560
566
|
} catch (e) {
|
|
561
567
|
return { ok: false, why: "network", error: e?.name === "TimeoutError" ? "The gu service did not answer in time. Try again." : "Can't reach the gu service right now." };
|
|
562
568
|
}
|
package/free-model.mjs
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE FREE MODEL (task #557, GH #433) — gu's side.
|
|
3
|
+
*
|
|
4
|
+
* A model-tokens voucher (/voucher CODE) gives a small monthly allowance of the owner's model key.
|
|
5
|
+
* gu then FETCHES the preset — endpoint, key, model — from the gu service and applies it like a
|
|
6
|
+
* saved preset (no setup by hand), counts what each turn on it costs, and refuses a new turn once
|
|
7
|
+
* the month's allowance is spent. The key is not in gu: the owner can replace it on the admin page,
|
|
8
|
+
* and gu picks the new one up the next time it fetches (each start, and after /voucher).
|
|
9
|
+
*
|
|
10
|
+
* ~/.gonext/free-model.json (0600) — { url, model, keyId, price, period, allowanceMicro, spentMicro }
|
|
11
|
+
*
|
|
12
|
+
* Money is in MICRO-DOLLARS (1 USD = 1,000,000) so the sums are whole numbers, as on the server
|
|
13
|
+
* (api/src/billing/llmAllowance.ts — the same formula and the same levels).
|
|
14
|
+
*
|
|
15
|
+
* WHAT IS COUNTED: the coder's prompt tokens (fresh at the input price, cached at the cached price
|
|
16
|
+
* only when the PROVIDER reported them — an assumed cache share would under-count) and its output
|
|
17
|
+
* tokens. Charged at the price the server sends, which is the busy-hour one.
|
|
18
|
+
*/
|
|
19
|
+
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
|
|
20
|
+
import { join } from "node:path";
|
|
21
|
+
|
|
22
|
+
export const FREE_MODEL_FILE = "free-model.json";
|
|
23
|
+
/** The key's name in gu's key list — how gu finds it again when the owner rotates it. */
|
|
24
|
+
export const FREE_KEY_NAME = "gu free model";
|
|
25
|
+
export const WARN_AT = 0.8;
|
|
26
|
+
export const LOW_AT = 0.95;
|
|
27
|
+
|
|
28
|
+
export const periodKey = (now = new Date()) => new Date(now).toISOString().slice(0, 7);
|
|
29
|
+
|
|
30
|
+
const whole = (n) => (Number.isFinite(Number(n)) && Number(n) > 0 ? Math.floor(Number(n)) : 0);
|
|
31
|
+
|
|
32
|
+
/** Micro-dollars one turn cost on the free model. Rounds up: many small turns never add up to nothing. */
|
|
33
|
+
export function turnCostMicro({ input = 0, cached = 0, cacheReported = false, output = 0 } = {}, price = {}) {
|
|
34
|
+
const sent = whole(input);
|
|
35
|
+
const hit = cacheReported ? Math.min(whole(cached), sent) : 0;
|
|
36
|
+
const inP = Number(price.inputPerM) || 0;
|
|
37
|
+
const cachedP = Number.isFinite(Number(price.cachedPerM)) ? Number(price.cachedPerM) : inP;
|
|
38
|
+
const outP = Number(price.outputPerM) || 0;
|
|
39
|
+
return Math.ceil((sent - hit) * inP + hit * cachedP + whole(output) * outP);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function levelFor(spent, allowance) {
|
|
43
|
+
if (!(allowance > 0)) return "over";
|
|
44
|
+
const used = spent / allowance;
|
|
45
|
+
return used >= 1 ? "over" : used >= LOW_AT ? "low" : used >= WARN_AT ? "warn" : "ok";
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const sameServer = (a, b) => {
|
|
49
|
+
const n = (u) => String(u ?? "").trim().replace(/\/+$/, "").toLowerCase();
|
|
50
|
+
return Boolean(n(a)) && n(a) === n(b);
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
/** Is this coder URL the free model's? */
|
|
54
|
+
export const isFreeServer = (state, url) => Boolean(state?.url) && sameServer(state.url, url);
|
|
55
|
+
|
|
56
|
+
/** The state as of `now`: a new month starts at zero spent. */
|
|
57
|
+
export function current(state, now = new Date()) {
|
|
58
|
+
if (!state) return null;
|
|
59
|
+
const p = periodKey(now);
|
|
60
|
+
return state.period === p ? state : { ...state, period: p, spentMicro: 0 };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** After a turn on the free model: the new state. */
|
|
64
|
+
export function addTurn(state, usage, now = new Date()) {
|
|
65
|
+
const s = current(state, now);
|
|
66
|
+
if (!s) return null;
|
|
67
|
+
return { ...s, spentMicro: whole(s.spentMicro) + turnCostMicro(usage, s.price) };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** After the service answered the preset: what gu keeps (never the key itself). */
|
|
71
|
+
export function stateFromPreset(preset, prev, now = new Date()) {
|
|
72
|
+
const p = periodKey(now);
|
|
73
|
+
const mine = prev && prev.period === p ? whole(prev.spentMicro) : 0;
|
|
74
|
+
return {
|
|
75
|
+
url: preset.baseUrl,
|
|
76
|
+
model: preset.model,
|
|
77
|
+
keyId: preset.keyId,
|
|
78
|
+
price: preset.price,
|
|
79
|
+
period: p,
|
|
80
|
+
allowanceMicro: whole(preset.allowanceMicro),
|
|
81
|
+
// The higher of ours and the service's: a reinstall cannot reset it, another computer's use counts.
|
|
82
|
+
spentMicro: Math.max(mine, whole(preset.spentMicro)),
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const usd = (micro) => `$${(whole(micro) / 1e6).toFixed(2)}`;
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The line to show, or null. `over` is the refusal itself; warn/low are shown once per level.
|
|
90
|
+
*/
|
|
91
|
+
export function notice(state, now = new Date()) {
|
|
92
|
+
const s = current(state, now);
|
|
93
|
+
if (!s || !s.allowanceMicro) return null;
|
|
94
|
+
const level = levelFor(s.spentMicro, s.allowanceMicro);
|
|
95
|
+
const pct = Math.min(100, Math.floor((100 * whole(s.spentMicro)) / s.allowanceMicro));
|
|
96
|
+
if (level === "over") {
|
|
97
|
+
return { level, text: `Your free model allowance for this month (${usd(s.allowanceMicro)}) is used up. Add your own model key with /model — or a local one with Ollama — to keep going; it renews on the 1st.` };
|
|
98
|
+
}
|
|
99
|
+
if (level === "low") return { level, text: `Free model: ${pct}% of this month's ${usd(s.allowanceMicro)} used — almost gone. Add your own key with /model before it ends.` };
|
|
100
|
+
if (level === "warn") return { level, text: `Free model: ${pct}% of this month's ${usd(s.allowanceMicro)} used.` };
|
|
101
|
+
return { level, text: null };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Is a NEW turn on this coder refused? Only at the START of a turn — never mid-turn — and only when
|
|
106
|
+
* the coder IS the free model. → the sentence, or null.
|
|
107
|
+
*/
|
|
108
|
+
export function blockReason(state, coderUrl, now = new Date()) {
|
|
109
|
+
if (!isFreeServer(state, coderUrl)) return null;
|
|
110
|
+
const n = notice(state, now);
|
|
111
|
+
return n?.level === "over" ? n.text : null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function readState(dir) {
|
|
115
|
+
try {
|
|
116
|
+
const j = JSON.parse(readFileSync(join(dir, FREE_MODEL_FILE), "utf8"));
|
|
117
|
+
return j && typeof j === "object" && typeof j.url === "string" ? j : null;
|
|
118
|
+
} catch {
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function writeState(dir, state) {
|
|
124
|
+
try {
|
|
125
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
126
|
+
writeFileSync(join(dir, FREE_MODEL_FILE), JSON.stringify(state, null, 2) + "\n", { mode: 0o600 });
|
|
127
|
+
return true;
|
|
128
|
+
} catch {
|
|
129
|
+
return false;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async function call(fetchImpl, url, init, timeoutMs) {
|
|
134
|
+
try {
|
|
135
|
+
const r = await fetchImpl(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
|
|
136
|
+
const j = await r.json().catch(() => ({}));
|
|
137
|
+
return { status: r.status, ok: r.ok, body: j ?? {} };
|
|
138
|
+
} catch (e) {
|
|
139
|
+
return { status: 0, ok: false, body: { error: e?.message ?? String(e) } };
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* GET the preset. → { ok: true, preset } | { ok: false, why: "none"|"over"|"not-configured"|"no-token"|"offline", error }
|
|
145
|
+
*/
|
|
146
|
+
export async function fetchPreset({ hostedBase, token, fetchImpl = fetch, timeoutMs = 8000 }) {
|
|
147
|
+
if (!token) return { ok: false, why: "no-token", error: "gu has no token yet." };
|
|
148
|
+
const r = await call(fetchImpl, `${String(hostedBase).replace(/\/+$/, "")}/api/billing/cli-token/model-preset`, {
|
|
149
|
+
headers: { Authorization: `Bearer ${String(token).trim()}` },
|
|
150
|
+
}, timeoutMs);
|
|
151
|
+
if (r.ok && typeof r.body.baseUrl === "string" && typeof r.body.apiKey === "string" && r.body.apiKey) {
|
|
152
|
+
return { ok: true, preset: r.body };
|
|
153
|
+
}
|
|
154
|
+
if (r.status === 0) return { ok: false, why: "offline", error: "could not reach the gu service." };
|
|
155
|
+
const why = ["none", "over", "not-configured"].includes(r.body.why) ? r.body.why : "offline";
|
|
156
|
+
return { ok: false, why, error: String(r.body.error || `HTTP ${r.status}`) };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** POST this month's spend. Best effort: → the spend the service now holds, or null. */
|
|
160
|
+
export async function reportSpend({ hostedBase, token, state, fetchImpl = fetch, timeoutMs = 8000 }) {
|
|
161
|
+
if (!token || !state) return null;
|
|
162
|
+
const r = await call(fetchImpl, `${String(hostedBase).replace(/\/+$/, "")}/api/billing/cli-token/model-usage`, {
|
|
163
|
+
method: "POST",
|
|
164
|
+
headers: { Authorization: `Bearer ${String(token).trim()}`, "Content-Type": "application/json" },
|
|
165
|
+
body: JSON.stringify({ period: state.period, spentMicro: whole(state.spentMicro) }),
|
|
166
|
+
}, timeoutMs);
|
|
167
|
+
return r.ok && Number.isFinite(Number(r.body.spentMicro)) ? Number(r.body.spentMicro) : null;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* APPLY THE PRESET to this account, through the same local-API calls /use-presets uses (preset-apply's
|
|
172
|
+
* `api`): the server is ADDED (or updated) — the person's other providers stay — its key is added as
|
|
173
|
+
* "gu free model" and made that server's default, and the coder and the agent model point at it.
|
|
174
|
+
* `rotateOnly`: the key changed and nothing else is touched (the person may have picked another coder).
|
|
175
|
+
* → { ok: true, rowId, keyAdded } | { ok: false, why }
|
|
176
|
+
*/
|
|
177
|
+
export async function applyPreset(preset, api, { rotateOnly = false } = {}) {
|
|
178
|
+
const settings = await api.settings();
|
|
179
|
+
if (!settings) return { ok: false, why: "couldn't read this account's settings from the local API" };
|
|
180
|
+
const rows = Array.isArray(settings.agentCodingBackends) ? settings.agentCodingBackends : [];
|
|
181
|
+
const mine = rows.find((r) => r && sameServer(r.url, preset.baseUrl));
|
|
182
|
+
if (!rotateOnly || !mine) {
|
|
183
|
+
const nextRows = mine
|
|
184
|
+
? rows.map((r) => (r === mine ? { ...r, defaultModel: preset.model, models: [...new Set([...(r.models ?? []), preset.model])].filter((m) => m !== preset.model), enabled: true } : r))
|
|
185
|
+
: [...rows, { kind: "openai", url: preset.baseUrl, defaultModel: preset.model, models: [], enabled: true }];
|
|
186
|
+
const patch = {
|
|
187
|
+
agentCodingBackends: nextRows,
|
|
188
|
+
...(rotateOnly ? {} : {
|
|
189
|
+
agentCodingModelUrl: preset.baseUrl,
|
|
190
|
+
agentCodingModelName: preset.model,
|
|
191
|
+
agentCodingModelKind: "openai",
|
|
192
|
+
agentModelUrl: preset.baseUrl,
|
|
193
|
+
agentModelName: preset.model,
|
|
194
|
+
agentModel: preset.model,
|
|
195
|
+
}),
|
|
196
|
+
};
|
|
197
|
+
if (!(await api.saveSettings(patch))) return { ok: false, why: "the local API refused the settings" };
|
|
198
|
+
}
|
|
199
|
+
const fresh = (await api.settings()) ?? {};
|
|
200
|
+
const row = (fresh.agentCodingBackends ?? []).find((r) => r && sameServer(r.url, preset.baseUrl));
|
|
201
|
+
if (!row?.id) return { ok: false, why: "the server row was not saved" };
|
|
202
|
+
// The key: re-added only when it changed (its fingerprint), so a restart adds nothing.
|
|
203
|
+
const keys = (await api.keys()) ?? [];
|
|
204
|
+
const named = keys.find((k) => k?.backendId === row.id && k?.name === `${FREE_KEY_NAME} ${preset.keyId}`);
|
|
205
|
+
let keyId = named?.id ?? "";
|
|
206
|
+
let keyAdded = false;
|
|
207
|
+
if (!keyId) {
|
|
208
|
+
keyId = await api.addKey(`${FREE_KEY_NAME} ${preset.keyId}`, preset.apiKey, row.id);
|
|
209
|
+
if (!keyId) return { ok: false, why: "the local API refused the key" };
|
|
210
|
+
keyAdded = true;
|
|
211
|
+
}
|
|
212
|
+
if (!(await api.setDefaultKey(row.id, keyId))) return { ok: false, why: "couldn't make the key that server's default" };
|
|
213
|
+
return { ok: true, rowId: row.id, keyAdded };
|
|
214
|
+
}
|
package/gonext_agent_chat.py
CHANGED
|
@@ -3243,7 +3243,15 @@ _DEEPSEEK_V4_RE = re.compile(r"deepseek[-_.]?v4", re.I)
|
|
|
3243
3243
|
# Hosts known to take DeepSeek's own `thinking` request field (GH #430). Another host serving the
|
|
3244
3244
|
# same model (OpenRouter, Together, vLLM…) spells the switch differently or not at all, so it
|
|
3245
3245
|
# keeps today's request unchanged unless GONEXT_DEEPSEEK_THINKING=off forces the field.
|
|
3246
|
-
|
|
3246
|
+
# GH #433: the Qwen Cloud PAY-AS-YOU-GO host (Singapore) joins the Token Plan one — the free model is
|
|
3247
|
+
# served from it. NOT yet confirmed live there (the docs only show `enable_thinking`); if the host
|
|
3248
|
+
# rejects the field, _repair_request drops it and says so, and the turn simply runs with thinking on.
|
|
3249
|
+
_DEEPSEEK_THINKING_HOSTS = frozenset({
|
|
3250
|
+
"api.deepseek.com",
|
|
3251
|
+
"token-plan.maas.qwencloudapi.com",
|
|
3252
|
+
"ap-southeast-1.maas.qwencloudapi.com",
|
|
3253
|
+
"maas.qwencloudapi.com",
|
|
3254
|
+
})
|
|
3247
3255
|
|
|
3248
3256
|
|
|
3249
3257
|
def _deepseek_thinking_kwargs(model_id, base_url="", env=None) -> dict:
|
package/gu-repl.mjs
CHANGED
|
@@ -1073,7 +1073,7 @@ const COMMANDS = [
|
|
|
1073
1073
|
{ name: "/shells", desc: "long commands the agent left running in the background — status, runtime, command, output; stop one" },
|
|
1074
1074
|
{ name: "/budget", desc: "short view of your API provider budgets and balances (Pro) — the same items as the web /providers page" },
|
|
1075
1075
|
{ name: "/tokens", desc: "break down the last prompt sent to the coding model — how much of it was RAG" },
|
|
1076
|
-
{ name: "/voucher", usage: "/voucher CODE", desc: "use a voucher code —
|
|
1076
|
+
{ name: "/voucher", usage: "/voucher CODE", desc: "use a voucher code — free days for this computer's trial or your free account, or a free model allowance" },
|
|
1077
1077
|
{ name: "/support", desc: "send the gu support team a request with gu's logs attached (secrets masked) — shows what goes first, then asks" },
|
|
1078
1078
|
{ name: "/clear-logs", desc: "show what gu's logs, RAG indexes and old API versions take on disk, then ask what to clear — the logs first" },
|
|
1079
1079
|
{ name: "/prices", usage: "/prices [update]", desc: "the price table and the cache table, and what the last turn and this session cost — \"update\" applies gu's newest published tables" },
|
|
@@ -8889,6 +8889,97 @@ async function noteTurnCost(inputTokens, breakdown, coder = null) {
|
|
|
8889
8889
|
* use marked; what the last turn and this session cost; and, when gu has published newer tables,
|
|
8890
8890
|
* that they are waiting. `/prices update` applies them — the same as clicking the notice.
|
|
8891
8891
|
*/
|
|
8892
|
+
// ---------------------------------------------------------------------------------------------
|
|
8893
|
+
// THE FREE MODEL (task #557, GH #433) — free-model.mjs has the rules; this is the wiring.
|
|
8894
|
+
// A model-tokens voucher gives a monthly allowance of the owner's key. The preset (server, key,
|
|
8895
|
+
// model) is fetched from the gu service and applied; each turn on it is counted; a new turn is
|
|
8896
|
+
// refused once the month's allowance is spent.
|
|
8897
|
+
// ---------------------------------------------------------------------------------------------
|
|
8898
|
+
let freeModel = null; // the saved state (free-model.mjs), or null = no free model on this computer
|
|
8899
|
+
let freeModelNoticed = ""; // the level already shown this month, so a notice is said once
|
|
8900
|
+
const freeModelDir = () => join(homedir(), ".gonext");
|
|
8901
|
+
|
|
8902
|
+
async function freeModelHostedBase() {
|
|
8903
|
+
const { DEFAULT_API_BASE } = await import("./device-login.mjs");
|
|
8904
|
+
return isClientExpert() ? String(process.env.GU_TOKEN_API_BASE ?? "").trim() || DEFAULT_API_BASE : apiBase;
|
|
8905
|
+
}
|
|
8906
|
+
|
|
8907
|
+
/**
|
|
8908
|
+
* Fetch the preset and apply it. First time (announce): the server, the key, and the coder AND agent
|
|
8909
|
+
* model all point at it. Later (a key rotation): only the key is swapped — what the person chose
|
|
8910
|
+
* since stays. Never throws; says why in one line when it cannot.
|
|
8911
|
+
*/
|
|
8912
|
+
async function setUpFreeModel({ token, announce = false } = {}) {
|
|
8913
|
+
try {
|
|
8914
|
+
const fm = await import("./free-model.mjs");
|
|
8915
|
+
const got = await withPendingStatus("fetching your free model", async () =>
|
|
8916
|
+
fm.fetchPreset({ hostedBase: await freeModelHostedBase(), token })
|
|
8917
|
+
);
|
|
8918
|
+
if (!got.ok) {
|
|
8919
|
+
if (announce || got.why === "over") console.log(GUTTER + (got.why === "over" ? yellow(got.error) : dim(got.error)));
|
|
8920
|
+
return false;
|
|
8921
|
+
}
|
|
8922
|
+
const first = !freeModel || freeModel.url !== got.preset.baseUrl;
|
|
8923
|
+
const keyChanged = !first && freeModel.keyId !== got.preset.keyId;
|
|
8924
|
+
if (!first && !keyChanged) {
|
|
8925
|
+
freeModel = fm.stateFromPreset(got.preset, freeModel);
|
|
8926
|
+
fm.writeState(freeModelDir(), freeModel);
|
|
8927
|
+
return true;
|
|
8928
|
+
}
|
|
8929
|
+
const done = await fm.applyPreset(got.preset, replPresetApi(), { rotateOnly: !first });
|
|
8930
|
+
if (!done.ok) {
|
|
8931
|
+
console.log(GUTTER + yellow(`couldn't set up the free model: ${done.why}.`));
|
|
8932
|
+
return false;
|
|
8933
|
+
}
|
|
8934
|
+
freeModel = fm.stateFromPreset(got.preset, freeModel);
|
|
8935
|
+
fm.writeState(freeModelDir(), freeModel);
|
|
8936
|
+
if (first) {
|
|
8937
|
+
await refreshAfterPresetApply(null, { model: got.preset.model, url: got.preset.baseUrl }, { coder: true });
|
|
8938
|
+
console.log(GUTTER + accent(`✓ ${got.preset.model} is now your agent model and your coding model.`) +
|
|
8939
|
+
dim(" Free use renews each month; /model switches back to your own."));
|
|
8940
|
+
}
|
|
8941
|
+
return true;
|
|
8942
|
+
} catch (e) {
|
|
8943
|
+
if (announce) console.log(GUTTER + yellow(`couldn't set up the free model: ${e?.message ?? e}`));
|
|
8944
|
+
return false;
|
|
8945
|
+
}
|
|
8946
|
+
}
|
|
8947
|
+
|
|
8948
|
+
/** At start: load the saved state; if there is one, look for a rotated key or a new month (quietly). */
|
|
8949
|
+
async function freeModelAtStart() {
|
|
8950
|
+
try {
|
|
8951
|
+
const fm = await import("./free-model.mjs");
|
|
8952
|
+
freeModel = fm.readState(freeModelDir());
|
|
8953
|
+
if (!freeModel) return;
|
|
8954
|
+
const ct = await import("./cli-token.mjs");
|
|
8955
|
+
const st = await ct.readState(join(homedir(), ".gonext"));
|
|
8956
|
+
if (st?.token) await setUpFreeModel({ token: st.token });
|
|
8957
|
+
} catch {
|
|
8958
|
+
/* the free model is never worth a failed start */
|
|
8959
|
+
}
|
|
8960
|
+
}
|
|
8961
|
+
|
|
8962
|
+
/** After a turn on the free model: count it, say a notice once per level, tell the service. Never throws. */
|
|
8963
|
+
async function noteFreeModelTurn(inputTokens, breakdown, outputTokens, coder) {
|
|
8964
|
+
try {
|
|
8965
|
+
const fm = await import("./free-model.mjs");
|
|
8966
|
+
if (!freeModel || !fm.isFreeServer(freeModel, coder?.url) || !(inputTokens > 0)) return;
|
|
8967
|
+
const cache = readTurnCache(breakdown) ?? { cached: 0, cacheReported: false };
|
|
8968
|
+
freeModel = fm.addTurn(freeModel, { input: inputTokens, cached: cache.cached, cacheReported: cache.cacheReported, output: outputTokens ?? 0 });
|
|
8969
|
+
fm.writeState(freeModelDir(), freeModel);
|
|
8970
|
+
const n = fm.notice(freeModel);
|
|
8971
|
+
if (n?.text && freeModelNoticed !== `${freeModel.period}:${n.level}`) {
|
|
8972
|
+
freeModelNoticed = `${freeModel.period}:${n.level}`;
|
|
8973
|
+
console.log(GUTTER + (n.level === "ok" ? dim(n.text) : yellow(n.text)) + "\n");
|
|
8974
|
+
}
|
|
8975
|
+
const ct = await import("./cli-token.mjs");
|
|
8976
|
+
const st = await ct.readState(join(homedir(), ".gonext"));
|
|
8977
|
+
void fm.reportSpend({ hostedBase: await freeModelHostedBase(), token: st?.token, state: freeModel });
|
|
8978
|
+
} catch {
|
|
8979
|
+
/* counting is never worth a broken prompt */
|
|
8980
|
+
}
|
|
8981
|
+
}
|
|
8982
|
+
|
|
8892
8983
|
/**
|
|
8893
8984
|
* /voucher CODE (#425) — a marketing code that adds free days. Works on the free trial (no account)
|
|
8894
8985
|
* and on a free account; the service answers with a fresh token that already carries the days, so
|
|
@@ -8929,6 +9020,14 @@ async function runVoucherCommand(line = "/voucher") {
|
|
|
8929
9020
|
licenceBlock = d.enforced && !d.allowed ? d.why : null;
|
|
8930
9021
|
tokenNotice = ct.barNotice({ token: r.token, publicKeyB64: pk, mode: isClientExpert() ? "expert" : "client", now: new Date(), attempted: true, site: ct.siteUrl() });
|
|
8931
9022
|
}
|
|
9023
|
+
if (r.kind === "model-tokens") {
|
|
9024
|
+
const cents = Number(r.centsPerMonth) || 0;
|
|
9025
|
+
console.log(GUTTER + accent(`✓ free model: $${(cents / 100).toFixed(2)} a month for ${r.months} month${r.months === 1 ? "" : "s"}.`));
|
|
9026
|
+
await setUpFreeModel({ token: r.token && check.ok ? r.token : state.token, announce: true });
|
|
9027
|
+
console.log("");
|
|
9028
|
+
if (barPinned()) paintBar();
|
|
9029
|
+
return;
|
|
9030
|
+
}
|
|
8932
9031
|
const p = check.ok ? check.payload : null;
|
|
8933
9032
|
const until = p?.plan === "trial" ? p.paidUntil : p?.plan === "free" && typeof p.freeUntil === "string" ? p.freeUntil : null;
|
|
8934
9033
|
console.log(GUTTER + accent(`✓ +${r.days} free days added.`) + (until ? ` Free on this computer until ${ct.shortDate(until)}.` : ""));
|
|
@@ -12767,6 +12866,16 @@ async function runAgentTurn(history, { attachJobId = "", ownJob = false } = {})
|
|
|
12767
12866
|
console.log(GUTTER + orange("Not sent.") + dim(" " + licenceBlock) + "\n");
|
|
12768
12867
|
return;
|
|
12769
12868
|
}
|
|
12869
|
+
// #557: the free model's month is spent. Only at the START of a turn (never halfway), and only
|
|
12870
|
+
// when the coder IS the free model — your own key and a local model keep working.
|
|
12871
|
+
if (!attachJobId && freeModel) {
|
|
12872
|
+
const fm = await import("./free-model.mjs");
|
|
12873
|
+
const why = fm.blockReason(freeModel, activeCodingUrl());
|
|
12874
|
+
if (why) {
|
|
12875
|
+
console.log(GUTTER + orange("Not sent.") + dim(" " + why) + "\n");
|
|
12876
|
+
return;
|
|
12877
|
+
}
|
|
12878
|
+
}
|
|
12770
12879
|
// TWO THINGS "attaching" used to mean at once (task #302, part 3): the question is NOT sent
|
|
12771
12880
|
// again (skipAsk), and the job is SOMEONE ELSE'S (attached — Ctrl+C only stops watching, its
|
|
12772
12881
|
// tokens are theirs to count). Re-attaching to this terminal's OWN turn after a lost connection
|
|
@@ -15201,6 +15310,7 @@ async function main() {
|
|
|
15201
15310
|
setInterval(() => void refreshLogsSize(), UPDATE_CHECK_MS).unref();
|
|
15202
15311
|
// The gu token (#232): same arrangement — background, never delays the prompt, unref'd.
|
|
15203
15312
|
startupTokenRefresh = refreshCliToken();
|
|
15313
|
+
void startupTokenRefresh.then(() => freeModelAtStart(), () => freeModelAtStart());
|
|
15204
15314
|
setInterval(() => void refreshCliToken(), TOKEN_TICK_MS).unref();
|
|
15205
15315
|
// …and the other-agents count (task #195). Slower than the turn's own poll and skipped while
|
|
15206
15316
|
// a turn runs; unref'd so a pending timer is never the reason gu refuses to exit.
|
|
@@ -16027,6 +16137,7 @@ async function main() {
|
|
|
16027
16137
|
lastTurnTotalOutput = outputTokens ?? 0;
|
|
16028
16138
|
// #323: what this turn's prompt tokens cost — on the token row and in /price.
|
|
16029
16139
|
void noteTurnCost(lastTurnInputTokens, lastPromptBreakdown, turnCoder);
|
|
16140
|
+
void noteFreeModelTurn(lastTurnInputTokens, lastPromptBreakdown, lastTurnOutputTokens, turnCoder);
|
|
16030
16141
|
// A turn that FAILED carries the __TURN_FAILED__:: sentinel: the worker still delivers
|
|
16031
16142
|
// the text (both UIs need to show it), but it is a failure notice, not a reply. Print
|
|
16032
16143
|
// it as one and DROP it — persisting it would re-send "⚠️ your account is suspended" to
|
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.910",
|
|
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",
|
|
@@ -82,6 +82,7 @@
|
|
|
82
82
|
"terminal-hover.mjs",
|
|
83
83
|
"terminal-layout.mjs",
|
|
84
84
|
"turn-queue.mjs",
|
|
85
|
+
"free-model.mjs",
|
|
85
86
|
"terminal-viewport.mjs",
|
|
86
87
|
"terminal-copy.mjs",
|
|
87
88
|
"version-check.mjs",
|