fwdloop 0.11.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.
@@ -0,0 +1,51 @@
1
+ /**
2
+ * `~/.config/fwdloop`, or an injected override — the ONE definition of fwdloop's config home
3
+ * (the keys file lives beside config.json; `src/keysfile.js` calls this, never its own copy).
4
+ * @param {string} [home] test seam; production never passes it
5
+ * @returns {string}
6
+ */
7
+ export function configHome(home?: string): string;
8
+ /**
9
+ * @param {string} [home]
10
+ * @returns {string} `<home>/config.json`
11
+ */
12
+ export function configPath(home?: string): string;
13
+ /**
14
+ * The home a model-call price lookup reads, resolved at the door. Under a test process
15
+ * (`NODE_ENV=test` or `node --test`) only an explicit `FWDLOOP_CONFIG_HOME` is read; with none, NO
16
+ * config is read at all — a test never touches the real `~/.config/fwdloop`. Outside tests: the real home.
17
+ * @returns {{ skip: boolean, home: string|undefined }}
18
+ */
19
+ export function configDoorHome(): {
20
+ skip: boolean;
21
+ home: string | undefined;
22
+ };
23
+ /** One provider field's value problem in plain words, or null when fine. Shared by validateDoc and the route. */
24
+ export function providerFieldProblem(field: any, v: any): string | null;
25
+ /**
26
+ * The parsed, validated document. `{}` when the file is missing. THROWS ConfigError when the file is
27
+ * there but unreadable, not a JSON object, or holds an invalid known field — never `{}` for those.
28
+ * @param {{ home?: string }} [opts]
29
+ * @returns {Record<string, any>}
30
+ */
31
+ export function readConfig(opts?: {
32
+ home?: string;
33
+ }): Record<string, any>;
34
+ /**
35
+ * Apply a patch and write. `null` deletes a field. Top-level fields shallow-merge; `prices` merges
36
+ * per slot, then per field (`prices.<slot> = null` clears the slot, `prices.<slot>.<field> = null`
37
+ * clears the field). Everything is validated before anything is written; a refusal leaves the file
38
+ * untouched.
39
+ * @param {Record<string, any>} patch
40
+ * @param {{ home?: string }} [opts]
41
+ * @returns {Record<string, any>} the document as written
42
+ */
43
+ export function updateConfig(patch: Record<string, any>, opts?: {
44
+ home?: string;
45
+ }): Record<string, any>;
46
+ /** A plain-words config failure (bad value, secret-shaped string, unreadable file). */
47
+ export class ConfigError extends Error {
48
+ }
49
+ export const PRICE_FIELDS: readonly string[];
50
+ export const PROVIDER_FIELDS: readonly string[];
51
+ export function cleanBaseUrl(v: any): any;
@@ -121,15 +121,16 @@ export function goalForLine(fromLine: any, lines: any): any;
121
121
  * `makeProviderFn` is a test seam: the live-provider factory (default `makeProvider`).
122
122
  *
123
123
  * @returns {Promise<{ok:boolean, declaration:object|null, reds:string[], rounds:number, calls:number, spendComplete:boolean,
124
- * costUsd:number|null, modelReturned:string|null, modelId?:string, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[]}>}
124
+ * costUsd:number|null, modelReturned:string|null, modelId?:string, price?:object|null, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[]}>}
125
125
  */
126
- export function draft({ proseText, slot, model, provider: injected, rates: injectedRates, modelId: injectedModelId, budgetUsd, skills, makeProviderFn, }: {
126
+ export function draft({ proseText, slot, model, provider: injected, rates: injectedRates, modelId: injectedModelId, env, budgetUsd, skills, makeProviderFn, }: {
127
127
  proseText: any;
128
128
  slot?: string | undefined;
129
129
  model: any;
130
130
  provider: any;
131
131
  rates: any;
132
132
  modelId: any;
133
+ env: any;
133
134
  budgetUsd?: number | undefined;
134
135
  skills?: readonly string[] | undefined;
135
136
  makeProviderFn?: typeof makeProvider | undefined;
@@ -143,6 +144,7 @@ export function draft({ proseText, slot, model, provider: injected, rates: injec
143
144
  costUsd: number | null;
144
145
  modelReturned: string | null;
145
146
  modelId?: string;
147
+ price?: object | null;
146
148
  tokens?: object | null;
147
149
  structureRetries: number;
148
150
  revisions: number;
@@ -0,0 +1,90 @@
1
+ /**
2
+ * `~/.config/fwdloop`, or an injected override. The CLI/panel door honors the test-only
3
+ * `FWDLOOP_CONFIG_HOME` through `keysForDoor` (two gates, like the other test seams).
4
+ * @param {string} [home] test seam; production never passes it
5
+ * @returns {string}
6
+ */
7
+ export function keysHome(home?: string): string;
8
+ /**
9
+ * @param {string} [home]
10
+ * @returns {string} `<home>/.env`
11
+ */
12
+ export function keysFilePath(home?: string): string;
13
+ /** The one wording of the 1A refusal (ruling 1A, hamr 2026-10-05). @param {string} [home] */
14
+ export function chmodSentence(home?: string): string;
15
+ /**
16
+ * Parse the file's text. Lines that are not `NAME=value` are skipped silently
17
+ * (never echoed — a malformed line may hold a secret).
18
+ * @param {string} text
19
+ * @returns {Record<string,string>}
20
+ */
21
+ export function parseKeysText(text: string): Record<string, string>;
22
+ /**
23
+ * @typedef {object} KeysLoad
24
+ * @property {boolean} ok false = refused: nothing that needs a key may run
25
+ * @property {string} path the keys file's path as shown to people
26
+ * @property {boolean} exists the file is there (true after a create)
27
+ * @property {string[]} names the NAMES the file defines with a value (sorted; never values)
28
+ * @property {string[]} shellOnly the known key names that only the shell sets (file empty/absent)
29
+ * @property {string|null} refusal a plain sentence when `ok` is false, else null
30
+ * @property {Record<string,string|undefined>} env shell env with the file filling the names the
31
+ * shell does not set; on a refusal just a copy of the shell env (no file value). THE ONLY
32
+ * place file values leave this module.
33
+ */
34
+ /**
35
+ * Load the keys file over an env. A missing file is created (0600) and is not a refusal.
36
+ * @param {{ env?: Record<string,string|undefined>, home?: string }} [opts]
37
+ * @returns {KeysLoad}
38
+ */
39
+ export function loadKeysEnv(opts?: {
40
+ env?: Record<string, string | undefined>;
41
+ home?: string;
42
+ }): KeysLoad;
43
+ /**
44
+ * The door helper the CLI and the panel call. Loads the file only when the caller is on the
45
+ * REAL environment, or names a home explicitly (a test), or a test process (`configDoorHome`) with
46
+ * `FWDLOOP_CONFIG_HOME` set — so a test that injects `env` alone, or runs under NODE_ENV=test
47
+ * without a home, never reads (or creates) the real `~/.config/fwdloop/.env`.
48
+ * @param {{ env?: Record<string,string|undefined>, keysHome?: string }} [deps]
49
+ * @returns {KeysLoad & { skipped: boolean }}
50
+ */
51
+ export function keysForDoor(deps?: {
52
+ env?: Record<string, string | undefined>;
53
+ keysHome?: string;
54
+ }): KeysLoad & {
55
+ skipped: boolean;
56
+ };
57
+ /** The key names fwdloop knows (one per provider slot). */
58
+ export const KEY_NAMES: readonly ("SYNTHETIC_API_KEY" | "DEEPSEEK_API_KEY")[];
59
+ export type KeysLoad = {
60
+ /**
61
+ * false = refused: nothing that needs a key may run
62
+ */
63
+ ok: boolean;
64
+ /**
65
+ * the keys file's path as shown to people
66
+ */
67
+ path: string;
68
+ /**
69
+ * the file is there (true after a create)
70
+ */
71
+ exists: boolean;
72
+ /**
73
+ * the NAMES the file defines with a value (sorted; never values)
74
+ */
75
+ names: string[];
76
+ /**
77
+ * the known key names that only the shell sets (file empty/absent)
78
+ */
79
+ shellOnly: string[];
80
+ /**
81
+ * a plain sentence when `ok` is false, else null
82
+ */
83
+ refusal: string | null;
84
+ /**
85
+ * shell env with the file filling the names the
86
+ * shell does not set; on a refusal just a copy of the shell env (no file value). THE ONLY
87
+ * place file values leave this module.
88
+ */
89
+ env: Record<string, string | undefined>;
90
+ };
@@ -91,9 +91,10 @@ export function buildEmitArtifactSchema(stepClass: any): Readonly<{
91
91
  * @param {any} [opts.provider] - an injected provider (tests only; production always builds live via `slot`).
92
92
  * @param {{in:number,out:number}} [opts.rates]
93
93
  * @param {string} [opts.modelId]
94
+ * @param {Record<string,string|undefined>} [opts.env] - the merged shell+keys-file env the key is read from (default process.env).
94
95
  * @returns {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class?:string}) => Promise<any>}
95
96
  */
96
- export function makeLiveModelStep({ slot, model, spendPath, provider: injectedProvider, rates: injectedRates, modelId: injectedModelId, }: {
97
+ export function makeLiveModelStep({ slot, model, spendPath, provider: injectedProvider, rates: injectedRates, modelId: injectedModelId, env, }: {
97
98
  slot?: string | undefined;
98
99
  model?: string | undefined;
99
100
  spendPath: string;
@@ -103,6 +104,7 @@ export function makeLiveModelStep({ slot, model, spendPath, provider: injectedPr
103
104
  out: number;
104
105
  } | undefined;
105
106
  modelId?: string | undefined;
107
+ env?: Record<string, string | undefined> | undefined;
106
108
  }): (executorContext: object, grantedTools: Record<string, any>, stepMeta?: {
107
109
  class?: string;
108
110
  }) => Promise<any>;
@@ -0,0 +1,109 @@
1
+ /** realpath of the longest existing prefix of `p`, the rest appended (a run dir does not exist yet at claim time). @param {string} p */
2
+ export function realpathLoose(p: string): string;
3
+ /** @param {string} [home] @returns {any[]} every well-formed row in file order (a torn line is skipped) */
4
+ export function readRuns(home?: string): any[];
5
+ /**
6
+ * The Money tab's figures (piece 4 reads this) and the check's month total.
7
+ * @param {{ home?: string, now?: () => number }} [opts]
8
+ */
9
+ export function spendSummary(opts?: {
10
+ home?: string;
11
+ now?: () => number;
12
+ }): {
13
+ month: {
14
+ modelMinutes: number | null;
15
+ modelMinutesAtLeast: any;
16
+ usd: any;
17
+ atLeast: any;
18
+ tokens: any;
19
+ };
20
+ total: {
21
+ modelMinutes: number | null;
22
+ modelMinutesAtLeast: any;
23
+ usd: any;
24
+ atLeast: any;
25
+ tokens: any;
26
+ };
27
+ byProvider: {
28
+ [k: string]: {
29
+ label: string;
30
+ month: {
31
+ modelMinutes: number | null;
32
+ modelMinutesAtLeast: any;
33
+ usd: any;
34
+ atLeast: any;
35
+ tokens: any;
36
+ };
37
+ total: {
38
+ modelMinutes: number | null;
39
+ modelMinutesAtLeast: any;
40
+ usd: any;
41
+ atLeast: any;
42
+ tokens: any;
43
+ };
44
+ };
45
+ };
46
+ undatedRows: number;
47
+ preM4dRunsNotCounted: boolean;
48
+ };
49
+ /**
50
+ * @typedef {object} Claim
51
+ * @property {boolean} ok the hold fits (or no limit is set)
52
+ * @property {string} holdId the hold row's id (a $0 hold when no limit is set)
53
+ * @property {{limitUsd:number|null, leftUsd:number|null, heldUsd:number, heldRuns:number, needUsd:number, atLeast:boolean}} room
54
+ */
55
+ /**
56
+ * The check at a door. Appends the hold row first (always, even with no limit), then decides. Throws ConfigError when config.json is
57
+ * broken (nothing is appended) or the row cannot be written. A refusal appends a `refused` row.
58
+ * @param {{ what: 'run'|'resume'|'draft', flow: string|null, runId: string|null, runDir: string, holdUsd: number, spentAtHold?: number, home?: string, now?: () => number }} a
59
+ * @returns {Claim}
60
+ */
61
+ export function claimHold({ what, flow, runId, runDir, holdUsd, spentAtHold, home, now, }: {
62
+ what: "run" | "resume" | "draft";
63
+ flow: string | null;
64
+ runId: string | null;
65
+ runDir: string;
66
+ holdUsd: number;
67
+ spentAtHold?: number;
68
+ home?: string;
69
+ now?: () => number;
70
+ }): Claim;
71
+ /**
72
+ * The run's own process ends or parks: give the hold back. Never throws (a failed settle is closed by the
73
+ * next check as "process gone"). `alsoRunDirs` names dirs this process also spent into (a rerun's new run).
74
+ * @param {{ holdId: string|null, why: string, home?: string, now?: () => number, alsoRunDirs?: string[] }} a
75
+ */
76
+ export function settleHold({ holdId, why, home, now, alsoRunDirs, }: {
77
+ holdId: string | null;
78
+ why: string;
79
+ home?: string;
80
+ now?: () => number;
81
+ alsoRunDirs?: string[];
82
+ }): void;
83
+ /**
84
+ * The ONE refusal text (CLI and page): the amount line, then the signed sentence.
85
+ * @param {Claim['room']} room
86
+ */
87
+ export function monthlyRefusalText(room: Claim["room"]): string;
88
+ export { ConfigError };
89
+ export const REFUSAL_SENTENCE: "Nothing spent. Raise the monthly limit in Settings, or wait for next month.";
90
+ export const NOT_RECORDED: "not recorded";
91
+ export type Claim = {
92
+ /**
93
+ * the hold fits (or no limit is set)
94
+ */
95
+ ok: boolean;
96
+ /**
97
+ * the hold row's id (a $0 hold when no limit is set)
98
+ */
99
+ holdId: string;
100
+ room: {
101
+ limitUsd: number | null;
102
+ leftUsd: number | null;
103
+ heldUsd: number;
104
+ heldRuns: number;
105
+ needUsd: number;
106
+ atLeast: boolean;
107
+ };
108
+ };
109
+ import { ConfigError } from './config.js';
@@ -1,6 +1,8 @@
1
1
  /**
2
- * @param {{ root: string, env?: Record<string, string|undefined>, bin?: string, logDir?: string,
2
+ * @param {{ root: string, env?: Record<string, string|undefined>, loadEnv?: () => { ok: boolean, env: Record<string, string|undefined>, refusal: string|null }, bin?: string, logDir?: string,
3
3
  * maxTries?: number, windowMs?: number, slotMs?: number }} opts
4
+ * `loadEnv` (M4d: the keys-file door, called before EVERY spawn so editing the file needs no panel restart) returns the merged env
5
+ * that is BOTH the child's spawn env AND its scrub list, or a refusal sentence that becomes the attempt's refusal (nothing spawns).
4
6
  * `env`/`bin`/`logDir`/`maxTries`/`windowMs`/`slotMs` are injectable so tests neither sleep 10 s
5
7
  * nor need a live key; production passes none of them. `slotMs` (default `windowMs / maxTries`,
6
8
  * i.e. 2000 ms) is only the spacing between tries: a test sets it small and `windowMs` (the
@@ -10,6 +12,11 @@
10
12
  export function createResumer(opts: {
11
13
  root: string;
12
14
  env?: Record<string, string | undefined>;
15
+ loadEnv?: () => {
16
+ ok: boolean;
17
+ env: Record<string, string | undefined>;
18
+ refusal: string | null;
19
+ };
13
20
  bin?: string;
14
21
  logDir?: string;
15
22
  maxTries?: number;
@@ -30,13 +30,14 @@ export function writeTokenFile({ port, token, dir, env, }: {
30
30
  * real listening socket where that is simpler.
31
31
  * @param {import('node:http').IncomingMessage} req
32
32
  * @param {import('node:http').ServerResponse} res
33
- * @param {{ root: string, port: number, token: string, resumer: ReturnType<typeof createResumer> }} opts
33
+ * @param {{ root: string, port: number, token: string, resumer: ReturnType<typeof createResumer>, settings: ReturnType<typeof createSettings> }} opts
34
34
  */
35
35
  export function handleRequest(req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse, opts: {
36
36
  root: string;
37
37
  port: number;
38
38
  token: string;
39
39
  resumer: ReturnType<typeof createResumer>;
40
+ settings: ReturnType<typeof createSettings>;
40
41
  }): void;
41
42
  /**
42
43
  * Start the panel server. Binds `127.0.0.1` ONLY. A taken port is a LOUD,
@@ -44,7 +45,7 @@ export function handleRequest(req: import("node:http").IncomingMessage, res: imp
44
45
  * header). Resolves once actually listening; rejects on a bind error
45
46
  * (including `EADDRINUSE`) with a `.port` field on the error for the
46
47
  * caller's message.
47
- * @param {{ port?: number, root: string, token?: string, resume?: { env?: Record<string,string|undefined>, bin?: string, logDir?: string, maxTries?: number, windowMs?: number, slotMs?: number } }} opts
48
+ * @param {{ port?: number, root: string, token?: 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 } }} opts
48
49
  * `resume` is for tests only (a fake env/bin, a short retry window); the CLI passes none.
49
50
  * @returns {Promise<{ server: import('node:http').Server, port: number, token: string, close: () => Promise<void> }>}
50
51
  */
@@ -52,6 +53,12 @@ export function createPanelServer(opts: {
52
53
  port?: number;
53
54
  root: string;
54
55
  token?: string;
56
+ settings?: {
57
+ home?: string;
58
+ env?: Record<string, string | undefined>;
59
+ fetch?: typeof fetch;
60
+ now?: () => number;
61
+ };
55
62
  resume?: {
56
63
  env?: Record<string, string | undefined>;
57
64
  bin?: string;
@@ -83,3 +90,4 @@ export function panelMain(argv: string[], ctx: {
83
90
  * side by side. */
84
91
  export const DEFAULT_PORT: 4800;
85
92
  import { createResumer } from './resume.js';
93
+ import { createSettings } from './settings.js';
@@ -0,0 +1,23 @@
1
+ /**
2
+ * @param {{ home?: string, skip?: boolean, env?: Record<string,string|undefined>, fetch?: typeof fetch, now?: () => number }} cfg
3
+ * `home` the config home (undefined = the real `~/.config/fwdloop`); `skip` true under a test process
4
+ * with no `FWDLOOP_CONFIG_HOME` (Settings then touches nothing); `env` the shell side (tests only);
5
+ * `fetch` and `now` are test seams.
6
+ */
7
+ export function createSettings(cfg: {
8
+ home?: string;
9
+ skip?: boolean;
10
+ env?: Record<string, string | undefined>;
11
+ fetch?: typeof fetch;
12
+ now?: () => number;
13
+ }): {
14
+ handle: ({ method, pathname, query, body }: {
15
+ method: string;
16
+ pathname: string;
17
+ query: URLSearchParams;
18
+ body: any;
19
+ }) => Promise<{
20
+ status: number;
21
+ body: any;
22
+ }>;
23
+ };
@@ -1,70 +1,39 @@
1
+ /**
2
+ * THE one lookup of a slot's model, API shape and address (M4d amendment 1). Every model call (run,
3
+ * resume, model step, drafter), Test, Balance and the spend rows read the slot through this and nothing
4
+ * else: a value saved on the Settings page (`config.providers[slot]`) wins per field, else the code
5
+ * default above. A blank saved Base URL means the default FOR THE EFFECTIVE SHAPE: the slot's own code
6
+ * address while the shape is the slot's code shape, else that shape's vendor address ('' = bare-agent's own).
7
+ * Unknown slot throws. `config` is already-read config (see `readPriceConfig`); no I/O here.
8
+ * @param {string} slotName
9
+ * @param {{ config?: Record<string, any> }} [opts]
10
+ * @returns {{ slot: string, envVar: string, legacyMaxTokens: boolean,
11
+ * model: string, shape: string, baseUrl: string,
12
+ * defaults: { model: string, shape: string, baseUrl: string } }}
13
+ */
14
+ export function resolveSlot(slotName: string, { config }?: {
15
+ config?: Record<string, any>;
16
+ }): {
17
+ slot: string;
18
+ envVar: string;
19
+ legacyMaxTokens: boolean;
20
+ model: string;
21
+ shape: string;
22
+ baseUrl: string;
23
+ defaults: {
24
+ model: string;
25
+ shape: string;
26
+ baseUrl: string;
27
+ };
28
+ };
1
29
  /**
2
30
  * Strip an `hf:` routing prefix and look up `suffix` with `Object.hasOwn` —
3
31
  * never plain truthiness/`in`, which would let a suffix like `"constructor"`
4
32
  * resolve to an inherited `Object.prototype` member.
33
+ * @param {string|null|undefined} modelId
34
+ * @param {Record<string, any>} [ratesTable]
5
35
  */
6
- export function lookupRate(modelId: any, ratesTable?: {
7
- 'zai-org/GLM-5.2': {
8
- in: number;
9
- out: number;
10
- source: string;
11
- };
12
- 'moonshotai/Kimi-K3': {
13
- in: number;
14
- out: number;
15
- source: string;
16
- };
17
- 'zai-org/GLM-5.3-Flash': {
18
- in: number;
19
- out: number;
20
- source: string;
21
- };
22
- 'zai-org/GLM-4.7-Flash': {
23
- in: number;
24
- out: number;
25
- source: string;
26
- };
27
- 'Qwen/Qwen3.8-27B': {
28
- in: number;
29
- out: number;
30
- source: string;
31
- };
32
- 'openai/gpt-oss-120b': {
33
- in: number;
34
- out: number;
35
- source: string;
36
- };
37
- 'nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-NVFP4': {
38
- in: number;
39
- out: number;
40
- source: string;
41
- };
42
- 'syn:large:text': {
43
- in: number;
44
- out: number;
45
- source: string;
46
- };
47
- 'syn:small:text': {
48
- in: number;
49
- out: number;
50
- source: string;
51
- };
52
- 'deepseek-v4-flash': {
53
- in: number;
54
- out: number;
55
- source: string;
56
- };
57
- 'deepseek-flash': {
58
- in: number;
59
- out: number;
60
- source: string;
61
- };
62
- 'deepseek-v4-pro': {
63
- in: number;
64
- out: number;
65
- source: string;
66
- };
67
- }): {
36
+ export function lookupRate(modelId: string | null | undefined, ratesTable?: Record<string, any>): {
68
37
  suffix: string;
69
38
  rates: any;
70
39
  } | null;
@@ -123,6 +92,7 @@ export function resolveModelRate(modelId: any, ratesTable?: {
123
92
  };
124
93
  'deepseek-flash': {
125
94
  in: number;
95
+ cacheIn: number;
126
96
  out: number;
127
97
  source: string;
128
98
  };
@@ -135,10 +105,71 @@ export function resolveModelRate(modelId: any, ratesTable?: {
135
105
  suffix: string;
136
106
  rates: any;
137
107
  };
108
+ /**
109
+ * THE one price lookup (M4d scope item 6): every model call — run, resume, model step, drafter —
110
+ * is booked and cap-checked from this. Per field: a Settings price (`config.prices[slot]`, USD per
111
+ * 1M -> per 1K) wins, else the code table's row, else the table's HIGHEST entry for that field
112
+ * (an unknown model; unknown cost is never 0). A cache-read price is known only from Settings or a
113
+ * row's `cacheIn`; otherwise it is left out (`cacheReadMult` omitted -> bare-agent's 0.1x of `in`).
114
+ *
115
+ * @param {string} modelId
116
+ * @param {{ slot?: string, config?: Record<string, any>, ratesTable?: Record<string, any> }} [opts]
117
+ * @returns {{
118
+ * rates: { in: number, out: number, cacheReadMult?: number },
119
+ * perM: { inPerM: number, cachedInPerM: number, outPerM: number },
120
+ * source: { in: 'settings'|'table'|'ceiling', cachedIn: 'settings'|'table'|'default-multiplier', out: 'settings'|'table'|'ceiling' },
121
+ * suffix: string|null,
122
+ * }}
123
+ */
124
+ export function resolvePrices(modelId: string, { slot, config, ratesTable }?: {
125
+ slot?: string;
126
+ config?: Record<string, any>;
127
+ ratesTable?: Record<string, any>;
128
+ }): {
129
+ rates: {
130
+ in: number;
131
+ out: number;
132
+ cacheReadMult?: number;
133
+ };
134
+ perM: {
135
+ inPerM: number;
136
+ cachedInPerM: number;
137
+ outPerM: number;
138
+ };
139
+ source: {
140
+ in: "settings" | "table" | "ceiling";
141
+ cachedIn: "settings" | "table" | "default-multiplier";
142
+ out: "settings" | "table" | "ceiling";
143
+ };
144
+ suffix: string | null;
145
+ };
146
+ /**
147
+ * The `price` object a spend row records: the per-1M numbers the call was booked at and where each
148
+ * came from. From a `resolvePrices` result; or from INJECTED rates (tests) with source "injected".
149
+ * @param {{ perM: any, source: any }|null|undefined} prices
150
+ * @param {{ in: number, out: number, cacheReadMult?: number }|null|undefined} [injectedRates]
151
+ */
152
+ export function priceRecord(prices: {
153
+ perM: any;
154
+ source: any;
155
+ } | null | undefined, injectedRates?: {
156
+ in: number;
157
+ out: number;
158
+ cacheReadMult?: number;
159
+ } | null | undefined): any;
160
+ /**
161
+ * The config a model call is priced against, read at the door: `{}` when no config applies
162
+ * (a test process with no `FWDLOOP_CONFIG_HOME`), else the validated `config.json`. A broken
163
+ * config THROWS (ConfigError) — a run's charge never changes silently.
164
+ * @param {string} [home] explicit config home (a test); default: the door's home
165
+ */
166
+ export function readPriceConfig(home?: string): Record<string, any>;
138
167
  /**
139
168
  * The ceiling cost (USD) of one round of `modelId` — never 0, never null.
140
169
  * A known model prices at its own rate; an unknown/missing model prices at
141
- * the HIGHEST in/out rate anywhere in `ratesTable`.
170
+ * the HIGHEST in/out rate anywhere in `ratesTable`. `opts.prices` (a
171
+ * `resolvePrices` result, e.g. from `makeProvider`) makes the cap check use the
172
+ * SAME price the round is booked at.
142
173
  */
143
174
  export function ceilingCostUsd(modelId: any, ratesTable?: {
144
175
  'zai-org/GLM-5.2': {
@@ -193,6 +224,7 @@ export function ceilingCostUsd(modelId: any, ratesTable?: {
193
224
  };
194
225
  'deepseek-flash': {
195
226
  in: number;
227
+ cacheIn: number;
196
228
  out: number;
197
229
  source: string;
198
230
  };
@@ -201,7 +233,7 @@ export function ceilingCostUsd(modelId: any, ratesTable?: {
201
233
  out: number;
202
234
  source: string;
203
235
  };
204
- }): number;
236
+ }, opts?: {}): number;
205
237
  /**
206
238
  * Compare the model asked for against the model actually served.
207
239
  * `match` identical; `prefix` identical once a routing prefix is stripped;
@@ -238,6 +270,17 @@ export function sumMeterings(events: any): {
238
270
  /** Append one spend row, stamping `modelMatch` — the one writer for
239
271
  * spend.jsonl. Warns (never throws) on a `substituted` model. */
240
272
  export function appendSpendRow(path: any, row: any): void;
273
+ /**
274
+ * The one rule for what a spend row costs: `usd` and whether it is `complete`. An incomplete row (a call
275
+ * died unmetered, or a round was left unpriced) counts its priced floor PLUS one ceiling per unmetered call
276
+ * (unknown cost is never 0). Same shape as poc/m6a/batch.mjs rowCostUsd.
277
+ * @param {any} row
278
+ * @returns {{usd: number, complete: boolean}}
279
+ */
280
+ export function spendRowCost(row: any): {
281
+ usd: number;
282
+ complete: boolean;
283
+ };
241
284
  /**
242
285
  * `appendSpendRow`'s own sibling reader (M4a piece 2, docs/wiki/the-module-
243
286
  * ladder.md M4a scope item 2: "one reader per book") — every row as written,
@@ -281,24 +324,30 @@ export function checkKeyPreflight(slotName: string, env?: Record<string, string
281
324
  * values this project uses.
282
325
  *
283
326
  * @param {string} slotName
284
- * @param {{ model?: string, timeoutMs?: number, deadlineMs?: number, thinking?: object|null }} [options]
327
+ * @param {{ model?: string, timeoutMs?: number, deadlineMs?: number, thinking?: object|null, env?: Record<string,string|undefined>, configHome?: string }} [options]
328
+ * `configHome` (a test) is where `config.json` prices are read; default: the door's home (`readPriceConfig`).
329
+ * `env` (M4d: the merged shell+keys-file env; default process.env) is where the key is read.
285
330
  * `thinking` (bare-agent >=0.49) is sent verbatim as body.thinking; unset/null leaves the body unchanged.
286
- * @returns {{ provider: any, rates: {in:number, out:number}, modelId: string, suffix: string, slot: string }}
331
+ * @returns {{ provider: any, rates: {in:number, out:number, cacheReadMult?:number}, modelId: string, suffix: string|null, slot: string, prices: ReturnType<typeof resolvePrices> }}
287
332
  */
288
333
  export function makeProvider(slotName: string, options?: {
289
334
  model?: string;
290
335
  timeoutMs?: number;
291
336
  deadlineMs?: number;
292
337
  thinking?: object | null;
338
+ env?: Record<string, string | undefined>;
339
+ configHome?: string;
293
340
  }): {
294
341
  provider: any;
295
342
  rates: {
296
343
  in: number;
297
344
  out: number;
345
+ cacheReadMult?: number;
298
346
  };
299
347
  modelId: string;
300
- suffix: string;
348
+ suffix: string | null;
301
349
  slot: string;
350
+ prices: ReturnType<typeof resolvePrices>;
302
351
  };
303
352
  /** Provider slots. Frozen — add a new slot here, never inline a baseUrl/env
304
353
  * var elsewhere. `deepseek` is the baseline (F12); `synthetic` is second. */
@@ -307,20 +356,26 @@ export const PROVIDER_SLOTS: Readonly<{
307
356
  baseUrl: "https://api.synthetic.new/openai/v1";
308
357
  envVar: "SYNTHETIC_API_KEY";
309
358
  defaultModel: "hf:Qwen/Qwen3.8-27B";
359
+ shape: "openai-api";
310
360
  legacyMaxTokens: false;
311
361
  }>;
312
362
  deepseek: Readonly<{
313
363
  baseUrl: "https://api.deepseek.com";
314
364
  envVar: "DEEPSEEK_API_KEY";
315
365
  defaultModel: "deepseek-flash";
366
+ shape: "openai-api";
316
367
  legacyMaxTokens: true;
317
368
  }>;
318
369
  }>;
319
370
  /**
320
371
  * List-rate ceilings (USD/1K tokens), hand-entered — see
321
- * poc/m0/spend.mjs@76a3607 for sourcing notes per row. A rate changes by
322
- * editing a row here, never a second table or a runtime flag (hamr's
323
- * ruling, 2026-09-21).
372
+ * poc/m0/spend.mjs@76a3607 for sourcing notes per row. This table is the DEFAULT
373
+ * price: a price set in Settings (`~/.config/fwdloop/config.json` `prices`, per
374
+ * provider slot) wins over a row here, per field, through `resolvePrices` below —
375
+ * the one lookup every model call is booked and cap-checked by (M4d, signed
376
+ * 2026-10-05; that REPLACES the 2026-09-21 "edit a row here, never a runtime
377
+ * flag" ruling). `cacheIn` (optional) is the cache-READ price per 1K; a row
378
+ * without it books cache reads at bare-agent's default 0.1x of `in`.
324
379
  */
325
380
  export const RATES_BY_SUFFIX: {
326
381
  'zai-org/GLM-5.2': {
@@ -375,6 +430,7 @@ export const RATES_BY_SUFFIX: {
375
430
  };
376
431
  'deepseek-flash': {
377
432
  in: number;
433
+ cacheIn: number;
378
434
  out: number;
379
435
  source: string;
380
436
  };