fwdloop 0.10.0 → 0.12.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 +130 -20
- package/package.json +1 -1
- package/src/ask.js +200 -8
- package/src/authoring.js +34 -6
- package/src/config.js +255 -0
- package/src/drafter.js +12 -8
- package/src/keysfile.js +180 -0
- package/src/liveness.js +7 -7
- package/src/model-step.js +16 -6
- package/src/monthly.js +231 -0
- package/src/panel/data.js +200 -73
- package/src/panel/index.html +750 -120
- package/src/panel/lock.js +42 -0
- package/src/panel/resume.js +43 -7
- package/src/panel/server.js +295 -47
- package/src/panel/settings.js +268 -0
- package/src/provider.js +194 -35
- package/src/providershapes.js +19 -0
- package/src/runner.js +47 -10
- package/types/ask.d.ts +70 -1
- package/types/authoring.d.ts +3 -2
- package/types/config.d.ts +51 -0
- package/types/drafter.d.ts +4 -2
- package/types/keysfile.d.ts +90 -0
- package/types/liveness.d.ts +2 -1
- package/types/model-step.d.ts +3 -1
- package/types/monthly.d.ts +109 -0
- package/types/panel/data.d.ts +108 -29
- package/types/panel/lock.d.ts +21 -0
- package/types/panel/resume.d.ts +12 -1
- package/types/panel/server.d.ts +39 -3
- package/types/panel/settings.d.ts +23 -0
- package/types/provider.d.ts +126 -70
- package/types/providershapes.d.ts +11 -0
package/src/authoring.js
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
|
|
16
16
|
import { createHash } from 'node:crypto';
|
|
17
17
|
import {
|
|
18
|
-
existsSync, mkdirSync, readFileSync, rmdirSync, writeFileSync,
|
|
18
|
+
existsSync, mkdirSync, readFileSync, realpathSync, rmdirSync, writeFileSync,
|
|
19
19
|
} from 'node:fs';
|
|
20
20
|
import path from 'node:path';
|
|
21
21
|
|
|
@@ -97,10 +97,13 @@ export const costText = (n, spendComplete = true) => {
|
|
|
97
97
|
const usd = costText;
|
|
98
98
|
|
|
99
99
|
/** Plain-text readout of what the human is about to sign. Pure. */
|
|
100
|
-
export function buildReadout({
|
|
100
|
+
export function buildReadout({
|
|
101
|
+
declaration, arbiter, lines, name, modelId, costUsd, rounds, spendComplete, root,
|
|
102
|
+
}) {
|
|
101
103
|
const out = [];
|
|
102
104
|
out.push(`DRAFT READOUT — NOT SIGNED — flow "${name}"`, '');
|
|
103
105
|
out.push(`Drafted by: ${modelId ?? '?'} in ${rounds} round(s), cost ${usd(costUsd, spendComplete)}`);
|
|
106
|
+
if (typeof root === 'string') out.push(`Flows root: ${root} (the flow is written to <flows root>/${name} when you sign)`);
|
|
104
107
|
out.push(`Cap per run (signed by you in the prose): $${arbiter.capUsd}`, '');
|
|
105
108
|
out.push('INPUTS');
|
|
106
109
|
for (const s of arbiter.sources) {
|
|
@@ -128,6 +131,20 @@ export function buildReadout({ declaration, arbiter, lines, name, modelId, costU
|
|
|
128
131
|
return `${out.join('\n')}\n`;
|
|
129
132
|
}
|
|
130
133
|
|
|
134
|
+
/** realpath of a path that may not exist yet: the real path of its nearest existing ancestor plus the rest. */
|
|
135
|
+
function realpathOfNew(p) {
|
|
136
|
+
const rest = [];
|
|
137
|
+
let cur = path.resolve(p);
|
|
138
|
+
for (;;) {
|
|
139
|
+
try { return path.join(realpathSync(cur), ...rest.reverse()); } catch (e) {
|
|
140
|
+
const up = path.dirname(cur);
|
|
141
|
+
if (up === cur || e.code === 'EACCES') return path.resolve(p);
|
|
142
|
+
rest.push(path.basename(cur));
|
|
143
|
+
cur = up;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
131
148
|
/** Read the prose file. Refuses (a red, never a throw) on unreadable or blank. */
|
|
132
149
|
export function readProseFile(file) {
|
|
133
150
|
let text;
|
|
@@ -153,6 +170,13 @@ export async function draftToDir({
|
|
|
153
170
|
if (!nameCheck.ok) return refuse([nameCheck.red]);
|
|
154
171
|
if (typeof root !== 'string' || root === '') return refuse(['draft: --root <flows dir> is required']);
|
|
155
172
|
if (!(budgetUsd > 0)) return refuse(['draft: budget must be a positive number']);
|
|
173
|
+
// An unsigned draft folder inside the flows root would list as a flow in the panel and Inbox (checked by realpath, at use time).
|
|
174
|
+
const realRoot = realpathOfNew(root);
|
|
175
|
+
const realDir = realpathOfNew(dir);
|
|
176
|
+
const rel = path.relative(realRoot, realDir);
|
|
177
|
+
if (rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel))) {
|
|
178
|
+
return refuse([`draft: "${dir}" is inside the flows root "${root}" — an unsigned draft would show as a flow; use a --out outside the flows root`]);
|
|
179
|
+
}
|
|
156
180
|
const read = readProseFile(proseFile);
|
|
157
181
|
if (!read.ok) return refuse([String(read.red)]);
|
|
158
182
|
const prose = { text: String(read.text) };
|
|
@@ -164,6 +188,8 @@ export async function draftToDir({
|
|
|
164
188
|
}
|
|
165
189
|
const secrets = secretVar && env[secretVar] ? [env[secretVar]] : [];
|
|
166
190
|
if (secrets.some((s) => s.length >= 8 && prose.text.includes(s))) return refuse(['prose: contains an API key value — refused']);
|
|
191
|
+
// Red messages can echo what a provider's error body echoed (a key): scrubbed like every file, before anything prints them.
|
|
192
|
+
const cleanReds = (reds) => (reds ?? []).map((r) => scrub(String(r), secrets));
|
|
167
193
|
// Claim the dir BEFORE the paid round (exclusive mkdir: a race or an existing path refuses at $0).
|
|
168
194
|
const exists = () => refuse([`draft: "${dir}" already exists — never overwritten, use a new dir`]);
|
|
169
195
|
if (existsSync(dir)) return exists();
|
|
@@ -175,11 +201,11 @@ export async function draftToDir({
|
|
|
175
201
|
}
|
|
176
202
|
|
|
177
203
|
const result = await draft({
|
|
178
|
-
proseText: prose.text, slot, model, budgetUsd, provider, rates, modelId,
|
|
204
|
+
proseText: prose.text, slot, model, budgetUsd, provider, rates, modelId, env,
|
|
179
205
|
});
|
|
180
206
|
if (result.stop === 'pre-flight') {
|
|
181
207
|
try { rmdirSync(dir); } catch { /* the claimed dir is still empty; leave it rather than mask the refusal */ }
|
|
182
|
-
return refuse(result.reds);
|
|
208
|
+
return refuse(cleanReds(result.reds));
|
|
183
209
|
}
|
|
184
210
|
|
|
185
211
|
// After a paid round: never a silent throw. The cost is returned so the caller prints it; the dir is claimed and stays.
|
|
@@ -203,7 +229,7 @@ export async function draftToDir({
|
|
|
203
229
|
const declarationText = scrub(dj(result.declaration), secrets);
|
|
204
230
|
const inputFactsText = scrub(dj(result.declaration.inputFacts), secrets);
|
|
205
231
|
const readoutText = scrub(buildReadout({
|
|
206
|
-
declaration: result.declaration, arbiter: parsed.arbiter, lines: parsed.lines, name, modelId: result.modelId, costUsd: result.costUsd, rounds: result.rounds, spendComplete: result.spendComplete,
|
|
232
|
+
declaration: result.declaration, arbiter: parsed.arbiter, lines: parsed.lines, name, modelId: result.modelId, costUsd: result.costUsd, rounds: result.rounds, spendComplete: result.spendComplete, root,
|
|
207
233
|
}), secrets);
|
|
208
234
|
files['declaration.json'] = declarationText;
|
|
209
235
|
files['input-facts.json'] = inputFactsText;
|
|
@@ -222,6 +248,8 @@ export async function draftToDir({
|
|
|
222
248
|
try {
|
|
223
249
|
appendSpendRow(path.join(dir, 'spend.jsonl'), {
|
|
224
250
|
kind: 'draft',
|
|
251
|
+
provider: slot,
|
|
252
|
+
price: result.price ?? null,
|
|
225
253
|
model: result.modelId ?? modelId ?? null,
|
|
226
254
|
modelReturned: result.modelReturned,
|
|
227
255
|
tokens: result.tokens ?? null,
|
|
@@ -244,7 +272,7 @@ export async function draftToDir({
|
|
|
244
272
|
return paidFail(`write failed after the paid round (${e.code ?? e.message}); the draft dir is incomplete and never signable`);
|
|
245
273
|
}
|
|
246
274
|
return {
|
|
247
|
-
ok: result.ok, wrote: true, dir, hash, reds: result.reds, costUsd: result.costUsd, spendComplete: result.spendComplete, stop: result.stop, rounds: result.rounds, calls: result.calls, leaks: 0,
|
|
275
|
+
ok: result.ok, wrote: true, dir, hash, reds: cleanReds(result.reds), costUsd: result.costUsd, spendComplete: result.spendComplete, stop: result.stop, rounds: result.rounds, calls: result.calls, leaks: 0,
|
|
248
276
|
};
|
|
249
277
|
}
|
|
250
278
|
|
package/src/config.js
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
// borrowed-from: bareloop src/config.js@0e55685 (and the secret-shape inventory of src/validate.js@07215d6)
|
|
2
|
+
// M4d scope items 2-4 — the ONE reader/writer of `~/.config/fwdloop/config.json`.
|
|
3
|
+
//
|
|
4
|
+
// Shape (unknown top-level fields are kept, never dropped):
|
|
5
|
+
// { "monthlyLimitUsd": <number > 0>, // absent = no limit (piece 3 reads it)
|
|
6
|
+
// "prices": { "<slot>": { "inPerM": n, "cachedInPerM": n, "outPerM": n } }, // USD per 1M tokens, each optional
|
|
7
|
+
// "providers": { "<slot>": { "model": "<id>", "shape": "<shape id>", "baseUrl": "" | "http(s)://…" } } } // each optional (M4d amendment 1)
|
|
8
|
+
// A price is a finite number above 0; 0, a negative, NaN, Infinity or text is a ConfigError
|
|
9
|
+
// naming the slot and field — on write AND on read, so a hand-edited 0 can never price a call at $0.
|
|
10
|
+
// Key VALUES never live here (keys file / shell only): a secret-shaped string is refused on write.
|
|
11
|
+
//
|
|
12
|
+
// A missing file = `{}` (nothing set). An unreadable or unparseable file THROWS `ConfigError` —
|
|
13
|
+
// never `{}`: a broken config must not silently mean "no limit" or "the table's price".
|
|
14
|
+
// Written atomically (tmp + rename), mode 0600.
|
|
15
|
+
import {
|
|
16
|
+
mkdirSync, readFileSync, renameSync, writeFileSync, chmodSync,
|
|
17
|
+
} from 'node:fs';
|
|
18
|
+
import { join, dirname } from 'node:path';
|
|
19
|
+
import { homedir } from 'node:os';
|
|
20
|
+
import { SHAPE_IDS } from './providershapes.js';
|
|
21
|
+
|
|
22
|
+
/** A plain-words config failure (bad value, secret-shaped string, unreadable file). */
|
|
23
|
+
export class ConfigError extends Error {}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* `~/.config/fwdloop`, or an injected override — the ONE definition of fwdloop's config home
|
|
27
|
+
* (the keys file lives beside config.json; `src/keysfile.js` calls this, never its own copy).
|
|
28
|
+
* @param {string} [home] test seam; production never passes it
|
|
29
|
+
* @returns {string}
|
|
30
|
+
*/
|
|
31
|
+
export function configHome(home) {
|
|
32
|
+
return home ?? join(homedir(), '.config', 'fwdloop');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* @param {string} [home]
|
|
37
|
+
* @returns {string} `<home>/config.json`
|
|
38
|
+
*/
|
|
39
|
+
export function configPath(home) {
|
|
40
|
+
return join(configHome(home), 'config.json');
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The home a model-call price lookup reads, resolved at the door. Under a test process
|
|
45
|
+
* (`NODE_ENV=test` or `node --test`) only an explicit `FWDLOOP_CONFIG_HOME` is read; with none, NO
|
|
46
|
+
* config is read at all — a test never touches the real `~/.config/fwdloop`. Outside tests: the real home.
|
|
47
|
+
* @returns {{ skip: boolean, home: string|undefined }}
|
|
48
|
+
*/
|
|
49
|
+
export function configDoorHome() {
|
|
50
|
+
const underTest = process.env.NODE_ENV === 'test' || process.env.NODE_TEST_CONTEXT !== undefined;
|
|
51
|
+
if (!underTest) return { skip: false, home: undefined };
|
|
52
|
+
const home = process.env.FWDLOOP_CONFIG_HOME || undefined;
|
|
53
|
+
return { skip: home === undefined, home };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export const PRICE_FIELDS = Object.freeze(['inPerM', 'cachedInPerM', 'outPerM']);
|
|
57
|
+
const SLOT_RE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
58
|
+
|
|
59
|
+
// The secret-shape inventory (bareloop src/validate.js SECRET_PATTERNS): known token shapes only,
|
|
60
|
+
// left-bounded so hyphenated words never match.
|
|
61
|
+
const SECRET_PATTERNS = [
|
|
62
|
+
/(?<![A-Za-z0-9_-])sk-[A-Za-z0-9_-]{16,}/,
|
|
63
|
+
/(?<![A-Za-z0-9_-])ghp_[A-Za-z0-9]{20,}/,
|
|
64
|
+
/(?<![A-Za-z0-9_-])github_pat_[A-Za-z0-9_]{20,}/,
|
|
65
|
+
/(?<![A-Za-z0-9_-])AKIA[0-9A-Z]{16}/,
|
|
66
|
+
/(?<![A-Za-z0-9_-])xox[bap]-[A-Za-z0-9-]{10,}/,
|
|
67
|
+
/(?<![A-Za-z0-9_-])AIza[0-9A-Za-z_-]{35}/,
|
|
68
|
+
];
|
|
69
|
+
const isSecretShaped = (str) => SECRET_PATTERNS.some((re) => re.test(str));
|
|
70
|
+
|
|
71
|
+
/** Paths (never values) of every string or key in a tree that carries a secret shape. @param {any} node @param {string} at @param {string[]} out */
|
|
72
|
+
function secretPaths(node, at, out) {
|
|
73
|
+
if (typeof node === 'string') {
|
|
74
|
+
if (isSecretShaped(node)) out.push(at || '(root)');
|
|
75
|
+
} else if (Array.isArray(node)) {
|
|
76
|
+
node.forEach((v, i) => secretPaths(v, `${at}.${i}`, out));
|
|
77
|
+
} else if (node !== null && typeof node === 'object') {
|
|
78
|
+
for (const [k, v] of Object.entries(node)) {
|
|
79
|
+
const p = at ? `${at}.${k}` : k;
|
|
80
|
+
if (isSecretShaped(k)) out.push(p);
|
|
81
|
+
secretPaths(v, p, out);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export const PROVIDER_FIELDS = Object.freeze(['model', 'shape', 'baseUrl']);
|
|
87
|
+
|
|
88
|
+
/** One provider field's value problem in plain words, or null when fine. Shared by validateDoc and the route. */
|
|
89
|
+
export function providerFieldProblem(field, v) {
|
|
90
|
+
if (field === 'model') {
|
|
91
|
+
if (typeof v !== 'string' || v.length === 0 || v.length > 200 || /\s/.test(v)) return 'must be a model id: 1 to 200 characters, no spaces';
|
|
92
|
+
} else if (field === 'shape') {
|
|
93
|
+
if (!SHAPE_IDS.includes(v)) return `must be one of ${SHAPE_IDS.join(', ')}`;
|
|
94
|
+
} else if (field === 'baseUrl') {
|
|
95
|
+
if (typeof v !== 'string' || !(v === '' || /^https?:\/\/\S+$/.test(v))) return 'must be empty (the default) or an http(s) address';
|
|
96
|
+
} else return 'is not a provider field';
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** A Base URL as stored: trailing slashes dropped. */
|
|
101
|
+
export const cleanBaseUrl = (v) => v.replace(/\/+$/, '');
|
|
102
|
+
|
|
103
|
+
const isPrice = (v) => typeof v === 'number' && Number.isFinite(v) && v > 0;
|
|
104
|
+
|
|
105
|
+
/** @param {any} providers */
|
|
106
|
+
function validateProviders(providers) {
|
|
107
|
+
if (providers === undefined) return;
|
|
108
|
+
if (providers === null || typeof providers !== 'object' || Array.isArray(providers)) {
|
|
109
|
+
throw new ConfigError('providers must be an object of provider slots');
|
|
110
|
+
}
|
|
111
|
+
for (const [slot, row] of Object.entries(providers)) {
|
|
112
|
+
if (!SLOT_RE.test(slot)) throw new ConfigError(`providers: "${slot}" is not a provider slot name`);
|
|
113
|
+
if (row === null || typeof row !== 'object' || Array.isArray(row)) throw new ConfigError(`providers.${slot} must be an object`);
|
|
114
|
+
for (const [field, v] of Object.entries(row)) {
|
|
115
|
+
if (!PROVIDER_FIELDS.includes(field)) throw new ConfigError(`providers.${slot}.${field} is not a provider field (${PROVIDER_FIELDS.join(', ')})`);
|
|
116
|
+
const problem = providerFieldProblem(field, v);
|
|
117
|
+
if (problem) throw new ConfigError(`providers.${slot}.${field} ${problem}`);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Validate a whole document's known fields; throws ConfigError naming the field.
|
|
124
|
+
* @param {Record<string, any>} doc
|
|
125
|
+
*/
|
|
126
|
+
function validateDoc(doc) {
|
|
127
|
+
if (doc.monthlyLimitUsd !== undefined && !isPrice(doc.monthlyLimitUsd)) {
|
|
128
|
+
throw new ConfigError('monthlyLimitUsd must be a number above 0 (remove the limit to have none)');
|
|
129
|
+
}
|
|
130
|
+
validateProviders(doc.providers);
|
|
131
|
+
if (doc.prices === undefined) return;
|
|
132
|
+
if (doc.prices === null || typeof doc.prices !== 'object' || Array.isArray(doc.prices)) {
|
|
133
|
+
throw new ConfigError('prices must be an object of provider slots');
|
|
134
|
+
}
|
|
135
|
+
for (const [slot, row] of Object.entries(doc.prices)) {
|
|
136
|
+
if (!SLOT_RE.test(slot)) throw new ConfigError(`prices: "${slot}" is not a provider slot name`);
|
|
137
|
+
if (row === null || typeof row !== 'object' || Array.isArray(row)) throw new ConfigError(`prices.${slot} must be an object`);
|
|
138
|
+
for (const [field, v] of Object.entries(row)) {
|
|
139
|
+
if (!PRICE_FIELDS.includes(field)) throw new ConfigError(`prices.${slot}.${field} is not a price field (${PRICE_FIELDS.join(', ')})`);
|
|
140
|
+
if (!isPrice(v)) throw new ConfigError(`prices.${slot}.${field} must be a number above 0 (USD per 1M tokens)`);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* The parsed, validated document. `{}` when the file is missing. THROWS ConfigError when the file is
|
|
147
|
+
* there but unreadable, not a JSON object, or holds an invalid known field — never `{}` for those.
|
|
148
|
+
* @param {{ home?: string }} [opts]
|
|
149
|
+
* @returns {Record<string, any>}
|
|
150
|
+
*/
|
|
151
|
+
export function readConfig(opts = {}) {
|
|
152
|
+
const file = configPath(opts.home);
|
|
153
|
+
let text;
|
|
154
|
+
try {
|
|
155
|
+
text = readFileSync(file, 'utf8');
|
|
156
|
+
} catch (/** @type {any} */ e) {
|
|
157
|
+
if (e?.code === 'ENOENT') return {};
|
|
158
|
+
throw new ConfigError(`${file} could not be read (${e?.code ?? 'error'}) — fix or remove it`);
|
|
159
|
+
}
|
|
160
|
+
let parsed;
|
|
161
|
+
try {
|
|
162
|
+
parsed = JSON.parse(text);
|
|
163
|
+
} catch {
|
|
164
|
+
throw new ConfigError(`${file} is not readable JSON — fix or remove it`);
|
|
165
|
+
}
|
|
166
|
+
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
167
|
+
throw new ConfigError(`${file} must hold a JSON object — fix or remove it`);
|
|
168
|
+
}
|
|
169
|
+
try {
|
|
170
|
+
validateDoc(parsed);
|
|
171
|
+
} catch (/** @type {any} */ e) {
|
|
172
|
+
throw new ConfigError(`${file}: ${e.message}`);
|
|
173
|
+
}
|
|
174
|
+
return parsed;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Apply a patch and write. `null` deletes a field. Top-level fields shallow-merge; `prices` merges
|
|
179
|
+
* per slot, then per field (`prices.<slot> = null` clears the slot, `prices.<slot>.<field> = null`
|
|
180
|
+
* clears the field). Everything is validated before anything is written; a refusal leaves the file
|
|
181
|
+
* untouched.
|
|
182
|
+
* @param {Record<string, any>} patch
|
|
183
|
+
* @param {{ home?: string }} [opts]
|
|
184
|
+
* @returns {Record<string, any>} the document as written
|
|
185
|
+
*/
|
|
186
|
+
export function updateConfig(patch, opts = {}) {
|
|
187
|
+
const cur = readConfig(opts);
|
|
188
|
+
/** @type {Record<string, any>} */
|
|
189
|
+
const next = { ...cur };
|
|
190
|
+
for (const [k, v] of Object.entries(patch)) {
|
|
191
|
+
if (k === 'prices' || k === 'providers') continue;
|
|
192
|
+
if (v === null) delete next[k];
|
|
193
|
+
else next[k] = v;
|
|
194
|
+
}
|
|
195
|
+
if (patch.prices !== undefined) {
|
|
196
|
+
const p = patch.prices;
|
|
197
|
+
if (p === null) {
|
|
198
|
+
delete next.prices;
|
|
199
|
+
} else {
|
|
200
|
+
if (typeof p !== 'object' || Array.isArray(p)) throw new ConfigError('prices must be an object of provider slots');
|
|
201
|
+
/** @type {Record<string, any>} */
|
|
202
|
+
const prices = { ...(next.prices ?? {}) };
|
|
203
|
+
for (const [slot, row] of Object.entries(p)) {
|
|
204
|
+
if (row === null) { delete prices[slot]; continue; }
|
|
205
|
+
if (typeof row !== 'object' || Array.isArray(row)) throw new ConfigError(`prices.${slot} must be an object`);
|
|
206
|
+
const merged = { ...(prices[slot] ?? {}) };
|
|
207
|
+
for (const [field, v] of Object.entries(row)) {
|
|
208
|
+
if (v === null) delete merged[field];
|
|
209
|
+
else merged[field] = v;
|
|
210
|
+
}
|
|
211
|
+
if (Object.keys(merged).length === 0) delete prices[slot];
|
|
212
|
+
else prices[slot] = merged;
|
|
213
|
+
}
|
|
214
|
+
if (Object.keys(prices).length === 0) delete next.prices;
|
|
215
|
+
else next.prices = prices;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
if (patch.providers !== undefined) {
|
|
219
|
+
const p = patch.providers;
|
|
220
|
+
if (p === null) {
|
|
221
|
+
delete next.providers;
|
|
222
|
+
} else {
|
|
223
|
+
if (typeof p !== 'object' || Array.isArray(p)) throw new ConfigError('providers must be an object of provider slots');
|
|
224
|
+
/** @type {Record<string, any>} */
|
|
225
|
+
const providers = { ...(next.providers ?? {}) };
|
|
226
|
+
for (const [slot, row] of Object.entries(p)) {
|
|
227
|
+
if (row === null) { delete providers[slot]; continue; }
|
|
228
|
+
if (typeof row !== 'object' || Array.isArray(row)) throw new ConfigError(`providers.${slot} must be an object`);
|
|
229
|
+
const merged = { ...(providers[slot] ?? {}) };
|
|
230
|
+
for (const [field, v] of Object.entries(row)) {
|
|
231
|
+
if (v === null) delete merged[field];
|
|
232
|
+
else merged[field] = field === 'baseUrl' && typeof v === 'string' ? cleanBaseUrl(v) : v;
|
|
233
|
+
}
|
|
234
|
+
if (Object.keys(merged).length === 0) delete providers[slot];
|
|
235
|
+
else providers[slot] = merged;
|
|
236
|
+
}
|
|
237
|
+
if (Object.keys(providers).length === 0) delete next.providers;
|
|
238
|
+
else next.providers = providers;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
validateDoc(next);
|
|
242
|
+
/** @type {string[]} */
|
|
243
|
+
const leaks = [];
|
|
244
|
+
secretPaths(next, '', leaks);
|
|
245
|
+
if (leaks.length) {
|
|
246
|
+
throw new ConfigError(`config.json never holds a key value — a secret-shaped string at ${leaks.join(', ')} was refused (keys live in the keys file)`);
|
|
247
|
+
}
|
|
248
|
+
const file = configPath(opts.home);
|
|
249
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
|
250
|
+
const tmp = `${file}.tmp-${process.pid}`;
|
|
251
|
+
writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
|
|
252
|
+
chmodSync(tmp, 0o600);
|
|
253
|
+
renameSync(tmp, file);
|
|
254
|
+
return next;
|
|
255
|
+
}
|
package/src/drafter.js
CHANGED
|
@@ -21,8 +21,9 @@ import { validateDeclaration, SHAPE_KEYS } from './declaration.js';
|
|
|
21
21
|
import { loadCatalogue } from './catalogue.js';
|
|
22
22
|
import { WIRED_VERBS, wiredMenu } from './primitives.js';
|
|
23
23
|
import { readInputFacts } from './input-facts.js';
|
|
24
|
-
import { makeProvider, sumMeterings, ceilingCostUsd } from './provider.js';
|
|
24
|
+
import { makeProvider, sumMeterings, ceilingCostUsd, priceRecord } from './provider.js';
|
|
25
25
|
import { LIVE_PROVIDER_OPTIONS } from './model-step.js';
|
|
26
|
+
import { ConfigError } from './config.js';
|
|
26
27
|
|
|
27
28
|
export const MAX_STRUCTURE_RETRIES = 2;
|
|
28
29
|
export const MAX_REVISIONS = 2;
|
|
@@ -177,10 +178,10 @@ export const DRAFT_PROVIDER_OPTIONS = Object.freeze({ ...LIVE_PROVIDER_OPTIONS,
|
|
|
177
178
|
* `makeProviderFn` is a test seam: the live-provider factory (default `makeProvider`).
|
|
178
179
|
*
|
|
179
180
|
* @returns {Promise<{ok:boolean, declaration:object|null, reds:string[], rounds:number, calls:number, spendComplete:boolean,
|
|
180
|
-
* costUsd:number|null, modelReturned:string|null, modelId?:string, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[]}>}
|
|
181
|
+
* costUsd:number|null, modelReturned:string|null, modelId?:string, price?:object|null, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[]}>}
|
|
181
182
|
*/
|
|
182
183
|
export async function draft({
|
|
183
|
-
proseText, slot = 'deepseek', model, provider: injected, rates: injectedRates, modelId: injectedModelId,
|
|
184
|
+
proseText, slot = 'deepseek', model, provider: injected, rates: injectedRates, modelId: injectedModelId, env,
|
|
184
185
|
budgetUsd = 0.10, skills = DRAFT_SKILLS, makeProviderFn = makeProvider,
|
|
185
186
|
}) {
|
|
186
187
|
const fail = (reds, extra = {}) => ({
|
|
@@ -198,11 +199,14 @@ export async function draft({
|
|
|
198
199
|
if (!facts.ok) return fail(facts.reds);
|
|
199
200
|
|
|
200
201
|
let { provider, rates, modelId } = { provider: injected, rates: injectedRates, modelId: injectedModelId };
|
|
202
|
+
let prices = null; // the one price lookup's result (live provider only); the cap check below uses the SAME price
|
|
201
203
|
if (provider == null) {
|
|
202
204
|
try {
|
|
203
|
-
({
|
|
205
|
+
({
|
|
206
|
+
provider, rates, modelId, prices = null,
|
|
207
|
+
} = makeProviderFn(slot, { model, env, ...DRAFT_PROVIDER_OPTIONS }));
|
|
204
208
|
} catch (err) {
|
|
205
|
-
return fail([
|
|
209
|
+
return fail([`${err instanceof ConfigError ? 'config' : 'key'}: ${err.message}`]);
|
|
206
210
|
}
|
|
207
211
|
}
|
|
208
212
|
|
|
@@ -212,7 +216,7 @@ export async function draft({
|
|
|
212
216
|
const cat = loadCatalogue();
|
|
213
217
|
if (!cat.ok) return fail([`catalogue: ${cat.reds.join('; ')}`]);
|
|
214
218
|
const validationCatalogue = cat.primitives;
|
|
215
|
-
const roundCeiling = ceilingCostUsd(modelId);
|
|
219
|
+
const roundCeiling = ceilingCostUsd(modelId, undefined, prices ? { prices } : {});
|
|
216
220
|
// One round at its ceiling must fit the budget, or refuse at $0 before any provider call.
|
|
217
221
|
if (roundCeiling > budgetUsd) {
|
|
218
222
|
return fail([`budget: $${budgetUsd} is below one round's worst-case cost — the minimum budget is $${roundCeiling.toFixed(4)}`]);
|
|
@@ -301,7 +305,7 @@ export async function draft({
|
|
|
301
305
|
log.push(entry);
|
|
302
306
|
const m = sumMeterings(meterings);
|
|
303
307
|
return {
|
|
304
|
-
ok: true, declaration, reds: [], rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, tokens: m.tokens, structureRetries, revisions, stop: null, log,
|
|
308
|
+
ok: true, declaration, reds: [], rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries, revisions, stop: null, log,
|
|
305
309
|
};
|
|
306
310
|
}
|
|
307
311
|
lastReds = [...verdict.reds];
|
|
@@ -319,6 +323,6 @@ export async function draft({
|
|
|
319
323
|
// Runner convention: `costUsd` is the priced sum (null when ANY round is unpriced, so the CLI prints UNKNOWN,
|
|
320
324
|
// never a bare number), and `spendComplete:false` marks a call that failed unmetered or a round left unpriced.
|
|
321
325
|
return {
|
|
322
|
-
ok: false, declaration: lastDecl, reds: lastReds, rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, tokens: m.tokens, structureRetries, revisions, stop, log,
|
|
326
|
+
ok: false, declaration: lastDecl, reds: lastReds, rounds: m.rounds, calls, spendComplete: unmetered === 0 && m.costUsd !== null, costUsd: m.costUsd, modelReturned: m.model, modelId, price: priceRecord(prices, rates), tokens: m.tokens, structureRetries, revisions, stop, log,
|
|
323
327
|
};
|
|
324
328
|
}
|
package/src/keysfile.js
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
// borrowed-from: bareloop src/keysfile.js@a42ca5f
|
|
2
|
+
// M4d scope item 1 — the keys file loader (`~/.config/fwdloop/.env`).
|
|
3
|
+
//
|
|
4
|
+
// Key VALUES live only in this file (mode 0600, outside any repo) and in the shell
|
|
5
|
+
// environment — never in config.json, the spine, runs.jsonl, a log, a page or an audit
|
|
6
|
+
// row. This is the ONE reader of that file. Plain `NAME=value` lines (an optional
|
|
7
|
+
// `export ` prefix, `#` full-line comments, one pair of matching quotes around the
|
|
8
|
+
// value); no dependency.
|
|
9
|
+
//
|
|
10
|
+
// Precedence: the SHELL wins. An exported `FOO=…` beats the file; the file only fills
|
|
11
|
+
// names the shell leaves unset (or empty). The merged env is a NEW object —
|
|
12
|
+
// `process.env` is never mutated.
|
|
13
|
+
//
|
|
14
|
+
// Adjusted from bareloop (ruling 1A, hamr 2026-10-05): a file with any group/other bit is
|
|
15
|
+
// REFUSED, not warned about. A refusal carries no env at all: nothing that needs a key runs.
|
|
16
|
+
//
|
|
17
|
+
// Values leave this module in exactly one place: the `env` of an ok `loadKeysEnv`.
|
|
18
|
+
// Everything else it returns (`names`, `path`, `exists`, `refusal`) is value-free by
|
|
19
|
+
// construction, and a parse problem never quotes the offending line.
|
|
20
|
+
import {
|
|
21
|
+
openSync, fstatSync, readFileSync, closeSync, writeFileSync, mkdirSync,
|
|
22
|
+
} from 'node:fs';
|
|
23
|
+
import { join } from 'node:path';
|
|
24
|
+
import { PROVIDER_SLOTS } from './provider.js';
|
|
25
|
+
import { configHome, configDoorHome } from './config.js';
|
|
26
|
+
|
|
27
|
+
const NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
28
|
+
|
|
29
|
+
/** The key names fwdloop knows (one per provider slot). */
|
|
30
|
+
export const KEY_NAMES = Object.freeze(Object.values(PROVIDER_SLOTS).map((p) => p.envVar));
|
|
31
|
+
|
|
32
|
+
const DEFAULT_SHOWN = '~/.config/fwdloop/.env';
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* `~/.config/fwdloop`, or an injected override. The CLI/panel door honors the test-only
|
|
36
|
+
* `FWDLOOP_CONFIG_HOME` through `keysForDoor` (two gates, like the other test seams).
|
|
37
|
+
* @param {string} [home] test seam; production never passes it
|
|
38
|
+
* @returns {string}
|
|
39
|
+
*/
|
|
40
|
+
export function keysHome(home) {
|
|
41
|
+
return configHome(home); // one definition of the config home (src/config.js)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* @param {string} [home]
|
|
46
|
+
* @returns {string} `<home>/.env`
|
|
47
|
+
*/
|
|
48
|
+
export function keysFilePath(home) {
|
|
49
|
+
return join(keysHome(home), '.env');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The path as a sentence shows it: `~/...` for the default home, the real path for an injected one. */
|
|
53
|
+
const shownPath = (home) => (home === undefined ? DEFAULT_SHOWN : keysFilePath(home));
|
|
54
|
+
|
|
55
|
+
/** The one wording of the 1A refusal (ruling 1A, hamr 2026-10-05). @param {string} [home] */
|
|
56
|
+
export function chmodSentence(home) {
|
|
57
|
+
return `Your keys file can be read by other users. Run: chmod 600 ${shownPath(home)}`;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Parse the file's text. Lines that are not `NAME=value` are skipped silently
|
|
62
|
+
* (never echoed — a malformed line may hold a secret).
|
|
63
|
+
* @param {string} text
|
|
64
|
+
* @returns {Record<string,string>}
|
|
65
|
+
*/
|
|
66
|
+
export function parseKeysText(text) {
|
|
67
|
+
/** @type {Record<string,string>} */
|
|
68
|
+
const out = {};
|
|
69
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
70
|
+
const line = raw.trim();
|
|
71
|
+
if (line === '' || line.startsWith('#')) continue;
|
|
72
|
+
const body = line.startsWith('export ') ? line.slice(7).trimStart() : line;
|
|
73
|
+
const eq = body.indexOf('=');
|
|
74
|
+
if (eq <= 0) continue;
|
|
75
|
+
const name = body.slice(0, eq).trim();
|
|
76
|
+
if (!NAME_RE.test(name)) continue;
|
|
77
|
+
let value = body.slice(eq + 1).trim();
|
|
78
|
+
if (value.length >= 2 && (value[0] === '"' || value[0] === "'") && value.endsWith(value[0])) {
|
|
79
|
+
value = value.slice(1, -1);
|
|
80
|
+
}
|
|
81
|
+
out[name] = value;
|
|
82
|
+
}
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Create the file when — and only when — it does not exist: mode 0600 (`wx`), dir 0700,
|
|
88
|
+
* the known key names as commented lines and nothing else.
|
|
89
|
+
* @param {string} [home]
|
|
90
|
+
* @returns {boolean} true if it was created
|
|
91
|
+
*/
|
|
92
|
+
function createKeysFile(home) {
|
|
93
|
+
mkdirSync(keysHome(home), { recursive: true, mode: 0o700 });
|
|
94
|
+
const body = '# fwdloop keys — type NAME=value by hand; this file is never shown or written by fwdloop.\n'
|
|
95
|
+
+ `${KEY_NAMES.map((n) => `# ${n}=`).join('\n')}\n`;
|
|
96
|
+
try {
|
|
97
|
+
writeFileSync(keysFilePath(home), body, { mode: 0o600, flag: 'wx' });
|
|
98
|
+
} catch (/** @type {any} */ e) {
|
|
99
|
+
if (e?.code === 'EEXIST') return false; // lost a race: the file is there, untouched
|
|
100
|
+
throw e;
|
|
101
|
+
}
|
|
102
|
+
return true;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* @typedef {object} KeysLoad
|
|
107
|
+
* @property {boolean} ok false = refused: nothing that needs a key may run
|
|
108
|
+
* @property {string} path the keys file's path as shown to people
|
|
109
|
+
* @property {boolean} exists the file is there (true after a create)
|
|
110
|
+
* @property {string[]} names the NAMES the file defines with a value (sorted; never values)
|
|
111
|
+
* @property {string[]} shellOnly the known key names that only the shell sets (file empty/absent)
|
|
112
|
+
* @property {string|null} refusal a plain sentence when `ok` is false, else null
|
|
113
|
+
* @property {Record<string,string|undefined>} env shell env with the file filling the names the
|
|
114
|
+
* shell does not set; on a refusal just a copy of the shell env (no file value). THE ONLY
|
|
115
|
+
* place file values leave this module.
|
|
116
|
+
*/
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Load the keys file over an env. A missing file is created (0600) and is not a refusal.
|
|
120
|
+
* @param {{ env?: Record<string,string|undefined>, home?: string }} [opts]
|
|
121
|
+
* @returns {KeysLoad}
|
|
122
|
+
*/
|
|
123
|
+
export function loadKeysEnv(opts = {}) {
|
|
124
|
+
const base = opts.env ?? process.env;
|
|
125
|
+
const file = keysFilePath(opts.home);
|
|
126
|
+
const path = shownPath(opts.home);
|
|
127
|
+
const knownShell = (parsed) => KEY_NAMES.filter((n) => base[n] && !parsed[n]);
|
|
128
|
+
/** @param {string} refusal @param {boolean} exists @returns {KeysLoad} */
|
|
129
|
+
const refused = (refusal, exists) => ({
|
|
130
|
+
ok: false, path, exists, names: [], shellOnly: [], refusal, env: { ...base },
|
|
131
|
+
});
|
|
132
|
+
let fd;
|
|
133
|
+
let created = false;
|
|
134
|
+
try {
|
|
135
|
+
try {
|
|
136
|
+
fd = openSync(file, 'r');
|
|
137
|
+
} catch (/** @type {any} */ e) {
|
|
138
|
+
if (e?.code !== 'ENOENT') throw e;
|
|
139
|
+
created = createKeysFile(opts.home);
|
|
140
|
+
fd = openSync(file, 'r');
|
|
141
|
+
}
|
|
142
|
+
const st = fstatSync(fd);
|
|
143
|
+
if (!st.isFile()) return refused(`Your keys file ${path} is not a regular file.`, true);
|
|
144
|
+
if ((st.mode & 0o077) !== 0) return refused(chmodSentence(opts.home), true);
|
|
145
|
+
const parsed = parseKeysText(readFileSync(fd, 'utf8'));
|
|
146
|
+
/** @type {Record<string,string|undefined>} */
|
|
147
|
+
const env = { ...base };
|
|
148
|
+
for (const [name, value] of Object.entries(parsed)) {
|
|
149
|
+
if (!env[name]) env[name] = value;
|
|
150
|
+
}
|
|
151
|
+
return {
|
|
152
|
+
ok: true, path, exists: true, names: Object.entries(parsed).filter(([, v]) => v !== '').map(([n]) => n).sort(), shellOnly: knownShell(parsed), refusal: null, env,
|
|
153
|
+
};
|
|
154
|
+
} catch (/** @type {any} */ e) {
|
|
155
|
+
return refused(`Your keys file ${path} could not be read (${e?.code ?? 'error'}).`, created || e?.code !== 'ENOENT');
|
|
156
|
+
} finally {
|
|
157
|
+
if (fd !== undefined) closeSync(fd);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* The door helper the CLI and the panel call. Loads the file only when the caller is on the
|
|
163
|
+
* REAL environment, or names a home explicitly (a test), or a test process (`configDoorHome`) with
|
|
164
|
+
* `FWDLOOP_CONFIG_HOME` set — so a test that injects `env` alone, or runs under NODE_ENV=test
|
|
165
|
+
* without a home, never reads (or creates) the real `~/.config/fwdloop/.env`.
|
|
166
|
+
* @param {{ env?: Record<string,string|undefined>, keysHome?: string }} [deps]
|
|
167
|
+
* @returns {KeysLoad & { skipped: boolean }}
|
|
168
|
+
*/
|
|
169
|
+
export function keysForDoor(deps = {}) {
|
|
170
|
+
const shell = process.env;
|
|
171
|
+
const door = configDoorHome(); // the one "under test" rule (NODE_ENV=test or node --test) and its home
|
|
172
|
+
const home = deps.keysHome ?? door.home;
|
|
173
|
+
const testNoHome = door.skip && home === undefined;
|
|
174
|
+
if ((deps.env !== undefined && home === undefined) || testNoHome) {
|
|
175
|
+
return {
|
|
176
|
+
ok: true, skipped: true, path: shownPath(undefined), exists: false, names: [], shellOnly: [], refusal: null, env: { ...(deps.env ?? shell) },
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
return { ...loadKeysEnv({ env: deps.env, home }), skipped: false };
|
|
180
|
+
}
|
package/src/liveness.js
CHANGED
|
@@ -118,22 +118,22 @@ export const LOCK_NO_HOLDER = 'with no recorded holder';
|
|
|
118
118
|
* unknown - liveness cannot be told (no /proc): never treated as dead
|
|
119
119
|
* empty - a lock with no readable holder (pre-amendment resumer, torn write)
|
|
120
120
|
* @param {string} runDir
|
|
121
|
-
* @returns {{state: 'none'|'live'|'dead'|'unknown'|'empty', pid: number|null, path: string}}
|
|
121
|
+
* @returns {{state: 'none'|'live'|'dead'|'unknown'|'empty', pid: number|null, procStart: string|null, path: string}}
|
|
122
122
|
*/
|
|
123
123
|
export function readResumeLock(runDir) {
|
|
124
124
|
const path = join(runDir, 'resume.lock');
|
|
125
125
|
let st;
|
|
126
|
-
try { st = lstatSync(path); } catch { return { state: 'none', pid: null, path }; }
|
|
127
|
-
if (!st.isFile()) return { state: 'empty', pid: null, path };
|
|
126
|
+
try { st = lstatSync(path); } catch { return { state: 'none', pid: null, procStart: null, path }; }
|
|
127
|
+
if (!st.isFile()) return { state: 'empty', pid: null, procStart: null, path };
|
|
128
128
|
let h;
|
|
129
|
-
try { h = JSON.parse(readFileSync(path, 'utf8')); } catch { return { state: 'empty', pid: null, path }; }
|
|
130
|
-
if (!h || !Number.isInteger(h.pid) || h.pid <= 0) return { state: 'empty', pid: null, path };
|
|
129
|
+
try { h = JSON.parse(readFileSync(path, 'utf8')); } catch { return { state: 'empty', pid: null, procStart: null, path }; }
|
|
130
|
+
if (!h || !Number.isInteger(h.pid) || h.pid <= 0) return { state: 'empty', pid: null, procStart: null, path };
|
|
131
131
|
const procStart = typeof h.procStart === 'string' ? h.procStart : null;
|
|
132
132
|
// This very process holds it (two resumeRun calls in one process): alive by definition,
|
|
133
133
|
// whatever its command line says.
|
|
134
|
-
if (h.pid === process.pid && procStart === procStartOf('self')) return { state: 'live', pid: h.pid, path };
|
|
134
|
+
if (h.pid === process.pid && procStart === procStartOf('self')) return { state: 'live', pid: h.pid, procStart, path };
|
|
135
135
|
const alive = isFwdloopAlive(h.pid, procStart);
|
|
136
|
-
return { state: alive === true ? 'live' : alive === false ? 'dead' : 'unknown', pid: h.pid, path };
|
|
136
|
+
return { state: alive === true ? 'live' : alive === false ? 'dead' : 'unknown', pid: h.pid, procStart, path };
|
|
137
137
|
}
|
|
138
138
|
|
|
139
139
|
/** The run's books, for the 10-minute fallback: state, audit, model log, spend ledger, and the pid file itself. */
|