fwdloop 0.11.0 → 0.13.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 (62) hide show
  1. package/bin/fwdloop +248 -27
  2. package/package.json +1 -1
  3. package/src/ask.js +3 -0
  4. package/src/authoring.js +103 -13
  5. package/src/books.js +23 -2
  6. package/src/canrun.js +36 -0
  7. package/src/config.js +256 -0
  8. package/src/declaration.js +72 -2
  9. package/src/drafter.js +53 -11
  10. package/src/draftspend.js +70 -0
  11. package/src/flow.js +43 -0
  12. package/src/keysfile.js +180 -0
  13. package/src/liveness.js +1 -1
  14. package/src/model-step.js +43 -8
  15. package/src/monthly.js +276 -0
  16. package/src/panel/author.js +482 -0
  17. package/src/panel/authorcard.js +297 -0
  18. package/src/panel/authorflows.js +312 -0
  19. package/src/panel/authorresume.js +149 -0
  20. package/src/panel/authorstart.js +257 -0
  21. package/src/panel/authorvalues.js +110 -0
  22. package/src/panel/data.js +228 -34
  23. package/src/panel/index.html +2073 -124
  24. package/src/panel/resume.js +14 -11
  25. package/src/panel/server.js +150 -117
  26. package/src/panel/settings.js +270 -0
  27. package/src/panel/spawn.js +77 -0
  28. package/src/provider.js +189 -43
  29. package/src/providershapes.js +19 -0
  30. package/src/runner.js +639 -85
  31. package/src/runvalues.js +178 -0
  32. package/src/send.js +10 -3
  33. package/src/setup.js +120 -0
  34. package/types/authoring.d.ts +24 -2
  35. package/types/books.d.ts +14 -2
  36. package/types/canrun.d.ts +32 -0
  37. package/types/config.d.ts +52 -0
  38. package/types/declaration.d.ts +9 -1
  39. package/types/drafter.d.ts +18 -2
  40. package/types/draftspend.d.ts +21 -0
  41. package/types/flow.d.ts +23 -0
  42. package/types/keysfile.d.ts +90 -0
  43. package/types/liveness.d.ts +2 -2
  44. package/types/model-step.d.ts +6 -2
  45. package/types/monthly.d.ts +130 -0
  46. package/types/panel/author.d.ts +335 -0
  47. package/types/panel/authorcard.d.ts +120 -0
  48. package/types/panel/authorflows.d.ts +175 -0
  49. package/types/panel/authorresume.d.ts +32 -0
  50. package/types/panel/authorstart.d.ts +115 -0
  51. package/types/panel/authorvalues.d.ts +62 -0
  52. package/types/panel/data.d.ts +103 -12
  53. package/types/panel/resume.d.ts +8 -1
  54. package/types/panel/server.d.ts +19 -33
  55. package/types/panel/settings.d.ts +23 -0
  56. package/types/panel/spawn.d.ts +30 -0
  57. package/types/provider.d.ts +123 -70
  58. package/types/providershapes.d.ts +11 -0
  59. package/types/runner.d.ts +120 -5
  60. package/types/runvalues.d.ts +97 -0
  61. package/types/send.d.ts +5 -1
  62. package/types/setup.d.ts +83 -0
@@ -0,0 +1,270 @@
1
+ // borrowed-from: bareloop src/panel/settingsroutes.js@2b101d5 — ADAPTED for fwdloop.
2
+ // M4d piece 4 (docs/wiki/the-module-ladder.md, "M4d", scope items 2-3): the Settings routes under
3
+ // `/api/settings/`, dispatched by `src/panel/server.js` AFTER the same gates as every other route
4
+ // (Host, cookie, and for a POST: Origin + the 8 KiB body cap). This file only decides what a settings
5
+ // request means.
6
+ //
7
+ // What it never does (negatives (i) (ii) (ix) (xiv)):
8
+ // - no route WRITES the keys file, and no response carries a key value: a key is read from the merged
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
11
+ // completion, and write no spend row;
12
+ // - no route reads or writes a flow or its cap. The only files touched are config.json (via
13
+ // `updateConfig`) and the keys file (read through `keysForDoor`), both under the one config home.
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
+ import {
17
+ readConfig, updateConfig, ConfigError, providerFieldProblem, cleanBaseUrl,
18
+ } from '../config.js';
19
+ import { SHAPES } from '../providershapes.js';
20
+ import { keysForDoor } from '../keysfile.js';
21
+ import { spendSummary } from '../monthly.js';
22
+
23
+ const DEEPSEEK_BALANCE_URL = 'https://api.deepseek.com/user/balance';
24
+ const TIMEOUT_MS = 4000;
25
+
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
+ const BROKEN_CONFIG = 'Your settings file (config.json) cannot be read. Fix or remove it, then look again.';
30
+
31
+ const isNumberAbove0 = (v) => typeof v === 'number' && Number.isFinite(v) && v > 0;
32
+
33
+ /**
34
+ * @param {{ home?: string, skip?: boolean, env?: Record<string,string|undefined>, fetch?: typeof fetch, now?: () => number }} cfg
35
+ * `home` the config home (undefined = the real `~/.config/fwdloop`); `skip` true under a test process
36
+ * with no `FWDLOOP_CONFIG_HOME` (Settings then touches nothing); `env` the shell side (tests only);
37
+ * `fetch` and `now` are test seams.
38
+ */
39
+ export function createSettings(cfg) {
40
+ const doFetch = cfg.fetch ?? globalThis.fetch;
41
+ const keys = () => keysForDoor({ env: cfg.env, keysHome: cfg.home });
42
+
43
+ /** @param {number} status @param {any} body */
44
+ const reply = (status, body) => ({ status, body });
45
+ /** @param {string} refused @param {string} say @param {number} [status] */
46
+ const refuse = (refused, say, status = 400) => reply(status, { ok: false, refused, say });
47
+
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);
50
+
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
+ }
56
+
57
+ /** config.json, or `{problem}` in plain words when it is broken (never read as "nothing set"). */
58
+ function config() {
59
+ try { return { config: readConfig({ home: cfg.home }), problem: null }; } catch (e) {
60
+ if (!(e instanceof ConfigError)) throw e;
61
+ return { config: {}, problem: BROKEN_CONFIG };
62
+ }
63
+ }
64
+
65
+ function providers() {
66
+ const k = keys();
67
+ const c = config();
68
+ const spend = spendSummary({ home: cfg.home, now: cfg.now });
69
+ const rows = Object.entries(PROVIDER_SLOTS).map(([slot, def]) => {
70
+ 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
+ let keyStatus = 'not set';
74
+ 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';
77
+ return {
78
+ slot,
79
+ label: slot,
80
+ envVar: def.envVar,
81
+ keyStatus,
82
+ model: eff.model,
83
+ shape: eff.shape,
84
+ baseUrl: eff.baseUrl,
85
+ savedBaseUrl: /** @type {Record<string, any>} */ (c.config).providers?.[slot]?.baseUrl ?? '',
86
+ defaults: eff.defaults,
87
+ 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),
93
+ };
94
+ });
95
+ return reply(200, {
96
+ ok: true,
97
+ keysFile: { path: k.path, exists: k.exists, refusal: k.refusal },
98
+ configProblem: c.problem,
99
+ shapes: SHAPES.map(({ id, label }) => ({ id, label })),
100
+ rows,
101
+ });
102
+ }
103
+
104
+ /** The key for a slot, for a header only; or `{why}` in plain words. @param {string} slot @returns {{ key?: string, why?: string }} */
105
+ function keyFor(slot) {
106
+ const k = keys();
107
+ if (!k.ok) return { why: String(k.refusal) };
108
+ const def = PROVIDER_SLOTS[slot];
109
+ const value = k.env[def.envVar];
110
+ if (value === undefined || value === '') return { why: 'No key set for this provider.' };
111
+ 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
+ return { key: value };
113
+ }
114
+
115
+ /** The key goes only in a header, in the form each shape expects. @param {string} shape @param {string} key @returns {Record<string, string>} */
116
+ function authHeaders(shape, key) {
117
+ if (shape === 'anthropic-api') return { 'x-api-key': key, 'anthropic-version': '2023-06-01' };
118
+ if (shape === 'gemini-api') return { 'x-goog-api-key': key };
119
+ return { Authorization: `Bearer ${key}` };
120
+ }
121
+
122
+ /** 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') {
124
+ const ctl = new AbortController();
125
+ const timer = setTimeout(() => ctl.abort(), TIMEOUT_MS);
126
+ try {
127
+ const res = await doFetch(url, { method: 'GET', headers: authHeaders(shape, key), signal: ctl.signal, redirect: 'manual' });
128
+ if (res.status >= 300 && res.status < 400) return { why: 'The provider answered with a redirect; the key was not sent on. Check the Base URL.' };
129
+ if (res.status === 401 || res.status === 403) return { why: 'The provider refused the key.' };
130
+ if (!res.ok) return { why: 'The provider answered with an error.' };
131
+ let body = null;
132
+ try { body = await res.json(); } catch { body = null; }
133
+ return { body };
134
+ } catch (/** @type {any} */ e) {
135
+ if (e?.name === 'AbortError') return { why: 'The provider did not answer in 4 seconds.' };
136
+ return { why: 'Could not reach the provider.' };
137
+ } finally {
138
+ clearTimeout(timer);
139
+ }
140
+ }
141
+
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 });
147
+ const started = Date.now();
148
+ const c = config();
149
+ if (c.problem) return reply(200, { ok: false, why: c.problem });
150
+ 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 });
155
+ }
156
+
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 });
173
+ }
174
+
175
+ /** Validate EVERY field first; write only if all pass. */
176
+ function price(body) {
177
+ const slot = slotOf(body?.slot);
178
+ if (!slot) return refuse('unknown-provider', 'That provider is not known.');
179
+ /** @type {Record<string, number|null>} */
180
+ const patch = {};
181
+ if (Object.hasOwn(body, 'cachedInPerM')) {
182
+ return refuse('bad-price', 'Cached input has no price of its own: it is priced as input. Nothing was saved.');
183
+ }
184
+ for (const f of /** @type {const} */ (['inPerM', 'outPerM'])) {
185
+ 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;
191
+ }
192
+ if (Object.keys(patch).length === 0) return refuse('bad-price', 'Nothing to save.');
193
+ try {
194
+ updateConfig({ prices: { [slot]: patch } }, { home: cfg.home });
195
+ } catch (e) {
196
+ if (!(e instanceof ConfigError)) throw e;
197
+ return refuse('config-broken', `${BROKEN_CONFIG} Nothing was saved.`);
198
+ }
199
+ return reply(200, { ok: true, slot });
200
+ }
201
+
202
+ /** Save a provider slot's name (model id), shape and Base URL. Validate EVERY field first; write only if all pass. */
203
+ function provider(body) {
204
+ const slot = slotOf(body?.slot);
205
+ 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>} */
209
+ const patch = {};
210
+ for (const [key, field] of Object.entries(fields)) {
211
+ if (!Object.hasOwn(body, key)) continue;
212
+ const v = body[key];
213
+ 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);
216
+ }
217
+ if (Object.keys(patch).length === 0) return refuse('bad-provider', 'Nothing to save.');
218
+ try {
219
+ updateConfig({ providers: { [slot]: patch } }, { home: cfg.home });
220
+ } catch (e) {
221
+ if (!(e instanceof ConfigError)) throw e;
222
+ return refuse('config-broken', `${BROKEN_CONFIG} Nothing was saved.`);
223
+ }
224
+ return reply(200, { ok: true, slot });
225
+ }
226
+
227
+ function moneyGet() {
228
+ const c = config();
229
+ const summary = spendSummary({ home: cfg.home, now: cfg.now });
230
+ const limit = c.problem === null && isNumberAbove0(c.config.monthlyLimitUsd) ? c.config.monthlyLimitUsd : null;
231
+ return reply(200, { ok: true, ...summary, monthlyLimitUsd: limit, configProblem: c.problem });
232
+ }
233
+
234
+ function moneyPost(body) {
235
+ if (body === null || typeof body !== 'object' || !Object.hasOwn(body, 'monthlyLimitUsd')) {
236
+ return refuse('bad-limit', 'Send a number above 0, or leave it empty for no limit. Nothing was saved.');
237
+ }
238
+ const raw = body.monthlyLimitUsd;
239
+ const clear = raw === null || raw === '';
240
+ if (!clear && !isNumberAbove0(raw)) return refuse('bad-limit', 'The monthly limit must be a number above 0, or empty for no limit. Nothing was saved.');
241
+ try {
242
+ updateConfig({ monthlyLimitUsd: clear ? null : raw }, { home: cfg.home });
243
+ } catch (e) {
244
+ if (!(e instanceof ConfigError)) throw e;
245
+ return refuse('config-broken', `${BROKEN_CONFIG} Nothing was saved.`);
246
+ }
247
+ return reply(200, { ok: true, monthlyLimitUsd: clear ? null : raw });
248
+ }
249
+
250
+ /**
251
+ * @param {{ method: string, pathname: string, query: URLSearchParams, body: any }} r
252
+ * @returns {Promise<{ status: number, body: any }>}
253
+ */
254
+ async function handle({ method, pathname, query, body }) {
255
+ 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'] };
257
+ 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
+ if (method === 'GET') {
259
+ if (pathname === '/api/settings/providers') return providers();
260
+ if (pathname === '/api/settings/balance') return balance(query);
261
+ return moneyGet();
262
+ }
263
+ if (pathname === '/api/settings/test') return test(body);
264
+ if (pathname === '/api/settings/price') return price(body);
265
+ if (pathname === '/api/settings/provider') return provider(body);
266
+ return moneyPost(body);
267
+ }
268
+
269
+ return { handle };
270
+ }
@@ -0,0 +1,77 @@
1
+ // M4e piece 2a, item 4 (docs/wiki/the-module-ladder.md, "M4e", scope 5): the ONE detached spawn the panel uses
2
+ // for every CLI child it starts — `fwdloop resume` (src/panel/resume.js) and `fwdloop draft` (src/panel/author.js)
3
+ // (and, later, `fwdloop run`). Extracted from resume.js's tryOnce, shape unchanged:
4
+ // process.execPath + the bin + an ARRAY argv (no shell), `detached: true` (own process group, so the child
5
+ // outlives the panel and a group kill reaches only it), `unref()`, stdio -> the log file (mode 0600 on create),
6
+ // env = exactly the object the caller passes.
7
+ // The caller passes the merged keys env (`keysForDoor`) and uses THAT SAME OBJECT as its scrub list (POC (a)
8
+ // wiring rule, M4d) — this function never reads process.env itself.
9
+ import { spawn } from 'node:child_process';
10
+ import { closeSync, openSync, writeFileSync } from 'node:fs';
11
+ import { join } from 'node:path';
12
+
13
+ import { readFileInside } from '../flow.js';
14
+ import { isFwdloopAlive, procStartOf } from '../liveness.js';
15
+ import { PROVIDER_SLOTS } from '../provider.js';
16
+
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
+ const UNKNOWN_FRESH_MS = 10 * 60 * 1000;
19
+
20
+ /**
21
+ * @param {{ bin: string, argv: string[], env: Record<string, string|undefined>, logPath: string }} a
22
+ * @returns {import('node:child_process').ChildProcess} the child (already `unref()`ed; the log fd is closed here)
23
+ */
24
+ export function spawnDetached({
25
+ bin, argv, env, logPath,
26
+ }) {
27
+ const fd = openSync(logPath, 'a', 0o600);
28
+ try {
29
+ const child = spawn(process.execPath, [bin, ...argv], { detached: true, stdio: ['ignore', fd, fd], env });
30
+ child.unref();
31
+ return child;
32
+ } finally {
33
+ closeSync(fd);
34
+ }
35
+ }
36
+
37
+ /**
38
+ * The ONE writer of a panel child's `pid.json` (`<dir>/pid.json`): the pid, its /proc starttime and when it was started.
39
+ * Called right after the spawn by the draft door and the start door. A child with no pid writes nothing.
40
+ * @param {string} dir @param {import('node:child_process').ChildProcess} child
41
+ */
42
+ export function writePidFile(dir, child) {
43
+ if (!Number.isInteger(child.pid)) return;
44
+ writeFileSync(join(dir, 'pid.json'), `${JSON.stringify({ pid: child.pid, procStart: procStartOf(/** @type {number} */ (child.pid)), startedAt: Date.now() })}\n`, { mode: 0o600 });
45
+ }
46
+
47
+ /** One JSON file of a panel folder through the one safe gateway; null when missing, unreadable or not an object. @param {string} dir @param {string} rel */
48
+ export function readJsonFile(dir, rel) {
49
+ const r = readFileInside(dir, rel);
50
+ if (!r.ok) return null;
51
+ try { const j = JSON.parse(r.text); return j && typeof j === 'object' && !Array.isArray(j) ? j : null; } catch { return null; }
52
+ }
53
+
54
+ /**
55
+ * Is the child recorded in `<dir>/pid.json` running? true / false, never null: no pid.json = nothing known to be running =
56
+ * false; a liveness that cannot be told (no /proc) reads as running only while pid.json is fresh (M4c's rule).
57
+ * @param {string} dir
58
+ */
59
+ export function childRunning(dir) {
60
+ const pid = readJsonFile(dir, 'pid.json');
61
+ if (!pid || !Number.isInteger(pid.pid)) return false;
62
+ const alive = isFwdloopAlive(pid.pid, typeof pid.procStart === 'string' ? pid.procStart : null);
63
+ if (alive !== null) return alive;
64
+ return typeof pid.startedAt === 'number' && Date.now() - pid.startedAt <= UNKNOWN_FRESH_MS;
65
+ }
66
+
67
+ /**
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
71
+ */
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;
77
+ }