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/src/runner.js CHANGED
@@ -49,13 +49,13 @@ import {
49
49
  readFlow, resolveRunDir, readFileInside, resolveInside,
50
50
  } from './flow.js';
51
51
  import {
52
- writeAskArchive, readAcceptedHashesByEmits, serializeArtifact, normalizeDecision, answerTiming,
52
+ writeAskArchive, readAcceptedHashesByEmits, serializeArtifact, normalizeDecision, answerTiming, effectiveExpiresAt, withReopen,
53
53
  } from './ask.js';
54
54
  import { WIRED_VERBS } from './primitives.js';
55
55
  import { closeByClass } from './closers.js';
56
56
  import { appendAudit, appendHistory } from './books.js';
57
57
  import {
58
- readResumeLock, recordPid, writeLockHolder, LOCK_NO_HOLDER,
58
+ readResumeLock, recordPid, writeLockHolder, procStartOf, LOCK_NO_HOLDER,
59
59
  } from './liveness.js';
60
60
 
61
61
  const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -631,8 +631,19 @@ async function runStepRalph({
631
631
  // never retried (M2 scope item 8) — both are the caller's own
632
632
  // `modelStep`'s job to distinguish; this loop only ever retries the
633
633
  // `transport: true` shape, exactly once.
634
+ const first = result;
634
635
  // eslint-disable-next-line no-await-in-loop
635
636
  result = await modelStep(executorContext, grantedTools, stepMeta);
637
+ // The first call's gate refusals and tool tally belong to this attempt's
638
+ // audit row too (the retry's collector starts empty). Only refused /
639
+ // tools / ungranted are merged — cost is never touched here.
640
+ if (result && typeof result === 'object') {
641
+ const refused = [...(first.refused ?? []), ...(result.refused ?? [])];
642
+ const tools = first.tools || result.tools ? { ...(first.tools ?? {}) } : null;
643
+ if (tools) for (const [k, v] of Object.entries(result.tools ?? {})) tools[k] = (tools[k] ?? 0) + v;
644
+ const ungranted = [...new Set([...(first.ungranted ?? []), ...(result.ungranted ?? [])])].sort();
645
+ result = { ...result, refused, tools, ...(ungranted.length > 0 ? { ungranted } : {}) };
646
+ }
636
647
  }
637
648
  const wallMs = Date.now() - startedAt;
638
649
 
@@ -1480,6 +1491,15 @@ function sumAuditUsd(runDir) {
1480
1491
  return { ok: true, total };
1481
1492
  }
1482
1493
 
1494
+ /** Unlink `resume.lock` only when its recorded holder is still THIS process (`readResumeLock`'s holder pid + start
1495
+ * time against our own). A lock a later taker made in its place is never touched. */
1496
+ function releaseResumeLock(runDir, lockPath) {
1497
+ const lock = readResumeLock(runDir);
1498
+ if (lock.pid === process.pid && lock.procStart === procStartOf('self')) {
1499
+ try { unlinkSync(lockPath); } catch { /* already gone */ }
1500
+ }
1501
+ }
1502
+
1483
1503
  /**
1484
1504
  * M4c amendment 2 (d): create `resume.lock` with `wx` and write the holder into it.
1485
1505
  * An existing lock is read: holder alive (or cannot be told) -> refuse by name
@@ -1493,8 +1513,10 @@ async function takeResumeLock(runDir, runId, lockPath) {
1493
1513
  try {
1494
1514
  const lockFd = openSync(lockPath, 'wx');
1495
1515
  try { writeLockHolder(lockFd); } catch (err) {
1516
+ // This call's own `wx` just created the file and no holder is in it yet, so it is ours to remove
1517
+ // (`releaseResumeLock` would skip it: it unlinks only a lock whose holder names this process).
1518
+ try { unlinkSync(lockPath); } catch { /* already gone */ }
1496
1519
  try { closeSync(lockFd); } catch { /* ignore */ }
1497
- try { unlinkSync(lockPath); } catch { /* ignore */ }
1498
1520
  return { ok: false, red: `resume: could not record the lock holder in ${lockPath} — ${err.message}` };
1499
1521
  }
1500
1522
  return { ok: true, lockFd };
@@ -1516,10 +1538,11 @@ async function takeResumeLock(runDir, runId, lockPath) {
1516
1538
  }
1517
1539
  if (lock.state === 'dead') {
1518
1540
  // Re-read right before the unlink: a racing taker may have cleared this lock and retaken it
1519
- // already, and must not lose its fresh lock. The window left is one syscall wide, and the
1520
- // answer's rename-to-consume (F44) still lets only one resume act on the answer.
1541
+ // already, and must not lose its fresh lock. Same holder (pid and start time) as judged dead.
1542
+ // The window left is one syscall wide, and the answer's rename-to-consume (F44) still lets only
1543
+ // one resume act on the answer.
1521
1544
  const again = readResumeLock(runDir);
1522
- if (again.state === 'dead' && again.pid === lock.pid) {
1545
+ if (again.state === 'dead' && again.pid === lock.pid && again.procStart === lock.procStart) {
1523
1546
  try { unlinkSync(lockPath); } catch { /* another taker already cleared it: retry wx */ }
1524
1547
  }
1525
1548
  }
@@ -1527,6 +1550,15 @@ async function takeResumeLock(runDir, runId, lockPath) {
1527
1550
  return { ok: false, red: `resume: run "${runId}" is locked by another resumer (${lockPath})` };
1528
1551
  }
1529
1552
 
1553
+ /** Two roots are the same flow location when their real paths agree: a run parked through a symlinked `--root`
1554
+ * recorded the typed link path, and a resume (or a CLI that realpaths its root) names the real one. A path that
1555
+ * cannot be resolved is compared as typed. */
1556
+ function sameRoot(recorded, requested) {
1557
+ if (typeof recorded !== 'string' || typeof requested !== 'string') return false;
1558
+ const real = (p) => { try { return realpathSync(p); } catch { return p; } };
1559
+ return recorded === requested || real(recorded) === real(requested);
1560
+ }
1561
+
1530
1562
  /**
1531
1563
  * M3 scope items 4-6: re-enter a parked run's SAME fold from a separate
1532
1564
  * process. Takes an exclusive `resume.lock` that records its holder's
@@ -1631,7 +1663,7 @@ export async function resumeRun({
1631
1663
  // parked run whose recorded flow location disagrees with what THIS call
1632
1664
  // was asked to resume is refused by name, never re-read from wherever
1633
1665
  // the state file happens to point.
1634
- if (state.flow?.root !== root || state.flow?.name !== name) {
1666
+ if (!sameRoot(state.flow?.root, root) || state.flow?.name !== name) {
1635
1667
  return {
1636
1668
  outcome: 'refused',
1637
1669
  red: `resume: run "${runId}" was parked against flow "${state.flow?.root}/${state.flow?.name}", `
@@ -1757,6 +1789,10 @@ export async function resumeRun({
1757
1789
  } catch (err) {
1758
1790
  return { outcome: 'refused', red: `resume: answer.json for run "${runId}" is not valid JSON — ${err.message}` };
1759
1791
  }
1792
+ // Valid JSON that is not an object (`null`, a number, a string, an array) has no askId to read: refused by name.
1793
+ if (answer === null || typeof answer !== 'object' || Array.isArray(answer)) {
1794
+ return { outcome: 'refused', red: `resume: answer.json for run "${runId}" is not a JSON object (it holds ${answer === null ? 'null' : Array.isArray(answer) ? 'an array' : `a ${typeof answer}`})` };
1795
+ }
1760
1796
  // M4b amendment 3: a consumed/saved answer that says `reject` (an older
1761
1797
  // version's file) is read as `redo`; the file on disk is never rewritten.
1762
1798
  answer = { ...answer, decision: normalizeDecision(answer.decision) };
@@ -1766,7 +1802,7 @@ export async function resumeRun({
1766
1802
 
1767
1803
  // M4c amendment 3: an answer's saved time, never the restart's clock, says whether it was on time. A missing or
1768
1804
  // unreadable one is refused by name here, before the consume, so the answer stays replayable.
1769
- const timing = answerTiming(answer.answeredAt, state.expiresAt);
1805
+ const timing = answerTiming(answer.answeredAt, effectiveExpiresAt(runDir, state.askId, state.expiresAt));
1770
1806
  if (timing === 'unreadable') {
1771
1807
  return { outcome: 'refused', red: `resume: answer.json for run "${runId}" has a missing or unreadable answeredAt ("${answer.answeredAt}") — refusing rather than treating it as on time` };
1772
1808
  }
@@ -2013,8 +2049,8 @@ export async function resumeRun({
2013
2049
  if (result.outcome === 'complete') return { ...result, auditRows };
2014
2050
  return result;
2015
2051
  } finally {
2052
+ releaseResumeLock(runDir, lockPath);
2016
2053
  try { closeSync(lockFd); } catch { /* already closed */ }
2017
- try { unlinkSync(lockPath); } catch { /* already gone */ }
2018
2054
  }
2019
2055
  }
2020
2056
 
@@ -2063,7 +2099,8 @@ export function readRunState(runDir) {
2063
2099
  export function readAsk(runDir) {
2064
2100
  const result = readFileInside(runDir, 'ask.json');
2065
2101
  if (!result.ok) return null;
2066
- try { return JSON.parse(result.text); } catch { return null; }
2102
+ // The deadline every reader sees is the effective one (`withReopen`: a reopened ask's new deadline).
2103
+ try { return withReopen(runDir, JSON.parse(result.text)); } catch { return null; }
2067
2104
  }
2068
2105
 
2069
2106
  /**
package/types/ask.d.ts CHANGED
@@ -22,6 +22,13 @@ export function answerTiming(answeredAt: unknown, expiresAt: unknown): "on-time"
22
22
  * @returns {string}
23
23
  */
24
24
  export function normalizeDecision(decision: string): string;
25
+ /** Terminal control codes out of text a model wrote, before it reaches a terminal: C0 (incl. ESC, which starts
26
+ * every CSI/OSC sequence), DEL and C1 (incl. the one-byte CSI, U+009B). Keeps \n and \t. A stripped ESC leaves the
27
+ * sequence's printable tail ("[2J") visible, which is inert. */
28
+ export function stripControl(text: any): string;
29
+ /** The status for a decision word read from disk, or undefined for anything that is not one of the table's OWN
30
+ * entries ("constructor", "toString" and the rest of Object.prototype read as unrecognised). */
31
+ export function decisionStatus(decision: any): any;
25
32
  /**
26
33
  * @param {{ timeoutMs?: number, pollMs?: number, clock?: () => string, writeLine?: (line:string) => void }} [opts]
27
34
  * @returns {(opts:{question:string, evidence:unknown, runDir:string, ttlMs?: number}) => Promise<{decision:string, reason?:string}>}
@@ -73,9 +80,70 @@ export function serializeArtifact(artifact: unknown): string;
73
80
  * @returns {string}
74
81
  */
75
82
  export function sha256Hex(serialised: string): string;
83
+ /**
84
+ * M4c-fix amendment 1 (a): why a saved `answer.json` is not a usable answer for the open ask `openAskId`, or `null`
85
+ * when it is usable. The resume refuses each of these by name before it consumes the file, so without a way aside
86
+ * the file would block every new answer (`answerAsk`'s exclusive create).
87
+ * @param {string} text the file's text @param {string} openAskId
88
+ * @returns {string|null}
89
+ */
90
+ export function brokenAnswerWhy(text: string, openAskId: string): string | null;
91
+ /**
92
+ * Move `answer.json` aside as a record: `answer.<askId>.<kind>.<n>.json`, `n` the first free number. Write-once:
93
+ * the new name is created with a hard link (`EEXIST` = taken, try the next), then the old name is removed — never
94
+ * a rename, which would overwrite; never a delete of the content. A symlinked `answer.json` is refused, not followed.
95
+ * @param {string} runDir @param {string} askId @param {'broken'|'late'} kind
96
+ * @returns {{ ok: true, name: string } | { ok: false, red: string }}
97
+ */
98
+ export function setAsideAnswer(runDir: string, askId: string, kind: "broken" | "late"): {
99
+ ok: true;
100
+ name: string;
101
+ } | {
102
+ ok: false;
103
+ red: string;
104
+ };
105
+ /**
106
+ * The deadline an ask is judged against: the newest valid reopen record's `expiresAt`, else `original`.
107
+ * A record that is unreadable, names another ask, or holds no parseable `expiresAt` is ignored.
108
+ * @param {string} runDir @param {string} askId @param {string} original the ask's own `expiresAt`
109
+ * @returns {string}
110
+ */
111
+ export function effectiveExpiresAt(runDir: string, askId: string, original: string): string;
112
+ /**
113
+ * An `ask.json`-shaped object as every reader should see it: `expiresAt` is the effective deadline, and `waitMs`
114
+ * is the signed wait the ask was parked with (its own `expiresAt` minus `askedAt`, written from the signed ttl),
115
+ * which a reopen repeats. `waitMs` is `null` when either time cannot be read.
116
+ * @param {string} runDir @param {any} ask
117
+ * @returns {any}
118
+ */
119
+ export function withReopen(runDir: string, ask: any): any;
120
+ /**
121
+ * Reopen an expired ask: a fresh window of the same signed length, starting now, on the same ask (the same draft;
122
+ * nothing about the run changes). Human only — the caller names who (`by`); no runner, agent or resume path calls this.
123
+ * Refused, by name, when: there is no such open ask, its answer was already taken, it has not expired, or a saved
124
+ * answer made in time is waiting (that one is resumed, not reopened). A late or broken saved answer is moved aside
125
+ * as a record (`answer.<askId>.late.<n>.json`, never deleted). Two clicks race on the record's exclusive create:
126
+ * the loser is refused "already reopened", so a double click opens one window, not two.
127
+ * @param {{ runDir: string, askId: string, by: string, clock?: () => string }} opts
128
+ * @returns {{ ok: true, expiresAt: string, n: number, setAside: string|null } | { ok: false, red: string }}
129
+ */
130
+ export function reopenAsk({ runDir, askId, by, clock, }: {
131
+ runDir: string;
132
+ askId: string;
133
+ by: string;
134
+ clock?: () => string;
135
+ }): {
136
+ ok: true;
137
+ expiresAt: string;
138
+ n: number;
139
+ setAside: string | null;
140
+ } | {
141
+ ok: false;
142
+ red: string;
143
+ };
76
144
  /**
77
145
  * @param {{ runDir: string, askId: string, decision: 'accept'|'redo'|'reject'|'rerun', reason?: string, clock?: () => string }} opts
78
- * @returns {{ ok: true } | { ok: false, red: string }}
146
+ * @returns {{ ok: true, setAside: string|null } | { ok: false, red: string }}
79
147
  */
80
148
  export function answerAsk({ runDir, askId, decision: givenDecision, reason, clock, }: {
81
149
  runDir: string;
@@ -85,6 +153,7 @@ export function answerAsk({ runDir, askId, decision: givenDecision, reason, cloc
85
153
  clock?: () => string;
86
154
  }): {
87
155
  ok: true;
156
+ setAside: string | null;
88
157
  } | {
89
158
  ok: false;
90
159
  red: string;
@@ -24,7 +24,7 @@ export function sweepForSecrets(dir: any, secrets: any): number;
24
24
  /** Exact signed TTL with its unit, never rounded: 2h / 30m / 20s / 1500ms (the largest unit that divides it exactly). */
25
25
  export function fmtTtl(ms: any): string;
26
26
  /** Plain-text readout of what the human is about to sign. Pure. */
27
- export function buildReadout({ declaration, arbiter, lines, name, modelId, costUsd, rounds, spendComplete }: {
27
+ export function buildReadout({ declaration, arbiter, lines, name, modelId, costUsd, rounds, spendComplete, root, }: {
28
28
  declaration: any;
29
29
  arbiter: any;
30
30
  lines: any;
@@ -33,6 +33,7 @@ export function buildReadout({ declaration, arbiter, lines, name, modelId, costU
33
33
  costUsd: any;
34
34
  rounds: any;
35
35
  spendComplete: any;
36
+ root: any;
36
37
  }): string;
37
38
  /** Read the prose file. Refuses (a red, never a throw) on unreadable or blank. */
38
39
  export function readProseFile(file: any): {
@@ -98,7 +99,7 @@ export function draftToDir({ proseFile, dir, root, name, slot, model, budgetUsd,
98
99
  wrote: boolean;
99
100
  dir: any;
100
101
  hash: string | null;
101
- reds: string[];
102
+ reds: any;
102
103
  costUsd: number | null;
103
104
  spendComplete: boolean;
104
105
  stop: string | null;
@@ -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
+ };
@@ -48,11 +48,12 @@ export function writeLockHolder(fd: number): void;
48
48
  * unknown - liveness cannot be told (no /proc): never treated as dead
49
49
  * empty - a lock with no readable holder (pre-amendment resumer, torn write)
50
50
  * @param {string} runDir
51
- * @returns {{state: 'none'|'live'|'dead'|'unknown'|'empty', pid: number|null, path: string}}
51
+ * @returns {{state: 'none'|'live'|'dead'|'unknown'|'empty', pid: number|null, procStart: string|null, path: string}}
52
52
  */
53
53
  export function readResumeLock(runDir: string): {
54
54
  state: "none" | "live" | "dead" | "unknown" | "empty";
55
55
  pid: number | null;
56
+ procStart: string | null;
56
57
  path: string;
57
58
  };
58
59
  /**
@@ -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';