fwdloop 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +2 -0
  2. package/bin/fwdloop +8 -6
  3. package/package.json +1 -1
  4. package/src/authoring.js +6 -6
  5. package/src/catalogue.json +9 -3
  6. package/src/ctx-tools.js +245 -0
  7. package/src/draft-steps.js +89 -30
  8. package/src/drafter.js +28 -4
  9. package/src/draftspend.js +109 -3
  10. package/src/liveness.js +34 -10
  11. package/src/panel/author.js +101 -33
  12. package/src/panel/authorcard.js +13 -9
  13. package/src/panel/authorflows.js +3 -3
  14. package/src/panel/authorresume.js +5 -4
  15. package/src/panel/authorvalues.js +5 -3
  16. package/src/panel/data.js +17 -5
  17. package/src/panel/index.html +74 -42
  18. package/src/panel/server.js +10 -5
  19. package/src/panel/settings.js +2 -2
  20. package/src/plain-checks.js +51 -0
  21. package/src/primitives.js +34 -3
  22. package/src/provider.js +17 -8
  23. package/src/run-store.js +47 -0
  24. package/src/runner.js +2 -0
  25. package/src/setup.js +3 -0
  26. package/src/version.js +13 -0
  27. package/types/authoring.d.ts +1 -3
  28. package/types/ctx-tools.d.ts +18 -0
  29. package/types/draft-steps.d.ts +38 -5
  30. package/types/drafter.d.ts +3 -3
  31. package/types/draftspend.d.ts +56 -0
  32. package/types/liveness.d.ts +7 -1
  33. package/types/panel/author.d.ts +5 -5
  34. package/types/panel/authorcard.d.ts +12 -2
  35. package/types/panel/authorflows.d.ts +3 -3
  36. package/types/panel/authorvalues.d.ts +3 -1
  37. package/types/panel/server.d.ts +4 -2
  38. package/types/plain-checks.d.ts +22 -0
  39. package/types/primitives.d.ts +0 -6
  40. package/types/provider.d.ts +7 -1
  41. package/types/run-store.d.ts +11 -0
  42. package/types/setup.d.ts +8 -0
  43. package/types/version.d.ts +2 -0
package/src/provider.js CHANGED
@@ -21,6 +21,7 @@ import {
21
21
  import { dirname, basename } from 'node:path';
22
22
  import { readFileInside } from './flow.js';
23
23
  import { readConfig, configDoorHome } from './config.js';
24
+ import { isKeyName } from './keysfile.js';
24
25
  import { OpenAI, Anthropic, Gemini } from 'bare-agent/providers';
25
26
 
26
27
  /**
@@ -54,9 +55,11 @@ class MalformedToolCallTolerantOpenAI extends OpenAI {
54
55
  /** The API shape a row has until one is picked in Settings: the wire protocol most providers speak (a shape is a protocol, not a provider). */
55
56
  const DEFAULT_SHAPE = 'openai-api';
56
57
 
57
- /** A provider row is named by its key's env name (M4d amendment 6): letters, digits, underscore; not a place, not a model. */
58
- const KEY_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
59
- export const isKeyName = (v) => typeof v === 'string' && KEY_NAME_RE.test(v);
58
+ /** A provider row is named by its key's env name (M4d amendment 6). M4d am21 item 4: ONE rule for what that name may be, `isKeyName` in src/keysfile.js (`…_KEY` in
59
+ * capitals): the same gate the keys file, the env pass-through and the log scrubber use, so a key a run can use is always one the scrubber knows. */
60
+ export { isKeyName };
61
+ /** The sentence part every refusal of a non-key name carries, so the rule is named wherever it is refused. */
62
+ export const KEY_NAME_RULE_SAY = 'a key name is written in capitals and ends in _KEY';
60
63
 
61
64
  /**
62
65
  * THE one lookup of a row's API shape, address and legacy-token tick (M4d amendment 6). A row IS its key's env name, so the slot name and the
@@ -68,7 +71,7 @@ export const isKeyName = (v) => typeof v === 'string' && KEY_NAME_RE.test(v);
68
71
  * @returns {{ slot: string, envVar: string, legacyMaxTokens: boolean, shape: string, baseUrl: string }}
69
72
  */
70
73
  export function resolveSlot(slotName, { config = {} } = {}) {
71
- if (!isKeyName(slotName)) throw new Error(`unknown provider "${slotName}" — a provider is the name of a key in your keys file`);
74
+ if (!isKeyName(slotName)) throw new Error(`unknown provider "${slotName}" — a provider is the name of a key in your keys file; ${KEY_NAME_RULE_SAY}`);
72
75
  const saved = (config.providers && Object.hasOwn(config.providers, slotName)) ? config.providers[slotName] : {};
73
76
  const shape = saved.shape ?? DEFAULT_SHAPE;
74
77
  return {
@@ -284,7 +287,7 @@ export function appendSpendRow(path, row) {
284
287
  // (M4d: forward only — today's Settings price never re-prices an old row). A row that recorded no price at all (an
285
288
  // old row; the code table that once priced it is gone, M4d amendment 5) has no ceiling to add: 0 here, and the row
286
289
  // stays `complete: false`, so every total that holds it reads "at least", never as a clean figure.
287
- function rowCeilingUsd(row) {
290
+ export function rowCeilingUsd(row) {
288
291
  const p = row.price;
289
292
  if (p && typeof p === 'object' && Number.isFinite(p.inPerM) && p.inPerM > 0 && Number.isFinite(p.outPerM) && p.outPerM > 0) {
290
293
  return (CEILING_INPUT_TOKENS / 1e6) * p.inPerM + (CEILING_OUTPUT_TOKENS / 1e6) * p.outPerM;
@@ -292,6 +295,11 @@ function rowCeilingUsd(row) {
292
295
  return 0;
293
296
  }
294
297
 
298
+ /** How many calls of an incomplete row were never metered (at least one). @param {any} row */
299
+ export function unmeteredCalls(row) {
300
+ return Number.isInteger(row.calls) && Number.isInteger(row.rounds) ? Math.max(1, row.calls - row.rounds) : 1;
301
+ }
302
+
295
303
  /**
296
304
  * The one rule for what a spend row costs: `usd` and whether it is `complete`. An incomplete row (a call
297
305
  * died unmetered, or a round was left unpriced) counts its priced floor PLUS one ceiling per unmetered call
@@ -301,7 +309,7 @@ function rowCeilingUsd(row) {
301
309
  */
302
310
  export function spendRowCost(row) {
303
311
  if (row.spendComplete === false) {
304
- const unmetered = Number.isInteger(row.calls) && Number.isInteger(row.rounds) ? Math.max(1, row.calls - row.rounds) : 1;
312
+ const unmetered = unmeteredCalls(row);
305
313
  return { usd: (row.costUsd ?? 0) + unmetered * rowCeilingUsd(row), complete: false };
306
314
  }
307
315
  if (row.costUsd === null || row.costUsd === undefined) return { usd: rowCeilingUsd(row), complete: false };
@@ -359,7 +367,7 @@ export function assertUnderGlobalCap(path, capUsd) {
359
367
  * @param {Record<string,string|undefined>} [env]
360
368
  */
361
369
  export function checkKeyPreflight(slotName, env = process.env) {
362
- if (!isKeyName(slotName)) return { ok: false, message: `key: unknown provider "${slotName}"` };
370
+ if (!isKeyName(slotName)) return { ok: false, message: `key: unknown provider "${slotName}" — ${KEY_NAME_RULE_SAY}` };
363
371
  const varName = slotName;
364
372
  const value = env[varName];
365
373
  if (value === undefined || value === '') {
@@ -426,7 +434,8 @@ export function makeProvider(slotName, options = {}) {
426
434
  ...common,
427
435
  legacyMaxTokens: slot.legacyMaxTokens,
428
436
  // bare-agent >=0.48: opt in to the raw broken tool-call arguments on
429
- // `malformedToolCall` (capped upstream at 500 chars). Not exposeErrorBody.
437
+ // `malformedToolCall` (bare-agent >=0.50 hands over the full uncapped string; model-step.js
438
+ // bounds it, RAW_ARGS_BOUND). Not exposeErrorBody.
430
439
  exposeMalformedArgs: true,
431
440
  });
432
441
 
@@ -0,0 +1,47 @@
1
+ // M7 piece 2 (docs/wiki/the-module-ladder.md, "M7 scope — SIGNED", item 2): memory
2
+ // lasts one run only. Each run gets its own fresh litectx store and nothing carries
3
+ // into the next run.
4
+ //
5
+ // One function decides where a run's store lives (`runStoreDir`); everything else
6
+ // asks it. The store is a sibling of the run folder, under `<runs>/.stores/<runId>/`,
7
+ // so it is OUTSIDE the run dir and therefore outside every `readScope` the gate hands
8
+ // a step (read reaches the run dir and its frozen inputs' dirs, nothing above). A
9
+ // granted `read` cannot open the store's sqlite file as raw bytes. `.stores` is not a
10
+ // valid run id (a run id must start with a letter or digit), so run listings skip it.
11
+ //
12
+ // The store is opened per call and closed in `finally`: no handle outlives a tool
13
+ // call, so a restarted process (resume) finds the same run's store on disk and a
14
+ // different run never shares one.
15
+
16
+ import { rmSync } from 'node:fs';
17
+ import path from 'node:path';
18
+ import { createRequire } from 'node:module';
19
+
20
+ const require = createRequire(import.meta.url);
21
+ const { LiteCtx } = require('litectx');
22
+
23
+ /** The folder holding THIS run's store. A different run dir is a different folder.
24
+ * @param {string} runDir */
25
+ export function runStoreDir(runDir) {
26
+ const resolved = path.resolve(runDir);
27
+ return path.join(path.dirname(resolved), '.stores', path.basename(resolved));
28
+ }
29
+
30
+ /** Open this run's store, run `fn(lc)`, close it. `root` is the run dir: litectx indexes
31
+ * only its own extensions (.md .js .py ...) there, never the run's json/jsonl records.
32
+ * @template T @param {string} runDir @param {(lc: any) => Promise<T>|T} fn @returns {Promise<T>} */
33
+ export async function withRunStore(runDir, fn) {
34
+ const lc = new LiteCtx({ root: path.resolve(runDir), dbPath: path.join(runStoreDir(runDir), 'index.db') });
35
+ try {
36
+ return await fn(lc);
37
+ } finally {
38
+ lc.close();
39
+ }
40
+ }
41
+
42
+ /** A run STARTS with an empty store, never an inherited one: a run id can be reused (the next id is max+1, so deleting the last run
43
+ * folder hands its id to the next run) and the store sits beside the run folder, not in it. Called by the one place a fresh run
44
+ * begins (`runFlow`); resume and continue keep the run's own store. @param {string} runDir */
45
+ export function resetRunStore(runDir) {
46
+ rmSync(runStoreDir(runDir), { recursive: true, force: true });
47
+ }
package/src/runner.js CHANGED
@@ -44,6 +44,7 @@ import {
44
44
  basename, dirname, extname, isAbsolute, join, resolve, sep,
45
45
  } from 'node:path';
46
46
  import { parseCsv } from './csv.js';
47
+ import { resetRunStore } from './run-store.js';
47
48
  import { fileURLToPath } from 'node:url';
48
49
 
49
50
  import {
@@ -1060,6 +1061,7 @@ export async function runFlow({
1060
1061
  flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: fresh.red, spent: { value: 0 },
1061
1062
  });
1062
1063
  }
1064
+ resetRunStore(runDir); // M7: a fresh run never inherits a store left by an earlier run of the same id
1063
1065
  mkdirSync(runDir, { recursive: true });
1064
1066
 
1065
1067
  // M6: the run keeps a write-once copy of the job it runs, from before its first step (its Job tab shows this, not the flow's later versions)
package/src/setup.js CHANGED
@@ -8,6 +8,7 @@
8
8
  // carry `note` / `change` kinds; they are only ever READ back, from the flow's own setup.jsonl.
9
9
  // Third outcomes: a draft with no result is `stopped`; a cost nobody booked is `null` (shown "unknown", never $0).
10
10
  import { lstatSync, writeFileSync } from 'node:fs';
11
+ import { triesOf } from './draft-steps.js';
11
12
  import { join } from 'node:path';
12
13
 
13
14
  import { scrub } from './authoring.js';
@@ -52,6 +53,8 @@ function planRow(sessionDir, rel, kind, n) {
52
53
  // retries the drafter spent on structure (log.json); null = not recorded (a plan from before it), never 0
53
54
  structureRetries: Number.isInteger(log?.structureRetries) ? log.structureRetries : null,
54
55
  verdict, hash, gap,
56
+ // M4d am15: every try of this plan (label, passed, the checker's raw refusals, the round's words), for the Audit Draft group; only when a retry happened
57
+ ...(Array.isArray(log?.log) && log.log.length > 1 ? { tries: triesOf(log.log) } : {}),
55
58
  };
56
59
  }
57
60
 
package/src/version.js ADDED
@@ -0,0 +1,13 @@
1
+ // M4d amendment 17: fwdloop's own version, for the panel header. The ONE reader: the server calls it when it serves the page, so the number is always the one in
2
+ // the package.json of the code that is running (never typed into the page). An unreadable file is "unknown", never a made-up number.
3
+ import { readFileSync } from 'node:fs';
4
+
5
+ const OWN_PACKAGE = new URL('../package.json', import.meta.url);
6
+
7
+ /** @param {string|URL} [file] a package.json (a test passes a copy) @returns {string|null} */
8
+ export function readOwnVersion(file = OWN_PACKAGE) {
9
+ try {
10
+ const v = JSON.parse(readFileSync(file, 'utf8'))?.version;
11
+ return typeof v === 'string' && /^[0-9A-Za-z.+-]{1,40}$/.test(v) ? v : null;
12
+ } catch { return null; }
13
+ }
@@ -86,7 +86,7 @@ export function draftKeyRefusal(slot: string, env: Record<string, string | undef
86
86
  *
87
87
  * Test seam: `provider`/`rates`/`modelId` are injected; without them a live provider is built.
88
88
  */
89
- export function draftToDir({ proseFile, dir, root, name, slot, model, draftThinking, keyNames, budgetUsd, env, provider, rates, modelId, noQuestions, }: {
89
+ export function draftToDir({ proseFile, dir, root, name, slot, model, draftThinking, keyNames, env, provider, rates, modelId, noQuestions, }: {
90
90
  proseFile: any;
91
91
  dir: any;
92
92
  root: any;
@@ -95,7 +95,6 @@ export function draftToDir({ proseFile, dir, root, name, slot, model, draftThink
95
95
  model: any;
96
96
  draftThinking?: "on" | "off" | undefined;
97
97
  keyNames: any;
98
- budgetUsd?: number | undefined;
99
98
  env?: NodeJS.ProcessEnv | undefined;
100
99
  provider: any;
101
100
  rates: any;
@@ -183,7 +182,6 @@ export function signDraft({ dir, approve, signedBy, signedAt, env, keyNames, ses
183
182
  recorded: boolean;
184
183
  };
185
184
  };
186
- export const DRAFT_BUDGET_USD: 0.1;
187
185
  export const SPEC_HASH_FILE: "spec.hash";
188
186
  /** The one folder under the flows root where the panel keeps its draft folders (M4e). Starts with a dot, so it is never a flow name. */
189
187
  export const PANEL_DRAFTS_DIR: ".drafts";
@@ -0,0 +1,18 @@
1
+ /**
2
+ * @param {object} o
3
+ * @param {string} o.runDir
4
+ * @param {(verb: string, rawPath: unknown) => Promise<string>} o.gatePath - the read gate; resolves a model-given path to the absolute path it judged, or throws GateRefusal.
5
+ * @returns {Record<string, {name: string, description: string, parameters: object, execute: (args: any) => Promise<string>}>}
6
+ */
7
+ export function makeCtxTools({ runDir, gatePath }: {
8
+ runDir: string;
9
+ gatePath: (verb: string, rawPath: unknown) => Promise<string>;
10
+ }): Record<string, {
11
+ name: string;
12
+ description: string;
13
+ parameters: object;
14
+ execute: (args: any) => Promise<string>;
15
+ }>;
16
+ /** One stashed item holds at most this many bytes (measured after secrets are masked,
17
+ * because that is what enters the store). Bareloop's number, signed in M7 item 3. */
18
+ export const ISOLATE_MAX_BYTES: 65536;
@@ -1,14 +1,47 @@
1
1
  /**
2
- * @param {{ log: any, declaration: any }} p `log` = the draft's log.json (parsed), `declaration` = declaration.json or declaration.rejected.json (parsed)
3
- * @returns {Array<{ id: string, label: string, status: 'done'|'failed', details: string[], reds?: string[] }> | null}
2
+ * The tries of a draft, one per round, oldest first. The free retry after a broken reply (a `structure-retry` round) keeps the number of the try it
3
+ * retries: "try N again", never a new number. `reds` are the checker's raw refusals; `outcome` is a non-validator round's plain words, `rawOutcome` its own raw words.
4
+ * @param {any[]} rounds the draft's log.json `log`
5
+ * @returns {Array<{ label: string, passed: boolean, reds: string[], outcome: string, rawOutcome: string, again: boolean }>}
4
6
  */
5
- export function draftStepList({ log, declaration }: {
7
+ export function triesOf(rounds: any[]): Array<{
8
+ label: string;
9
+ passed: boolean;
10
+ reds: string[];
11
+ outcome: string;
12
+ rawOutcome: string;
13
+ again: boolean;
14
+ }>;
15
+ /**
16
+ * `questionOpen` (am15 item 3): the plan asked a question and the draft has NOT ended: its plan-checks line is not red and has no Fix ("red appears only on a draft that ended red").
17
+ * @param {{ log: any, declaration: any, questionOpen?: boolean }} p `log` = the draft's log.json (parsed), `declaration` = declaration.json or declaration.rejected.json (parsed)
18
+ * @returns {Array<{ id: string, label: string, status: 'done'|'failed'|'waiting', details: string[], note?: boolean }> | null}
19
+ */
20
+ export function draftStepList({ log, declaration, questionOpen }: {
6
21
  log: any;
7
22
  declaration: any;
23
+ questionOpen?: boolean;
24
+ }): Array<{
25
+ id: string;
26
+ label: string;
27
+ status: "done" | "failed" | "waiting";
28
+ details: string[];
29
+ note?: boolean;
30
+ }> | null;
31
+ /**
32
+ * M4d amendment 15, every line of the list: the line of ONE revise (or the redraft after answers), from that plan folder's own log.json. Same rules as `draftStepList`:
33
+ * one line, `<name> · <model> · <n rounds> · <cost>` and, for a plan that passed after refused tries, `fixed by the AI after N tries`; a red one carries one plain
34
+ * reason (and the Fix line under it), never details, folds or raw checker text. The try-by-try history is `triesOf` (the Audit Draft group). `null` = no log.
35
+ * @param {{ log: any, name: string }} p
36
+ * @returns {Array<{ id: string, label: string, status: 'done'|'failed'|'waiting', details: string[], note?: boolean }> | null}
37
+ */
38
+ export function reviseStepList({ log, name }: {
39
+ log: any;
40
+ name: string;
8
41
  }): Array<{
9
42
  id: string;
10
43
  label: string;
11
- status: "done" | "failed";
44
+ status: "done" | "failed" | "waiting";
12
45
  details: string[];
13
- reds?: string[];
46
+ note?: boolean;
14
47
  }> | null;
@@ -244,7 +244,7 @@ export function goalForLine(fromLine: any, lines: any): any;
244
244
  /**
245
245
  * Draft one declaration. `provider`/`rates`/`modelId` may be injected (tests,
246
246
  * the batch); otherwise a live provider is built from `slot` (throws on a bad
247
- * key — the batch preflights first). `budgetUsd` is this draft's hard cap.
247
+ * key — the batch preflights first). The draft's hard cap is the cap signed in the prose (M4d am13); `priorSpend(ceilingUsd)` (am16) is what this job's earlier drafting already spent, so every round must fit what is LEFT of the cap.
248
248
  * `makeProviderFn` is a test seam: the live-provider factory (default `makeProvider`).
249
249
  * `onBook` (M4e piece 2a, scope 13): called right BEFORE each provider call (`inFlight: true`, the call counted in
250
250
  * `calls`) and right AFTER it (`inFlight: false`), with what is known so far, so the caller can book spend per call
@@ -255,7 +255,7 @@ export function goalForLine(fromLine: any, lines: any): any;
255
255
  * costUsd:number|null, modelReturned:string|null, modelId?:string, price?:object|null, tokens?:object|null, structureRetries:number, revisions:number, stop:string|null, log:object[],
256
256
  * questions?:{line:number, question:string}[], droppedQuestions?:object[], notChecked?:string[], thinking?:{asked:string, status:string|null, say:string|null}, inputs?:{role:string, detail:string}[]}>}
257
257
  */
258
- export function draft({ proseText, slot, model, provider: injected, rates: injectedRates, modelId: injectedModelId, env, budgetUsd, skills, makeProviderFn, onBook, offerQuestions, draftThinking, }: {
258
+ export function draft({ proseText, slot, model, provider: injected, rates: injectedRates, modelId: injectedModelId, env, priorSpend, skills, makeProviderFn, onBook, offerQuestions, draftThinking, }: {
259
259
  proseText: any;
260
260
  slot: any;
261
261
  model: any;
@@ -263,7 +263,7 @@ export function draft({ proseText, slot, model, provider: injected, rates: injec
263
263
  rates: any;
264
264
  modelId: any;
265
265
  env: any;
266
- budgetUsd?: number | undefined;
266
+ priorSpend?: ((ceilingUsd: number) => number) | null | undefined;
267
267
  skills?: readonly string[] | undefined;
268
268
  makeProviderFn?: typeof makeProvider | undefined;
269
269
  onBook: any;
@@ -18,4 +18,60 @@ export function readDraftSpend(dir: string): Record<string, any> | null;
18
18
  * @returns {Record<string, any>[]}
19
19
  */
20
20
  export function readDirSpendRows(dir: string): Record<string, any>[];
21
+ /**
22
+ * M4d amendment 16 item 1: what ALL of a job's drafting spent — the one writer of that total. A panel draft's session folder holds one plan
23
+ * folder per draft (`draft/`, `draft-<n>/` for each revise and the redraft after answers); each is read by `readDirSpendRows` and priced by
24
+ * `spendRowCost`, the one cost rule. A round whose cost is not known counts at its WORST CASE (item 5): its own booked price's ceiling, else
25
+ * `ceilingUsd` (Settings prices x the fixed token limits), never $0; `notPriced` counts those rounds and `complete` is false.
26
+ * @param {string} sessionDir the panel's draft folder
27
+ * @param {{ ceilingUsd?: number, exclude?: string }} [o] `exclude` = a plan folder name to leave out (the one being written now)
28
+ * @returns {{ usd: number, notPriced: number, complete: boolean, missingEarlier: boolean }}
29
+ */
30
+ export function draftingSpent(sessionDir: string, { ceilingUsd, exclude }?: {
31
+ ceilingUsd?: number;
32
+ exclude?: string;
33
+ }, seen?: Set<any>): {
34
+ usd: number;
35
+ notPriced: number;
36
+ complete: boolean;
37
+ missingEarlier: boolean;
38
+ };
39
+ /**
40
+ * M4d amendment 16 items 1, 3, 5: the split of the card's Cap $ at Sign & run. `leftUsd` is what the first run may spend, rounded DOWN to 4 places (never
41
+ * more than is left). `line` is the sentence the page shows.
42
+ * @param {number} capUsd @param {{ usd: number, notPriced: number }} spent
43
+ */
44
+ export function potSplit(capUsd: number, spent: {
45
+ usd: number;
46
+ notPriced: number;
47
+ }): {
48
+ capUsd: number;
49
+ spentUsd: number;
50
+ notPriced: number;
51
+ leftUsd: number;
52
+ line: string;
53
+ };
54
+ /**
55
+ * The drafter's `priorSpend` for the plan folder `dir`: when it sits in a panel session folder (a `card.json` beside it), what the session's earlier plans spent;
56
+ * null for a plain CLI draft (no session, nothing earlier). The folder being written is left out.
57
+ * @param {string} dir @returns {((ceilingUsd: number) => number)|null}
58
+ */
59
+ export function sessionPriorSpend(dir: string): ((ceilingUsd: number) => number) | null;
60
+ /**
61
+ * M4d amendment 19 item 1: what a draft reserves against the monthly limit: what is LEFT of the cap in its prose (cap minus what this job's drafting already
62
+ * spent, `sessionPriorSpend`), not one round. A prose that does not parse falls back to one round: the draft itself refuses it at $0.
63
+ * @param {string} proseText @param {string} outDir the plan folder the draft will write @param {number} ceilingUsd one round at its worst case
64
+ */
65
+ export function draftHoldUsd(proseText: string, outDir: string, ceilingUsd: number): number;
66
+ /**
67
+ * M4d amendment 19 item 5 / amendment 20: the ONE sentence for a cap that cannot pay for one round. `kind` is "drafting" (the Chat card, the drafter) or "run"
68
+ * (Run a signed flow, Resume); nothing else differs. `modelId` is the model the minimum was computed for, `minUsd` its worst-case round.
69
+ * @param {'drafting'|'run'} kind @param {number} capUsd @param {number} minUsd @param {string} modelId
70
+ */
71
+ export function capTooSmallText(kind: "drafting" | "run", capUsd: number, minUsd: number, modelId: string): string;
21
72
  export const DRAFT_SPEND_FILE: "draft-spend.json";
73
+ /** M4d am21 item 2: the one sentence for a Start over (or revise, or sign) whose chain names an earlier draft that is gone. */
74
+ export const EARLIER_MISSING_SAY: "An earlier draft of this job is missing, so its spend can't be counted.";
75
+ /** The file a Start over's session folder carries to name the session it started over from (written once by src/panel/author.js). */
76
+ export const STARTED_OVER_FILE: "started-over-from.json";
77
+ export function usdText(n: number): string;
@@ -14,9 +14,10 @@ export function procStartOf(pid: number | "self"): string | null;
14
14
  * null - cannot tell (no /proc, or not ours to read): caller falls back to the 10-minute rule
15
15
  * @param {number} pid
16
16
  * @param {string|null} [procStart] the starttime recorded by the process itself; absent/null = not compared
17
+ * @param {typeof REAL_PROC} [proc] where /proc is read from (tests pass a snapshot)
17
18
  * @returns {boolean|null}
18
19
  */
19
- export function isFwdloopAlive(pid: number, procStart?: string | null): boolean | null;
20
+ export function isFwdloopAlive(pid: number, procStart?: string | null, proc?: typeof REAL_PROC): boolean | null;
20
21
  /**
21
22
  * The one writer call: this process records itself in the run dir's
22
23
  * `pids.jsonl`, before its first step.
@@ -68,3 +69,8 @@ export function readResumeLock(runDir: string): {
68
69
  export function booksFresh(runDir: string, nowMs?: number): boolean;
69
70
  /** The words the runner's refusal uses for a lock it cannot clear; the panel reads the same constant (M4c amendment 3 (e)). */
70
71
  export const LOCK_NO_HOLDER: "with no recorded holder";
72
+ declare namespace REAL_PROC {
73
+ function cmdline(pid: number): string;
74
+ function stat(pid: number): string;
75
+ }
76
+ export {};
@@ -54,7 +54,7 @@ export function createAuthor(opts: {
54
54
  jobLines: any;
55
55
  hasSend: boolean;
56
56
  capFloorUsd: number;
57
- floorText: string;
57
+ floorModel: string | null;
58
58
  model: {
59
59
  slot: string;
60
60
  model: string;
@@ -135,7 +135,7 @@ export function createAuthor(opts: {
135
135
  jobLines: any;
136
136
  hasSend: boolean;
137
137
  capFloorUsd: number;
138
- floorText: string;
138
+ floorModel: string | null;
139
139
  model: {
140
140
  slot: string;
141
141
  model: string;
@@ -194,14 +194,14 @@ export function createAuthor(opts: {
194
194
  /**
195
195
  * `GET /api/author/monthly-check?cap=<usd>`: the note under Cap, one read-only check. `{ text, red }` is what to show (red =
196
196
  * the cap does not fit this month); `floorUsd` is the smallest cap that funds one round of a model step, for the page's
197
- * `needs at least $X per run` line. A cap that is not a number above 0 gets no note. Never spends, never writes.
198
- * @param {unknown} cap @param {string|null} [spent] what a resumed run has already spent (amendment 4 item 4) @param {{ provider?: string, model?: string, flow?: string }|null} [pick] the card's picked model, or (a Resume) the flow whose recorded model it is: its own prices are the floor (M4d am6)
197
+ * floor line (am20: `Cap $X is below one drafting|run round's worst case for <model>, $Y. …`, `kind` picks the word). A cap that is not a number above 0 gets no note. Never spends, never writes.
198
+ * @param {unknown} cap @param {string|null} [spent] what a resumed run has already spent (amendment 4 item 4) @param {{ provider?: string, model?: string, flow?: string }|null} [pick] the card's picked model, or (a Run / Resume) the flow whose recorded model it @param {string} [kind] 'run' for Run a signed flow and Resume, else the Chat card's 'drafting' is: its own prices are the floor (M4d am6)
199
199
  */
200
200
  monthlyCheck(cap: unknown, spent?: string | null, pick?: {
201
201
  provider?: string;
202
202
  model?: string;
203
203
  flow?: string;
204
- } | null): {
204
+ } | null, kind?: string, draftId?: string | null): {
205
205
  status: number;
206
206
  body: {
207
207
  ok: boolean;
@@ -152,8 +152,18 @@ export function capFloorFor(hasRoundStep: boolean, home?: string, pick?: {
152
152
  provider?: string;
153
153
  model?: string;
154
154
  } | null): number;
155
- /** The one sentence for a cap under the floor (red under Cap, and the Draft / sign refusal). @param {number} floorUsd */
156
- export function capFloorText(floorUsd: number): string;
155
+ /** The floor and the model id it was computed for (M4d am20: the refusal sentence names it). `{ usd: 0, model: null }` when there is nothing to hold. @param {boolean} hasRoundStep @param {string} [home] @param {{ slot?: string, provider?: string, model?: string }|null} [pick] */
156
+ export function capFloorOf(hasRoundStep: boolean, home?: string, pick?: {
157
+ slot?: string;
158
+ provider?: string;
159
+ model?: string;
160
+ } | null): {
161
+ usd: number;
162
+ model: null;
163
+ } | {
164
+ usd: number;
165
+ model: string;
166
+ };
157
167
  /**
158
168
  * Amendment 1's destination checks, in ONE place: the New job card and the per-run destination of amendment 5 both ask it. `null` = fine,
159
169
  * else the sentence (a folder that is the run folder, a flow folder, the root, `.drafts`, `.starts`, the config folder, a file, a missing
@@ -16,7 +16,7 @@ export function formFacts(read: any, home?: string, flowDir?: string, picked?: {
16
16
  jobLines: any;
17
17
  hasSend: boolean;
18
18
  capFloorUsd: number;
19
- floorText: string;
19
+ floorModel: string | null;
20
20
  model: {
21
21
  slot: string;
22
22
  model: string;
@@ -82,7 +82,7 @@ export function createFlowsDoor(opts: {
82
82
  jobLines: any;
83
83
  hasSend: boolean;
84
84
  capFloorUsd: number;
85
- floorText: string;
85
+ floorModel: string | null;
86
86
  model: {
87
87
  slot: string;
88
88
  model: string;
@@ -169,7 +169,7 @@ export function createFlowsDoor(opts: {
169
169
  jobLines: any;
170
170
  hasSend: boolean;
171
171
  capFloorUsd: number;
172
- floorText: string;
172
+ floorModel: string | null;
173
173
  model: {
174
174
  slot: string;
175
175
  model: string;
@@ -11,6 +11,7 @@ export function leastResumeCapUsd(spentUsd: number, floorUsd: number): number;
11
11
  * @param {{capUsd: number, destination: string|null, askWaits: Record<string,string>}} a.base the values in force now (the flow's own, or the run's newest signed version)
12
12
  * @param {string} a.realRoot the flows root (real path)
13
13
  * @param {boolean} a.capOnly Resume: destination and waits are never read from the body
14
+ * @param {string|null} [a.floorModel] the model id the floor was computed for (named in the refusal, M4d am20)
14
15
  * @param {number} a.floorUsd the smallest cap that funds one round of a step (amendment 4 item 2); 0 = none
15
16
  * @param {number} [a.spentUsd] what the run has already spent (Resume): the cap must be above it
16
17
  * @param {boolean} [a.always] Resume: the floor and the monthly check always apply. A Run applies them only when its cap differs from the
@@ -18,7 +19,7 @@ export function leastResumeCapUsd(spentUsd: number, floorUsd: number): number;
18
19
  * @param {(remainingUsd: number) => null | { problem: string } | { ok: boolean, room: any }} a.monthlyClaim the one monthly check
19
20
  * @returns {{ ok: true, values: {capUsd: number, destination: string|null, askWaits: Record<string,string>}, differs: boolean, remainingUsd: number } | { ok: false, status: number, refusals: {field: string, say: string}[], refused?: string, say?: string }}
20
21
  */
21
- export function checkValues({ allowedKeys, body, base, realRoot, capOnly, floorUsd, spentUsd, monthlyClaim, always, }: {
22
+ export function checkValues({ allowedKeys, body, base, realRoot, capOnly, floorUsd, floorModel, spentUsd, monthlyClaim, always, }: {
22
23
  allowedKeys: string[];
23
24
  body: any;
24
25
  base: {
@@ -28,6 +29,7 @@ export function checkValues({ allowedKeys, body, base, realRoot, capOnly, floorU
28
29
  };
29
30
  realRoot: string;
30
31
  capOnly: boolean;
32
+ floorModel?: string | null | undefined;
31
33
  floorUsd: number;
32
34
  spentUsd?: number | undefined;
33
35
  always?: boolean | undefined;
@@ -4,11 +4,12 @@
4
4
  * real listening socket where that is simpler.
5
5
  * @param {import('node:http').IncomingMessage} req
6
6
  * @param {import('node:http').ServerResponse} res
7
- * @param {{ root: string, port: number, resumer: ReturnType<typeof createResumer>, settings: ReturnType<typeof createSettings>, author: ReturnType<typeof createAuthor> }} opts
7
+ * @param {{ root: string, port: number, packagePath?: string, resumer: ReturnType<typeof createResumer>, settings: ReturnType<typeof createSettings>, author: ReturnType<typeof createAuthor> }} opts
8
8
  */
9
9
  export function handleRequest(req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse, opts: {
10
10
  root: string;
11
11
  port: number;
12
+ packagePath?: string;
12
13
  resumer: ReturnType<typeof createResumer>;
13
14
  settings: ReturnType<typeof createSettings>;
14
15
  author: ReturnType<typeof createAuthor>;
@@ -19,13 +20,14 @@ export function handleRequest(req: import("node:http").IncomingMessage, res: imp
19
20
  * header). Resolves once actually listening; rejects on a bind error
20
21
  * (including `EADDRINUSE`) with a `.port` field on the error for the
21
22
  * caller's message.
22
- * @param {{ port?: number, root: string, settings?: { home?: string, env?: Record<string,string|undefined>, fetch?: typeof fetch, now?: () => number, openFolderSpawn?: Function, platform?: string }, resume?: { env?: Record<string,string|undefined>, bin?: string, logDir?: string, maxTries?: number, windowMs?: number, slotMs?: number }, author?: { env?: Record<string,string|undefined>, loadEnv?: () => any, bin?: string } }} opts
23
+ * @param {{ port?: number, root: string, packagePath?: string, settings?: { home?: string, env?: Record<string,string|undefined>, fetch?: typeof fetch, now?: () => number, openFolderSpawn?: Function, platform?: string }, resume?: { env?: Record<string,string|undefined>, bin?: string, logDir?: string, maxTries?: number, windowMs?: number, slotMs?: number }, author?: { env?: Record<string,string|undefined>, loadEnv?: () => any, bin?: string } }} opts
23
24
  * `resume` and `author` are for tests only (a fake env/bin, a short retry window); the CLI passes none.
24
25
  * @returns {Promise<{ server: import('node:http').Server, port: number, close: () => Promise<void> }>}
25
26
  */
26
27
  export function createPanelServer(opts: {
27
28
  port?: number;
28
29
  root: string;
30
+ packagePath?: string;
29
31
  settings?: {
30
32
  home?: string;
31
33
  env?: Record<string, string | undefined>;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * @param {unknown} raw one raw refusal text
3
+ * @returns {{ say: string, reason: string, fix: string, raw: string }}
4
+ */
5
+ export function plainPlanCheck(raw: unknown): {
6
+ say: string;
7
+ reason: string;
8
+ fix: string;
9
+ raw: string;
10
+ };
11
+ /** @type {ReadonlyArray<{re: RegExp, say: string|null, fix: string}>} `say` null = the checker's own sentence, as it is without its "declaration: " prefix */
12
+ export const PLAN_CHECK_RULES: ReadonlyArray<{
13
+ re: RegExp;
14
+ say: string | null;
15
+ fix: string;
16
+ }>;
17
+ export const GENERIC_SAY: "One of the checks on the plan failed.";
18
+ export const GENERIC_FIX: "Draft again.";
19
+ export function pageRules(): {
20
+ re: string;
21
+ say: string | null;
22
+ }[];
@@ -50,10 +50,4 @@ export class GateRefusal extends Error {
50
50
  path: any;
51
51
  rule: any;
52
52
  }
53
- /** The verbs this piece actually implements (the switch below, as data) —
54
- * one writer for "is this verb wired": `resolvePrimitives`'s own reds use
55
- * it, and `src/runner.js`'s preflight (F46: a step granted a
56
- * catalogue-present-but-unwired verb, e.g. litectx's `compress`, must
57
- * refuse before any model call or spend) imports this SAME set rather than
58
- * keeping a second copy of the list. */
59
53
  export const WIRED_VERBS: Set<string>;
@@ -164,6 +164,9 @@ export function sumMeterings(events: any): {
164
164
  /** Append one spend row, stamping `modelMatch` — the one writer for
165
165
  * spend.jsonl. Warns (never throws) on a `substituted` model. */
166
166
  export function appendSpendRow(path: any, row: any): void;
167
+ export function rowCeilingUsd(row: any): number;
168
+ /** How many calls of an incomplete row were never metered (at least one). @param {any} row */
169
+ export function unmeteredCalls(row: any): number;
167
170
  /**
168
171
  * The one rule for what a spend row costs: `usd` and whether it is `complete`. An incomplete row (a call
169
172
  * died unmetered, or a round was left unpriced) counts its priced floor PLUS one ceiling per unmetered call
@@ -243,9 +246,12 @@ export function makeProvider(slotName: string, options?: {
243
246
  source: any;
244
247
  };
245
248
  };
246
- export function isKeyName(v: any): boolean;
249
+ export { isKeyName };
250
+ /** The sentence part every refusal of a non-key name carries, so the rule is named wherever it is refused. */
251
+ export const KEY_NAME_RULE_SAY: "a key name is written in capitals and ends in _KEY";
247
252
  export const CEILING_INPUT_TOKENS: 32000;
248
253
  export const CEILING_OUTPUT_TOKENS: 16000;
249
254
  /** A model that is not usable (`resolveUsableModel`): its message is the plain sentence, shown as it is (no "key:" or "config:" prefix). */
250
255
  export class ModelRefusal extends Error {
251
256
  }
257
+ import { isKeyName } from './keysfile.js';
@@ -0,0 +1,11 @@
1
+ /** The folder holding THIS run's store. A different run dir is a different folder.
2
+ * @param {string} runDir */
3
+ export function runStoreDir(runDir: string): string;
4
+ /** Open this run's store, run `fn(lc)`, close it. `root` is the run dir: litectx indexes
5
+ * only its own extensions (.md .js .py ...) there, never the run's json/jsonl records.
6
+ * @template T @param {string} runDir @param {(lc: any) => Promise<T>|T} fn @returns {Promise<T>} */
7
+ export function withRunStore<T>(runDir: string, fn: (lc: any) => Promise<T> | T): Promise<T>;
8
+ /** A run STARTS with an empty store, never an inherited one: a run id can be reused (the next id is max+1, so deleting the last run
9
+ * folder hands its id to the next run) and the store sits beside the run folder, not in it. Called by the one place a fresh run
10
+ * begins (`runFlow`); resume and continue keep the run's own store. @param {string} runDir */
11
+ export function resetRunStore(runDir: string): void;
package/types/setup.d.ts CHANGED
@@ -11,6 +11,14 @@ export function buildSetupRows({ sessionDir, planDir, hash, signedBy, signedAt,
11
11
  signedAt: string;
12
12
  flowHash?: string;
13
13
  }): ({
14
+ tries?: {
15
+ label: string;
16
+ passed: boolean;
17
+ reds: string[];
18
+ outcome: string;
19
+ rawOutcome: string;
20
+ again: boolean;
21
+ }[] | undefined;
14
22
  kind: any;
15
23
  n: any;
16
24
  at: any;
@@ -0,0 +1,2 @@
1
+ /** @param {string|URL} [file] a package.json (a test passes a copy) @returns {string|null} */
2
+ export function readOwnVersion(file?: string | URL): string | null;