fwdloop 0.15.0 → 0.16.0

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.
Files changed (52) hide show
  1. package/bin/fwdloop +106 -31
  2. package/package.json +2 -2
  3. package/src/authoring.js +23 -11
  4. package/src/closers.js +5 -0
  5. package/src/config.js +66 -4
  6. package/src/declaration.js +25 -1
  7. package/src/draft-steps.js +79 -0
  8. package/src/drafter.js +54 -15
  9. package/src/flowmodel.js +30 -0
  10. package/src/input-facts.js +12 -3
  11. package/src/keysfile.js +51 -16
  12. package/src/model-step.js +13 -11
  13. package/src/monthly.js +9 -1
  14. package/src/panel/author.js +81 -22
  15. package/src/panel/authorcard.js +25 -17
  16. package/src/panel/authorflows.js +33 -18
  17. package/src/panel/authorresume.js +9 -8
  18. package/src/panel/authorstart.js +11 -9
  19. package/src/panel/data.js +3 -3
  20. package/src/panel/index.html +516 -146
  21. package/src/panel/resume.js +3 -3
  22. package/src/panel/server.js +4 -3
  23. package/src/panel/settings.js +138 -80
  24. package/src/panel/spawn.js +15 -9
  25. package/src/provider.js +136 -178
  26. package/src/providershapes.js +7 -7
  27. package/src/runner.js +38 -22
  28. package/src/thinking.js +55 -0
  29. package/types/authoring.d.ts +11 -4
  30. package/types/closers.d.ts +2 -0
  31. package/types/config.d.ts +9 -1
  32. package/types/draft-steps.d.ts +14 -0
  33. package/types/drafter.d.ts +13 -10
  34. package/types/flowmodel.d.ts +16 -0
  35. package/types/input-facts.d.ts +6 -1
  36. package/types/keysfile.d.ts +23 -6
  37. package/types/model-step.d.ts +1 -1
  38. package/types/monthly.d.ts +1 -0
  39. package/types/panel/author.d.ts +44 -6
  40. package/types/panel/authorcard.d.ts +21 -8
  41. package/types/panel/authorflows.d.ts +29 -6
  42. package/types/panel/authorresume.d.ts +2 -1
  43. package/types/panel/authorstart.d.ts +16 -6
  44. package/types/panel/data.d.ts +2 -2
  45. package/types/panel/resume.d.ts +2 -1
  46. package/types/panel/server.d.ts +3 -1
  47. package/types/panel/settings.d.ts +3 -1
  48. package/types/panel/spawn.d.ts +13 -4
  49. package/types/provider.d.ts +94 -284
  50. package/types/providershapes.d.ts +3 -4
  51. package/types/runner.d.ts +2 -4
  52. package/types/thinking.d.ts +25 -0
@@ -42,7 +42,7 @@ import { tmpdir } from 'node:os';
42
42
  import { dirname, join } from 'node:path';
43
43
  import { fileURLToPath } from 'node:url';
44
44
  import { scrub } from '../authoring.js';
45
- import { PROVIDER_SLOTS } from '../provider.js';
45
+ import { keyValues } from '../keysfile.js';
46
46
  import { spawnDetached } from './spawn.js';
47
47
 
48
48
  const HERE = dirname(fileURLToPath(import.meta.url));
@@ -76,7 +76,7 @@ function ensureLogDir(dir) {
76
76
  }
77
77
 
78
78
  /**
79
- * @param {{ root: string, env?: Record<string, string|undefined>, loadEnv?: () => { ok: boolean, env: Record<string, string|undefined>, refusal: string|null }, bin?: string, logDir?: string,
79
+ * @param {{ root: string, env?: Record<string, string|undefined>, loadEnv?: () => { ok: boolean, env: Record<string, string|undefined>, refusal: string|null, keyNames?: string[] }, bin?: string, logDir?: string,
80
80
  * maxTries?: number, windowMs?: number, slotMs?: number }} opts
81
81
  * `loadEnv` (M4d: the keys-file door, called before EVERY spawn so editing the file needs no panel restart) returns the merged env
82
82
  * that is BOTH the child's spawn env AND its scrub list, or a refusal sentence that becomes the attempt's refusal (nothing spawns).
@@ -123,7 +123,7 @@ export function createResumer(opts) {
123
123
  child.once('error', release);
124
124
  // The child's output is quoted in a refusal (`reason`) that reaches HTTP responses and the books: the
125
125
  // provider key(s) of this panel's env are scrubbed here, the one place that reads the log slice (amendment 1 (e)(3)).
126
- const keys = Object.values(PROVIDER_SLOTS).map((p) => runEnv[p.envVar]).filter(Boolean);
126
+ const keys = keyValues(runEnv, loaded.keyNames);
127
127
  const sliceOfLog = () => {
128
128
  try { return scrub(readFileSync(logPath).subarray(offset).toString('utf8').trim(), keys); } catch { return ''; } // offset is in BYTES
129
129
  };
@@ -456,7 +456,8 @@ export function handleRequest(req, res, opts) {
456
456
  if (pathname === '/api/author/live') r = opts.author.live();
457
457
  else if (pathname === '/api/author/flows') r = opts.author.flows();
458
458
  else if (pathname === '/api/author/run-again') r = opts.author.runAgain(url.searchParams.get('flow'), url.searchParams.get('runId'));
459
- else if (pathname === '/api/author/monthly-check') r = opts.author.monthlyCheck(url.searchParams.get('cap'), url.searchParams.get('spent'));
459
+ else if (pathname === '/api/author/monthly-check') r = opts.author.monthlyCheck(url.searchParams.get('cap'), url.searchParams.get('spent'), { provider: url.searchParams.get('provider') ?? undefined, model: url.searchParams.get('model') ?? undefined, flow: url.searchParams.get('flow') ?? undefined });
460
+ else if (pathname === '/api/author/models') r = opts.author.models();
460
461
  else if (pathname === '/api/author/resume-form') r = opts.author.resumeForm(url.searchParams.get('flow'), url.searchParams.get('runId'));
461
462
  else if (sm) r = opts.author.startGet(sm[1]);
462
463
  else if (am) r = opts.author.get(am[1]);
@@ -569,7 +570,7 @@ export function handleRequest(req, res, opts) {
569
570
  * header). Resolves once actually listening; rejects on a bind error
570
571
  * (including `EADDRINUSE`) with a `.port` field on the error for the
571
572
  * caller's message.
572
- * @param {{ port?: number, root: string, settings?: { home?: string, env?: Record<string,string|undefined>, fetch?: typeof fetch, now?: () => number }, resume?: { env?: Record<string,string|undefined>, bin?: string, logDir?: string, maxTries?: number, windowMs?: number, slotMs?: number }, author?: { env?: Record<string,string|undefined>, loadEnv?: () => any, bin?: string } }} opts
573
+ * @param {{ port?: number, root: string, settings?: { home?: string, env?: Record<string,string|undefined>, fetch?: typeof fetch, now?: () => number, openFolderSpawn?: Function, platform?: string }, resume?: { env?: Record<string,string|undefined>, bin?: string, logDir?: string, maxTries?: number, windowMs?: number, slotMs?: number }, author?: { env?: Record<string,string|undefined>, loadEnv?: () => any, bin?: string } }} opts
573
574
  * `resume` and `author` are for tests only (a fake env/bin, a short retry window); the CLI passes none.
574
575
  * @returns {Promise<{ server: import('node:http').Server, port: number, close: () => Promise<void> }>}
575
576
  */
@@ -591,7 +592,7 @@ export function createPanelServer(opts) {
591
592
  // Settings reads and writes only under the one config home: an injected one (tests), else the door's — under a test
592
593
  // process with no FWDLOOP_CONFIG_HOME, Settings is switched off rather than touch the real ~/.config/fwdloop.
593
594
  const settings = createSettings({
594
- home: opts.settings?.home ?? door.home, skip: opts.settings?.home === undefined && door.skip, env: opts.settings?.env, fetch: opts.settings?.fetch, now: opts.settings?.now,
595
+ home: opts.settings?.home ?? door.home, skip: opts.settings?.home === undefined && door.skip, env: opts.settings?.env, fetch: opts.settings?.fetch, now: opts.settings?.now, openFolderSpawn: opts.settings?.openFolderSpawn, platform: opts.settings?.platform,
595
596
  });
596
597
  return new Promise((resolve, reject) => {
597
598
  // Bound port is resolved from the live socket (`server.address().port`)
@@ -7,31 +7,32 @@
7
7
  // What it never does (negatives (i) (ii) (ix) (xiv)):
8
8
  // - no route WRITES the keys file, and no response carries a key value: a key is read from the merged
9
9
  // env only to put in an `Authorization` header, then forgotten;
10
- // - Test and Balance are one GET each (`<baseUrl>/models`, DeepSeek's `/user/balance`), never a
10
+ // - Test and the model list are one GET (`<baseUrl>/models`), never a
11
11
  // completion, and write no spend row;
12
12
  // - no route reads or writes a flow or its cap. The only files touched are config.json (via
13
13
  // `updateConfig`) and the keys file (read through `keysForDoor`), both under the one config home.
14
14
  // Every refusal is a plain sentence in `say`; nothing here puts an HTTP code, an id or a path on the page.
15
- import { PROVIDER_SLOTS, resolvePrices, resolveSlot, checkKeyPreflight } from '../provider.js';
16
15
  import {
17
- readConfig, updateConfig, ConfigError, providerFieldProblem, cleanBaseUrl,
16
+ effectiveModels, resolveSlot, checkKeyPreflight,
17
+ } from '../provider.js';
18
+ import {
19
+ readConfig, updateConfig, ConfigError, providerFieldProblem, cleanBaseUrl, modelsProblem,
18
20
  } from '../config.js';
19
21
  import { SHAPES } from '../providershapes.js';
20
- import { keysForDoor } from '../keysfile.js';
22
+ import { keysForDoor, isKeyName } from '../keysfile.js';
21
23
  import { spendSummary } from '../monthly.js';
24
+ import { spawnOpener as realSpawn } from './spawn.js';
25
+ import { dirname } from 'node:path';
26
+ import { homedir } from 'node:os';
22
27
 
23
- const DEEPSEEK_BALANCE_URL = 'https://api.deepseek.com/user/balance';
24
28
  const TIMEOUT_MS = 4000;
25
29
 
26
- /** Plain words for each price field (the page's two boxes; cached input is priced as input, M4d amendment 2). */
27
- const FIELD_LABEL = Object.freeze({ inPerM: 'Input', outPerM: 'Output' });
28
-
29
30
  const BROKEN_CONFIG = 'Your settings file (config.json) cannot be read. Fix or remove it, then look again.';
30
31
 
31
32
  const isNumberAbove0 = (v) => typeof v === 'number' && Number.isFinite(v) && v > 0;
32
33
 
33
34
  /**
34
- * @param {{ home?: string, skip?: boolean, env?: Record<string,string|undefined>, fetch?: typeof fetch, now?: () => number }} cfg
35
+ * @param {{ home?: string, skip?: boolean, env?: Record<string,string|undefined>, fetch?: typeof fetch, now?: () => number, openFolderSpawn?: Function, platform?: string }} cfg
35
36
  * `home` the config home (undefined = the real `~/.config/fwdloop`); `skip` true under a test process
36
37
  * with no `FWDLOOP_CONFIG_HOME` (Settings then touches nothing); `env` the shell side (tests only);
37
38
  * `fetch` and `now` are test seams.
@@ -45,14 +46,15 @@ export function createSettings(cfg) {
45
46
  /** @param {string} refused @param {string} say @param {number} [status] */
46
47
  const refuse = (refused, say, status = 400) => reply(status, { ok: false, refused, say });
47
48
 
48
- /** The slot named by a request, or null. @param {unknown} slot */
49
- const slotOf = (slot) => (typeof slot === 'string' && Object.hasOwn(PROVIDER_SLOTS, slot) ? slot : null);
49
+ /** The row names: every key in the file with a value, plus a set-up key only the shell holds (M4d amendment 6 item 1). */
50
+ const rowNames = (k) => [...new Set([...k.names, ...k.shellOnly])].sort();
50
51
 
51
- /** Balance is offered only on an OpenAI-compatible slot whose host is api.deepseek.com (bareloop's rule). @param {{ shape: string, baseUrl: string }} eff */
52
- function canBalance(eff) {
53
- if (eff.shape !== 'openai-api') return false;
54
- try { return new URL(eff.baseUrl).host === 'api.deepseek.com'; } catch { return false; }
55
- }
52
+ /** The plain-words refusal for a slot that is not a key name at all, or null (the one rule is `isKeyName`). @param {unknown} slot */
53
+ const notKeyName = (slot) => (typeof slot === 'string' && slot !== '' && !isKeyName(slot)
54
+ ? refuse('not-a-key-name', `${slot} is not a key name. A key name ends in _KEY, like MY_API_KEY. Nothing was saved.`) : null);
55
+
56
+ /** The row named by a request, or null: only a key that is in the keys file (or the shell) is a row. @param {unknown} slot */
57
+ const slotOf = (slot) => (isKeyName(slot) && rowNames(keys()).includes(slot) ? slot : null);
56
58
 
57
59
  /** config.json, or `{problem}` in plain words when it is broken (never read as "nothing set"). */
58
60
  function config() {
@@ -66,30 +68,28 @@ export function createSettings(cfg) {
66
68
  const k = keys();
67
69
  const c = config();
68
70
  const spend = spendSummary({ home: cfg.home, now: cfg.now });
69
- const rows = Object.entries(PROVIDER_SLOTS).map(([slot, def]) => {
71
+ const rows = rowNames(k).map((slot) => {
70
72
  const eff = resolveSlot(slot, { config: c.config });
71
- const p = resolvePrices(eff.model, { slot, config: c.config });
72
- const one = (value, source) => ({ value, source });
73
+ const own = spend.byModel[slot] ?? {};
74
+ const models = effectiveModels(slot, c.config).map(({ model, use, inPerM, outPerM }) => ({
75
+ model, use, ...(inPerM === undefined ? {} : { inPerM }), ...(outPerM === undefined ? {} : { outPerM }),
76
+ // this model's own tokens from the spend rows that name it; absent = no row names it (never 0)
77
+ ...(Object.hasOwn(own, model) ? { tokens: own[model] } : {}),
78
+ }));
73
79
  let keyStatus = 'not set';
74
80
  if (!k.ok) keyStatus = 'refused';
75
- else if (k.names.includes(def.envVar)) keyStatus = 'set in file';
76
- else if (k.shellOnly.includes(def.envVar)) keyStatus = 'found in shell';
81
+ else if (k.names.includes(slot)) keyStatus = 'set in file';
82
+ else if (k.shellOnly.includes(slot)) keyStatus = 'found in shell';
77
83
  return {
78
84
  slot,
79
85
  label: slot,
80
- envVar: def.envVar,
86
+ envVar: slot,
81
87
  keyStatus,
82
- model: eff.model,
83
88
  shape: eff.shape,
84
89
  baseUrl: eff.baseUrl,
85
- savedBaseUrl: /** @type {Record<string, any>} */ (c.config).providers?.[slot]?.baseUrl ?? '',
86
- defaults: eff.defaults,
90
+ legacyMaxTokens: eff.legacyMaxTokens,
87
91
  tokens: spend.byProvider[slot]?.total.tokens ?? 0,
88
- price: {
89
- inPerM: one(p.perM.inPerM, p.source.in),
90
- outPerM: one(p.perM.outPerM, p.source.out),
91
- },
92
- canBalance: canBalance(eff),
92
+ models,
93
93
  };
94
94
  });
95
95
  return reply(200, {
@@ -105,8 +105,7 @@ export function createSettings(cfg) {
105
105
  function keyFor(slot) {
106
106
  const k = keys();
107
107
  if (!k.ok) return { why: String(k.refusal) };
108
- const def = PROVIDER_SLOTS[slot];
109
- const value = k.env[def.envVar];
108
+ const value = k.env[slot];
110
109
  if (value === undefined || value === '') return { why: 'No key set for this provider.' };
111
110
  if (!checkKeyPreflight(slot, k.env).ok) return { why: 'The key has a space or a line break in it. Fix it in your keys file, then reload keys.' };
112
111
  return { key: value };
@@ -120,7 +119,7 @@ export function createSettings(cfg) {
120
119
  }
121
120
 
122
121
  /** One $0 GET with a 4 s deadline and the key only in the header. @param {string} url @param {string} key @returns {Promise<{ body?: any, why?: string }>} */
123
- async function getWithKey(url, key, shape = 'openai-api') {
122
+ async function getWithKey(url, key, shape) {
124
123
  const ctl = new AbortController();
125
124
  const timer = setTimeout(() => ctl.abort(), TIMEOUT_MS);
126
125
  try {
@@ -139,59 +138,116 @@ export function createSettings(cfg) {
139
138
  }
140
139
  }
141
140
 
142
- async function test(body) {
143
- const slot = slotOf(body?.slot);
144
- if (!slot) return refuse('unknown-provider', 'That provider is not known.');
145
- const k = keyFor(slot);
146
- if (k.why) return reply(200, { ok: false, why: k.why });
141
+ /** The model ids a provider's list answer holds, per API shape (`data[].id` for two shapes; the third shape: `models[].name`, minus its `models/` prefix). @param {string} shape @param {any} body @returns {string[]} */
142
+ function idsOf(shape, body) {
143
+ const list = shape === 'gemini-api' ? body?.models : body?.data;
144
+ const key = shape === 'gemini-api' ? 'name' : 'id';
145
+ const ids = (Array.isArray(list) ? list : []).map((m) => (typeof m?.[key] === 'string' ? m[key].replace(/^models\//, '') : '')).filter((id) => id !== '');
146
+ return [...new Set(ids)].sort();
147
+ }
148
+
149
+ /**
150
+ * The ONE model-list call (M4d amendment 6 item 3): one free GET of `<Base URL>/models` with the key in the header only. Test and the page's list
151
+ * both read it. `{ ok:true, models, ms }` or `{ ok:false, why }` in plain words. Writes nothing.
152
+ * @param {unknown} rawSlot
153
+ */
154
+ async function listModels(rawSlot) {
155
+ const slot = slotOf(rawSlot);
156
+ if (!slot) return { unknown: true };
147
157
  const started = Date.now();
148
158
  const c = config();
149
- if (c.problem) return reply(200, { ok: false, why: c.problem });
159
+ if (c.problem) return { ok: false, why: c.problem };
150
160
  const eff = resolveSlot(slot, { config: c.config });
151
- const base = eff.baseUrl !== '' ? eff.baseUrl : 'https://generativelanguage.googleapis.com/v1beta'; // bare-agent's own Gemini address
152
- const r = await getWithKey(`${base}/models`, String(k.key), eff.shape);
153
- if (r.why) return reply(200, { ok: false, why: r.why });
154
- return reply(200, { ok: true, ms: Date.now() - started });
161
+ // the address comes first: a key reaches the env only once its row is set up, so a row with no address has nothing to send yet
162
+ if (eff.baseUrl === '') return { ok: false, why: `Type a Base URL for ${slot} in Settings.` };
163
+ const k = keyFor(slot);
164
+ if (k.why) return { ok: false, why: k.why };
165
+ const r = await getWithKey(`${eff.baseUrl}/models`, String(k.key), eff.shape);
166
+ if (r.why) return { ok: false, why: r.why };
167
+ return { ok: true, models: idsOf(eff.shape, r.body), ms: Date.now() - started };
155
168
  }
156
169
 
157
- async function balance(query) {
158
- const slot = slotOf(query.get('slot'));
159
- if (!slot) return refuse('unknown-provider', 'That provider is not known.');
160
- const c = config();
161
- if (c.problem) return reply(200, { ok: false, why: c.problem });
162
- if (!canBalance(resolveSlot(slot, { config: c.config }))) return reply(200, { ok: false, why: 'Not offered by this provider.' });
163
- const k = keyFor(slot);
164
- if (k.why) return reply(200, { ok: false, why: k.why });
165
- const r = await getWithKey(DEEPSEEK_BALANCE_URL, String(k.key));
166
- if (r.why) return reply(200, { ok: false, why: r.why });
167
- const infos = Array.isArray(r.body?.balance_infos) ? r.body.balance_infos : [];
168
- const balances = infos
169
- .filter((b) => b && typeof b.currency === 'string' && b.total_balance !== undefined)
170
- .map((b) => ({ currency: b.currency, total: String(b.total_balance) }));
171
- if (balances.length === 0) return reply(200, { ok: false, why: 'The provider did not report a balance.' });
172
- return reply(200, { ok: true, balances });
170
+ /**
171
+ * borrowed-from: bareloop src/panel/settingsroutes.js@07c298f (the open-keys-folder route), adapted to fwdloop's reply shape.
172
+ * Opens the FOLDER of the server's own keys file path (never a file, never an editor, never a path from the request) in the OS file
173
+ * manager: argv array, no shell, detached. Another OS, a failed spawn, or a test process with no injected opener: `opened:false` and
174
+ * the folder path, which the page shows as text. `openFolderSpawn` / `platform` are test seams.
175
+ * @param {any} body
176
+ */
177
+ function openKeysFolder(body) {
178
+ if (body !== null && typeof body === 'object' && Object.keys(body).length > 0) {
179
+ return Promise.resolve(refuse('no-path-allowed', 'The keys folder is opened from the panel\'s own settings; a path cannot be sent. Nothing was opened.'));
180
+ }
181
+ const shown = keys().path;
182
+ const dir = dirname(shown.startsWith('~') ? homedir() + shown.slice(1) : shown);
183
+ const cannot = () => reply(200, { ok: true, opened: false, path: dir });
184
+ const platform = cfg.platform ?? process.platform;
185
+ const cmd = platform === 'linux' ? 'xdg-open' : (platform === 'darwin' ? 'open' : null);
186
+ const opener = cfg.openFolderSpawn ?? (process.env.NODE_ENV === 'test' ? null : realSpawn);
187
+ if (!cmd || !opener) return Promise.resolve(cannot());
188
+ return new Promise((resolve) => {
189
+ let child;
190
+ try { child = opener(cmd, [dir], { detached: true, stdio: 'ignore' }); } catch { resolve(cannot()); return; }
191
+ let settled = false;
192
+ child.once('error', () => { if (!settled) { settled = true; resolve(cannot()); } });
193
+ child.once('spawn', () => {
194
+ if (settled) return;
195
+ settled = true;
196
+ if (typeof child.unref === 'function') child.unref();
197
+ resolve(reply(200, { ok: true, opened: true, path: dir }));
198
+ });
199
+ });
200
+ }
201
+
202
+ async function test(body) {
203
+ const bad = notKeyName(body?.slot);
204
+ if (bad) return bad;
205
+ const r = await listModels(body?.slot);
206
+ if (r.unknown) return refuse('unknown-provider', 'That provider is not known.');
207
+ return reply(200, r.ok ? { ok: true, ms: r.ms } : r);
208
+ }
209
+
210
+ async function models(body) {
211
+ const bad = notKeyName(body?.slot);
212
+ if (bad) return bad;
213
+ const r = await listModels(body?.slot);
214
+ if (r.unknown) return refuse('unknown-provider', 'That provider is not known.');
215
+ if (!r.ok) return reply(200, r);
216
+ const ids = r.models ?? [];
217
+ return reply(200, ids.length === 0 ? { ok: false, why: 'The provider did not list any models.' } : { ok: true, models: ids });
173
218
  }
174
219
 
175
- /** Validate EVERY field first; write only if all pass. */
176
- function price(body) {
220
+ /**
221
+ * Save one model line: {slot, model, use?, inPerM?, outPerM?} (a field left out keeps the line's value; a price
222
+ * `null` clears it). The whole slot list is judged by `modelsProblem` (the one rule) BEFORE anything is written;
223
+ * Idea borrowed from bareloop src/panel/settingsroutes.js@caf019b (both prices or neither, :165-179), not copied: the
224
+ * rule here is `modelsProblem` (tick needs both, 0 / 0 allowed, exact sentence).
225
+ */
226
+ function model(body) {
227
+ const bad = notKeyName(body?.slot);
228
+ if (bad) return bad;
177
229
  const slot = slotOf(body?.slot);
178
230
  if (!slot) return refuse('unknown-provider', 'That provider is not known.');
179
- /** @type {Record<string, number|null>} */
180
- const patch = {};
231
+ const c = config();
232
+ if (c.problem) return refuse('config-broken', `${BROKEN_CONFIG} Nothing was saved.`);
181
233
  if (Object.hasOwn(body, 'cachedInPerM')) {
182
234
  return refuse('bad-price', 'Cached input has no price of its own: it is priced as input. Nothing was saved.');
183
235
  }
236
+ if (typeof body.model !== 'string') return refuse('bad-model', 'Pick a model line. Nothing was saved.');
237
+ // the saved list as it is, minus an older file's `thinkingOff` (read by nothing; dropped here, amendment 7)
238
+ const list = effectiveModels(slot, c.config).map((m) => { const { thinkingOff, ...rest } = /** @type {Record<string, any>} */ (m); return { ...rest }; });
239
+ let line = list.find((m) => m.model === body.model);
240
+ if (!line) { line = { model: body.model, use: false }; list.push(line); }
241
+ if (Object.hasOwn(body, 'use')) line.use = body.use;
184
242
  for (const f of /** @type {const} */ (['inPerM', 'outPerM'])) {
185
243
  if (!Object.hasOwn(body, f)) continue;
186
- const v = body[f];
187
- if (v !== null && !isNumberAbove0(v)) {
188
- return refuse('bad-price', `${FIELD_LABEL[f]} price must be a number above 0, or empty to use the default. Nothing was saved.`);
189
- }
190
- patch[f] = v;
244
+ if (body[f] === null) delete line[f];
245
+ else line[f] = body[f];
191
246
  }
192
- if (Object.keys(patch).length === 0) return refuse('bad-price', 'Nothing to save.');
247
+ const problem = modelsProblem(list);
248
+ if (problem) return refuse('bad-model', problem);
193
249
  try {
194
- updateConfig({ prices: { [slot]: patch } }, { home: cfg.home });
250
+ updateConfig({ models: { [slot]: list } }, { home: cfg.home });
195
251
  } catch (e) {
196
252
  if (!(e instanceof ConfigError)) throw e;
197
253
  return refuse('config-broken', `${BROKEN_CONFIG} Nothing was saved.`);
@@ -199,20 +255,21 @@ export function createSettings(cfg) {
199
255
  return reply(200, { ok: true, slot });
200
256
  }
201
257
 
202
- /** Save a provider slot's name (model id), shape and Base URL. Validate EVERY field first; write only if all pass. */
258
+ /** Save a row's shape, Base URL and legacyMaxTokens tick. Validate EVERY field first; write only if all pass. */
203
259
  function provider(body) {
260
+ const bad = notKeyName(body?.slot);
261
+ if (bad) return bad;
204
262
  const slot = slotOf(body?.slot);
205
263
  if (!slot) return refuse('unknown-provider', 'That provider is not known.');
206
- const fields = { name: 'model', shape: 'shape', baseUrl: 'baseUrl' };
207
- const say = { name: 'The name must be a model id: 1 to 200 characters, no spaces.', shape: 'Pick an API shape from the list.', baseUrl: 'The Base URL must be empty (use the default) or start with http:// or https://.' };
208
- /** @type {Record<string, string|null>} */
264
+ const say = { shape: 'Pick an API shape from the list.', baseUrl: 'The Base URL must start with http:// or https://.', legacyMaxTokens: 'The legacy max_tokens tick must be on or off.' };
265
+ /** @type {Record<string, string|boolean|null>} */
209
266
  const patch = {};
210
- for (const [key, field] of Object.entries(fields)) {
267
+ for (const key of Object.keys(say)) {
211
268
  if (!Object.hasOwn(body, key)) continue;
212
269
  const v = body[key];
213
270
  const clearUrl = key === 'baseUrl' && v === '';
214
- if (!clearUrl && providerFieldProblem(field, v) !== null) return refuse('bad-provider', `${say[key]} Nothing was saved.`);
215
- patch[field] = clearUrl ? null : (key === 'baseUrl' ? cleanBaseUrl(v) : v);
271
+ if (!clearUrl && providerFieldProblem(key, v) !== null) return refuse('bad-provider', `${say[key]} Nothing was saved.`);
272
+ patch[key] = clearUrl ? null : (key === 'baseUrl' ? cleanBaseUrl(v) : v);
216
273
  }
217
274
  if (Object.keys(patch).length === 0) return refuse('bad-provider', 'Nothing to save.');
218
275
  try {
@@ -253,15 +310,16 @@ export function createSettings(cfg) {
253
310
  */
254
311
  async function handle({ method, pathname, query, body }) {
255
312
  if (cfg.skip) return refuse('settings-unavailable', 'Settings is not available here.', 404);
256
- const known = { GET: ['/api/settings/providers', '/api/settings/balance', '/api/settings/money'], POST: ['/api/settings/test', '/api/settings/price', '/api/settings/provider', '/api/settings/money'] };
313
+ const known = { GET: ['/api/settings/providers', '/api/settings/money'], POST: ['/api/settings/open-keys-folder', '/api/settings/test', '/api/settings/models', '/api/settings/model', '/api/settings/provider', '/api/settings/money'] };
257
314
  if (!(known[method] ?? []).includes(pathname)) return refuse('no-such-settings-route', 'Settings cannot do that. Keys are typed into your keys file by hand.', 404);
258
315
  if (method === 'GET') {
259
316
  if (pathname === '/api/settings/providers') return providers();
260
- if (pathname === '/api/settings/balance') return balance(query);
261
317
  return moneyGet();
262
318
  }
319
+ if (pathname === '/api/settings/open-keys-folder') return openKeysFolder(body);
263
320
  if (pathname === '/api/settings/test') return test(body);
264
- if (pathname === '/api/settings/price') return price(body);
321
+ if (pathname === '/api/settings/models') return models(body);
322
+ if (pathname === '/api/settings/model') return model(body);
265
323
  if (pathname === '/api/settings/provider') return provider(body);
266
324
  return moneyPost(body);
267
325
  }
@@ -12,11 +12,20 @@ import { join } from 'node:path';
12
12
 
13
13
  import { readFileInside } from '../flow.js';
14
14
  import { isFwdloopAlive, procStartOf } from '../liveness.js';
15
- import { PROVIDER_SLOTS } from '../provider.js';
15
+ import { keyValues } from '../keysfile.js';
16
16
 
17
17
  /** A pid whose liveness cannot be told (no /proc) counts as running only while its pid.json is this fresh (M4c's 10-minute rule). */
18
18
  const UNKNOWN_FRESH_MS = 10 * 60 * 1000;
19
19
 
20
+ /**
21
+ * The ONE spawn for the Settings "Open keys folder" button (borrowed-from: bareloop src/panel/settingsroutes.js@07c298f): the OS file manager
22
+ * (`xdg-open` / `open`) on a folder the server chose, argv array, no shell, detached. Settings calls it only through its injected seam.
23
+ * @param {string} cmd @param {string[]} args @param {import('node:child_process').SpawnOptions} o
24
+ */
25
+ export function spawnOpener(cmd, args, o) {
26
+ return spawn(cmd, args, o);
27
+ }
28
+
20
29
  /**
21
30
  * @param {{ bin: string, argv: string[], env: Record<string, string|undefined>, logPath: string }} a
22
31
  * @returns {import('node:child_process').ChildProcess} the child (already `unref()`ed; the log fd is closed here)
@@ -65,13 +74,10 @@ export function childRunning(dir) {
65
74
  }
66
75
 
67
76
  /**
68
- * The provider key VALUES in the merged env — the scrub list. The env that holds them is the SAME object that is the child's
69
- * spawn env (POC (a), M4d wiring rule), so the list can never differ from what the child was given.
70
- * @param {Record<string, string|undefined>} env
77
+ * The provider key VALUES of a keys load (`keysForDoor`) — the scrub list. The env that holds them is the SAME object that is the child's
78
+ * spawn env (POC (a), M4d wiring rule), and the names are the load's own `keyNames`, so the list can never differ from what the child was given.
79
+ * @param {{ env: Record<string, string|undefined>, keyNames?: string[] }} loaded
71
80
  */
72
- export function providerKeys(env) {
73
- /** @type {string[]} */
74
- const out = [];
75
- for (const p of Object.values(PROVIDER_SLOTS)) { const k = env[p.envVar]; if (typeof k === 'string' && k !== '') out.push(k); }
76
- return out;
81
+ export function providerKeys(loaded) {
82
+ return keyValues(loaded.env, loaded.keyNames);
77
83
  }