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.
@@ -1,3 +1,44 @@
1
+ /**
2
+ * Resolve `<root>/<flowName>` safely — `checkFlowName` first (never a raw
3
+ * string joined into a path). `checkFlowName` rules out a flowName that
4
+ * escapes `root` lexically (no `/`, `\`, `..`), but a flow directory named
5
+ * by URL is not required to have come from `listFlowNames` first — a
6
+ * request can name a flow directly. So if `<root>/<flowName>` actually
7
+ * exists, it is re-checked with `realpathSync`: it must resolve inside the
8
+ * real `root`, same class of hole `resolveRunDir` closes for a run dir one
9
+ * level down (a symlinked flow directory would never show up in a
10
+ * `listFlowNames` listing, since a symlink dirent never reports
11
+ * `isDirectory()`, but a direct request naming it by its allow-list-legal
12
+ * name must still be refused). A not-yet-existing flow directory has
13
+ * nothing to realpath, so only the lexical result applies to it.
14
+ * Returns the flow directory, or a refusal.
15
+ * @param {string} root
16
+ * @param {string} flowName
17
+ * @returns {{ok:true, flowDir:string}|{ok:false, red:string, why?:'outside-root'}}
18
+ */
19
+ export function resolveFlowDir(root: string, flowName: string): {
20
+ ok: true;
21
+ flowDir: string;
22
+ } | {
23
+ ok: false;
24
+ red: string;
25
+ why?: "outside-root";
26
+ };
27
+ /**
28
+ * A consumed-answer marker exists for THIS ask (`askId`) — `answerAsk`'s own write
29
+ * (`src/ask.js`) renames to `answer.<askId>.consumed.json` on accept, and
30
+ * `resumeRun` (`src/runner.js`) does the same when it consumes an in-place
31
+ * `answer.json`. A directory-naming-convention check, not a "book" with its
32
+ * own single-row shape, so it lives here rather than growing a one-off
33
+ * reader in either writer's module. Per the signed rule (ladder M4a scope
34
+ * item 4) it is per the OPEN ask's askId: after redo -> re-park the old
35
+ * ask's marker stays on disk and must not answer the new ask. An ask with no
36
+ * askId (pre-M3) can be paired with no marker: false.
37
+ * @param {string} runDir
38
+ * @param {string|null} askId the open ask's own askId
39
+ * @returns {boolean}
40
+ */
41
+ export function hasConsumedAnswer(runDir: string, askId: string | null): boolean;
1
42
  /**
2
43
  * M4b piece 2: a SAVED, not-yet-consumed answer — `answer.json` (what
3
44
  * `answerAsk` writes; the resume consumes it by renaming it away, F44). Read
@@ -13,15 +54,16 @@ export function readSavedAnswer(runDir: string): {
13
54
  } | null;
14
55
  /**
15
56
  * M4b amendment 1 scope 2: the ONE derivation of "answer saved, resume not
16
- * started". From the books: an answer saved (`answer.json` present) and so
17
- * unconsumed. From the panel's in-memory attempt record (`attempt`, may be
57
+ * started" (now worded "your answer is saved; the run stopped before using it" — M4c-fix amendment 3 (c)).
58
+ * From the books: an answer saved (`answer.json` present) and so unconsumed. From the panel's in-memory attempt record (`attempt`, may be
18
59
  * null): whether a resume is still being started, and the resume's own refusal.
19
60
  * `null` when there is nothing to say (no saved answer and no attempt).
20
- * M4c amendment 3: `ask` (the run's open `ask.json`, may be null). A saved answer for that ask that was
21
- * NOT saved in time (`answerTiming`) once the deadline has passed is not a resumable answer: it reads as
22
- * none, so the run is `[!]` expired, the same as an ask nobody answered.
61
+ * M4c amendment 3: `ask` (the run's open `ask.json`, may be null; its `expiresAt` is the effective deadline). A saved
62
+ * answer for that ask that was NOT saved in time, once the deadline has passed, is not a resumable answer: it reads
63
+ * as none, so the ask is expired and offers the reopen (M4c-fix amendment 1 (b)). One with no readable time, before
64
+ * the deadline, reads `broken` (amendment 1 (a)).
23
65
  * @param {{savedAnswer: {askId:string, decision:string|null, answeredAt?:string|null}|null, attempt: any, ask?: any}} ctx
24
- * @returns {{state: 'starting'|'not-started'|'took-over', askId: string|null, tries: number|null, maxTries: number|null, reason: string|null, label: string}|null}
66
+ * @returns {{state: 'starting'|'not-started'|'broken'|'took-over', askId: string|null, tries: number|null, maxTries: number|null, reason: string|null, label: string}|null}
25
67
  */
26
68
  export function deriveResumeState({ savedAnswer: saved, attempt, ask }: {
27
69
  savedAnswer: {
@@ -32,7 +74,7 @@ export function deriveResumeState({ savedAnswer: saved, attempt, ask }: {
32
74
  attempt: any;
33
75
  ask?: any;
34
76
  }): {
35
- state: "starting" | "not-started" | "took-over";
77
+ state: "starting" | "not-started" | "broken" | "took-over";
36
78
  askId: string | null;
37
79
  tries: number | null;
38
80
  maxTries: number | null;
@@ -40,32 +82,49 @@ export function deriveResumeState({ savedAnswer: saved, attempt, ask }: {
40
82
  label: string;
41
83
  } | null;
42
84
  /**
43
- * M4c amendment 2 (a): the ONE rule for "stuck". The answer is saved and not yet
44
- * taken (`resume.state === 'not-started'`: `answer.json` is on disk; the panel's
45
- * transient 'starting' is not stuck) and nothing is carrying the run on: the
46
- * newest pid row's process is not alive AND the resume lock is not held by a
47
- * live process (`readResumeLock`, src/liveness.js). computeGlyph, the Inbox
48
- * (`listStops`) and Runs (`listRuns`) all read this, never a second copy.
85
+ * The sign's word and the plain line after the dash. The existing plain line is kept as is; only a line that already
86
+ * opens with the word ("stuck — …") or is the word itself ("passed") loses that repeat, so it is never said twice.
87
+ * `noWord`: a run the human ended on purpose with rerun wears `[✗]` but is never called "failed" (M4b amendment 3),
88
+ * so it shows its plain line alone.
89
+ * @param {string} glyph a `computeGlyph` sign @param {string} label its plain line @param {boolean} [noWord]
90
+ * @returns {{word: string|null, line: string|null}}
91
+ */
92
+ export function signParts(glyph: string, label: string, noWord?: boolean): {
93
+ word: string | null;
94
+ line: string | null;
95
+ };
96
+ /**
97
+ * The ONE decision "is this run stuck, why, and what does it say" (M4c amendment 2 (a), amendment 3 (e), M4c-fix 15,
98
+ * 16). The answer is saved and not yet taken (`resume.state === 'not-started'`: `answer.json` is on disk; the
99
+ * panel's transient 'starting' and the `late` state are not stuck) and nothing is carrying the run on: the newest
100
+ * pid row's process is not alive AND the resume lock is not held by a live process, nor by one whose liveness
101
+ * cannot be told (`unknown`: never called stuck). The reason is typed, derived from the lock file and the saved
102
+ * answer themselves — never from a refusal string, so it is the same after a panel restart. Everything that shows
103
+ * "stuck" (computeGlyph, the Inbox, Runs, the Ask tab) reads this.
49
104
  * @param {{resume?: any, liveness?: 'running'|'gone'|'unknown', lock?: string}} ctx
50
- * @returns {boolean}
105
+ * @returns {{stuck: false, reason: null, label: null, why: null}|{stuck: true, reason: 'retry'|'lock-no-holder', label: string, why: string|null}}
51
106
  */
52
- export function isStuck({ resume, liveness, lock }: {
107
+ export function stuckState({ resume, liveness, lock }: {
53
108
  resume?: any;
54
109
  liveness?: "running" | "gone" | "unknown";
55
110
  lock?: string;
56
- }): boolean;
57
- /**
58
- * M4c amendment 3 (e): the ONE choice of the stuck label. After a "Try the resume again" the runner
59
- * refused for a lock with no recorded holder (`LOCK_NO_HOLDER`, src/liveness.js) and that lock is
60
- * still there unreadable (`lock === 'empty'`), trying again can never work: the label says to remove
61
- * the file by hand. Every other stuck run keeps `STUCK_LABEL`.
62
- * @param {{resume?: any, lock?: string}} ctx
63
- * @returns {string}
64
- */
65
- export function stuckLabelFor({ resume, lock }: {
111
+ }): {
112
+ stuck: false;
113
+ reason: null;
114
+ label: null;
115
+ why: null;
116
+ } | {
117
+ stuck: true;
118
+ reason: "retry" | "lock-no-holder";
119
+ label: string;
120
+ why: string | null;
121
+ };
122
+ /** @param {{resume?: any, liveness?: 'running'|'gone'|'unknown', lock?: string}} ctx @returns {boolean} */
123
+ export function isStuck(ctx: {
66
124
  resume?: any;
125
+ liveness?: "running" | "gone" | "unknown";
67
126
  lock?: string;
68
- }): string;
127
+ }): boolean;
69
128
  /**
70
129
  * M4c item 1: does this sign pulse? Only `[▶]` running and `[·]` WAITING ON YOU
71
130
  * do, and `[II]` stuck (M4c amendment 2: it is not a final state). The other
@@ -102,7 +161,7 @@ export function glyphPulses(g: {
102
161
  * - `[?]` died / unknown — no history row, no open ask, and either the
103
162
  * pid row's process is gone (M4c), or there is no pid row / no /proc and
104
163
  * the books are older than 10 minutes. Never guessed into `[✗]` or `[✓]`.
105
- * - `[·]` answer saved, resume not started / starting (M4b amendment 1) —
164
+ * - `[·]` your answer is saved; the run stopped before using it / starting (M4b amendment 1) —
106
165
  * `answer.json` still on disk (`resume` = `deriveResumeState`): never
107
166
  * "waiting on you" (the human already answered) and never a success.
108
167
  * - `[▶]` running (M4c) — no end row, no open unanswered ask, and either the
@@ -590,6 +649,26 @@ export function inboxOpenCount(rows: any[]): number;
590
649
  * (it restarted since the answer was saved) — said so, never blank. */
591
650
  export const RESUME_REASON_UNKNOWN: "reason unknown: the panel restarted, so it has no record of the resume attempt";
592
651
  export const WAITING_LABEL: "waiting on you (parked, unanswered)";
593
- export const STUCK_LABEL: "stuck \u2014 answer saved, click try the resume again";
594
- export const STUCK_LOCK_LABEL: "stuck \u2014 remove the old resume lock by hand, then try again";
652
+ export const STUCK_LABEL: "stuck \u2014 your answer is saved; the run stopped before using it";
653
+ export const STUCK_LOCK_LABEL: "stuck \u2014 an old resume lock is in the way";
654
+ export const BROKEN_LABEL: "Your saved answer could not be read.";
655
+ export const BROKEN_ANSWER_WHY: "Please answer again; the broken one is kept aside.";
595
656
  export const CRASHED_LABEL: "crashed after taking your answer \u2014 start a fresh run";
657
+ /**
658
+ * M4c-fix amendment 2 (g): the ONE table from a sign to its bold word. Runs, the Inbox and the run header all show
659
+ * the word this table gives (the server stamps it on every row; the page never invents one).
660
+ * @type {Record<string, string>}
661
+ */
662
+ export const SIGN_WORDS: Record<string, string>;
663
+ /** The typed reasons a stuck run can have. `retry`: nothing is wrong that the books name, so trying again is the
664
+ * action. `lock-no-holder`: the resume lock has no recorded holder, so trying again can never work. */
665
+ export const STUCK_REASONS: {
666
+ retry: {
667
+ label: string;
668
+ why: null;
669
+ };
670
+ 'lock-no-holder': {
671
+ label: string;
672
+ why: string;
673
+ };
674
+ };
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Remove `<runDir>/resume.lock`, only if at THIS moment it has no recorded holder (`readResumeLock` -> `empty`;
3
+ * a live, dead or unknowable holder is never touched), and only if the lock file really sits inside this run dir
4
+ * (realpath of the run dir against realpath of `--root` at use time; a symlinked lock is unlinked as the link itself,
5
+ * never followed).
6
+ * Then one audit row through the one audit writer, shaped like the `ask-reopened` row (a pure note: cost 0, no model).
7
+ * @param {{root: string, runDir: string, nowIso?: string}} a
8
+ * @returns {{ok: true, at: string}|{ok: false, refused: 'no-lock'|'lock-has-holder'|'lock-outside-run', red: string}}
9
+ */
10
+ export function removeOldLock({ root, runDir, nowIso }: {
11
+ root: string;
12
+ runDir: string;
13
+ nowIso?: string;
14
+ }): {
15
+ ok: true;
16
+ at: string;
17
+ } | {
18
+ ok: false;
19
+ refused: "no-lock" | "lock-has-holder" | "lock-outside-run";
20
+ red: string;
21
+ };
@@ -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;
@@ -40,6 +47,10 @@ export function createResumer(opts: {
40
47
  logPath: null;
41
48
  superseded: boolean;
42
49
  };
50
+ /** True while this run is already resuming: a resume child of this panel is alive for it, or its
51
+ * latest attempt is still starting (between tries). Routes refuse a second resume while true.
52
+ * @param {string} flow @param {string} runId */
53
+ busy(flow: string, runId: string): boolean;
43
54
  /** A copy of the run's attempt record, or null (none yet, or the panel restarted).
44
55
  * @param {string} flow @param {string} runId */
45
56
  get(flow: string, runId: string): any;
@@ -1,16 +1,43 @@
1
+ /**
2
+ * hamr's 2026-10-03 ruling "1A": the panel token is REUSED across restarts, so a bookmark of
3
+ * `http://127.0.0.1:<port>/` keeps working once the link was opened. Reads the token file (same path
4
+ * `writeTokenFile` writes); a new token only when the file is missing, unreadable, not a regular file,
5
+ * not mode 0600, not ours, or not 64 hex chars (the caller then rewrites it 0600).
6
+ * @param {{ port: number, dir?: string, env?: Record<string, string|undefined> }} a
7
+ * @returns {string}
8
+ */
9
+ export function loadOrMakeToken({ port, dir, env }: {
10
+ port: number;
11
+ dir?: string;
12
+ env?: Record<string, string | undefined>;
13
+ }): string;
14
+ /**
15
+ * M4c-fix item 2: the token's one on-disk home — `<dir>/panel-<port>.token`, dir 0700, file 0600,
16
+ * `dir` = `$XDG_RUNTIME_DIR/fwdloop`, else `~/.cache/fwdloop`. Refuses a dir that is a symlink or
17
+ * not ours. The file is replaced (unlink, then exclusive create at 0600), never rewritten in place,
18
+ * so it never exists with a looser mode. Returns the file's path.
19
+ * @param {{ port: number, token: string, dir?: string, env?: Record<string, string|undefined> }} a
20
+ */
21
+ export function writeTokenFile({ port, token, dir, env, }: {
22
+ port: number;
23
+ token: string;
24
+ dir?: string;
25
+ env?: Record<string, string | undefined>;
26
+ }): string;
1
27
  /**
2
28
  * Handle one request against the API + the page. Exported
3
29
  * separately from {@link createPanelServer} so tests can drive it without a
4
30
  * real listening socket where that is simpler.
5
31
  * @param {import('node:http').IncomingMessage} req
6
32
  * @param {import('node:http').ServerResponse} res
7
- * @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
8
34
  */
9
35
  export function handleRequest(req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse, opts: {
10
36
  root: string;
11
37
  port: number;
12
38
  token: string;
13
39
  resumer: ReturnType<typeof createResumer>;
40
+ settings: ReturnType<typeof createSettings>;
14
41
  }): void;
15
42
  /**
16
43
  * Start the panel server. Binds `127.0.0.1` ONLY. A taken port is a LOUD,
@@ -18,13 +45,20 @@ export function handleRequest(req: import("node:http").IncomingMessage, res: imp
18
45
  * header). Resolves once actually listening; rejects on a bind error
19
46
  * (including `EADDRINUSE`) with a `.port` field on the error for the
20
47
  * caller's message.
21
- * @param {{ port?: number, root: 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
22
49
  * `resume` is for tests only (a fake env/bin, a short retry window); the CLI passes none.
23
- * @returns {Promise<{ server: import('node:http').Server, port: number, close: () => Promise<void> }>}
50
+ * @returns {Promise<{ server: import('node:http').Server, port: number, token: string, close: () => Promise<void> }>}
24
51
  */
25
52
  export function createPanelServer(opts: {
26
53
  port?: number;
27
54
  root: string;
55
+ token?: string;
56
+ settings?: {
57
+ home?: string;
58
+ env?: Record<string, string | undefined>;
59
+ fetch?: typeof fetch;
60
+ now?: () => number;
61
+ };
28
62
  resume?: {
29
63
  env?: Record<string, string | undefined>;
30
64
  bin?: string;
@@ -36,6 +70,7 @@ export function createPanelServer(opts: {
36
70
  }): Promise<{
37
71
  server: import("node:http").Server;
38
72
  port: number;
73
+ token: string;
39
74
  close: () => Promise<void>;
40
75
  }>;
41
76
  /**
@@ -55,3 +90,4 @@ export function panelMain(argv: string[], ctx: {
55
90
  * side by side. */
56
91
  export const DEFAULT_PORT: 4800;
57
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
  };
@@ -0,0 +1,11 @@
1
+ /**
2
+ * `id` is the value saved in config.json; `defaultUrl` is the host a blank Base URL means for a slot
3
+ * that has no code default of its own on this shape ('' = bare-agent's own default for that vendor).
4
+ * @type {readonly {id: string, label: string, defaultUrl: string}[]}
5
+ */
6
+ export const SHAPES: readonly {
7
+ id: string;
8
+ label: string;
9
+ defaultUrl: string;
10
+ }[];
11
+ export const SHAPE_IDS: readonly string[];