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.
- package/bin/fwdloop +106 -31
- package/package.json +2 -2
- package/src/authoring.js +23 -11
- package/src/closers.js +5 -0
- package/src/config.js +66 -4
- package/src/declaration.js +25 -1
- package/src/draft-steps.js +79 -0
- package/src/drafter.js +54 -15
- package/src/flowmodel.js +30 -0
- package/src/input-facts.js +12 -3
- package/src/keysfile.js +51 -16
- package/src/model-step.js +13 -11
- package/src/monthly.js +9 -1
- package/src/panel/author.js +81 -22
- package/src/panel/authorcard.js +25 -17
- package/src/panel/authorflows.js +33 -18
- package/src/panel/authorresume.js +9 -8
- package/src/panel/authorstart.js +11 -9
- package/src/panel/data.js +3 -3
- package/src/panel/index.html +516 -146
- package/src/panel/resume.js +3 -3
- package/src/panel/server.js +4 -3
- package/src/panel/settings.js +138 -80
- package/src/panel/spawn.js +15 -9
- package/src/provider.js +136 -178
- package/src/providershapes.js +7 -7
- package/src/runner.js +38 -22
- package/src/thinking.js +55 -0
- package/types/authoring.d.ts +11 -4
- package/types/closers.d.ts +2 -0
- package/types/config.d.ts +9 -1
- package/types/draft-steps.d.ts +14 -0
- package/types/drafter.d.ts +13 -10
- package/types/flowmodel.d.ts +16 -0
- package/types/input-facts.d.ts +6 -1
- package/types/keysfile.d.ts +23 -6
- package/types/model-step.d.ts +1 -1
- package/types/monthly.d.ts +1 -0
- package/types/panel/author.d.ts +44 -6
- package/types/panel/authorcard.d.ts +21 -8
- package/types/panel/authorflows.d.ts +29 -6
- package/types/panel/authorresume.d.ts +2 -1
- package/types/panel/authorstart.d.ts +16 -6
- package/types/panel/data.d.ts +2 -2
- package/types/panel/resume.d.ts +2 -1
- package/types/panel/server.d.ts +3 -1
- package/types/panel/settings.d.ts +3 -1
- package/types/panel/spawn.d.ts +13 -4
- package/types/provider.d.ts +94 -284
- package/types/providershapes.d.ts +3 -4
- package/types/runner.d.ts +2 -4
- package/types/thinking.d.ts +25 -0
package/src/panel/resume.js
CHANGED
|
@@ -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 {
|
|
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 =
|
|
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
|
};
|
package/src/panel/server.js
CHANGED
|
@@ -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`)
|
package/src/panel/settings.js
CHANGED
|
@@ -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
|
|
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
|
-
|
|
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
|
|
49
|
-
const
|
|
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
|
-
/**
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
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 =
|
|
71
|
+
const rows = rowNames(k).map((slot) => {
|
|
70
72
|
const eff = resolveSlot(slot, { config: c.config });
|
|
71
|
-
const
|
|
72
|
-
const
|
|
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(
|
|
76
|
-
else if (k.shellOnly.includes(
|
|
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:
|
|
86
|
+
envVar: slot,
|
|
81
87
|
keyStatus,
|
|
82
|
-
model: eff.model,
|
|
83
88
|
shape: eff.shape,
|
|
84
89
|
baseUrl: eff.baseUrl,
|
|
85
|
-
|
|
86
|
-
defaults: eff.defaults,
|
|
90
|
+
legacyMaxTokens: eff.legacyMaxTokens,
|
|
87
91
|
tokens: spend.byProvider[slot]?.total.tokens ?? 0,
|
|
88
|
-
|
|
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
|
|
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
|
|
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
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
const
|
|
146
|
-
|
|
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
|
|
159
|
+
if (c.problem) return { ok: false, why: c.problem };
|
|
150
160
|
const eff = resolveSlot(slot, { config: c.config });
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
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
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
const
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
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
|
-
/**
|
|
176
|
-
|
|
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
|
-
|
|
180
|
-
|
|
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
|
-
|
|
187
|
-
|
|
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
|
-
|
|
247
|
+
const problem = modelsProblem(list);
|
|
248
|
+
if (problem) return refuse('bad-model', problem);
|
|
193
249
|
try {
|
|
194
|
-
updateConfig({
|
|
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
|
|
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
|
|
207
|
-
|
|
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
|
|
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(
|
|
215
|
-
patch[
|
|
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/
|
|
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/
|
|
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
|
}
|
package/src/panel/spawn.js
CHANGED
|
@@ -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 {
|
|
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
|
|
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
|
|
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(
|
|
73
|
-
|
|
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
|
}
|