literally-aeo 0.1.1 → 0.2.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 (262) hide show
  1. package/README.md +42 -6
  2. package/dist/author-tools.js +33 -64
  3. package/dist/cli.mjs +2723 -1616
  4. package/dist/lib/agents/author-schema.js +4 -5
  5. package/dist/lib/agents/author-validation.js +5 -6
  6. package/dist/lib/agents/copy-validation.js +4 -5
  7. package/dist/lib/agents/verifier.js +8 -8
  8. package/dist/lib/analysis/domain-classifier.js +8 -8
  9. package/dist/lib/analysis/domain-labels.js +3 -4
  10. package/dist/lib/analysis/progress.js +3 -4
  11. package/dist/lib/analysis/sentiment.js +8 -8
  12. package/dist/lib/author/examples.js +5 -6
  13. package/dist/lib/bundle/contracts.js +5 -6
  14. package/dist/lib/bundle/export.js +22 -19
  15. package/dist/lib/bundle/isolation.js +17 -0
  16. package/dist/lib/bundle/journal.js +6 -7
  17. package/dist/lib/bundle/project-journal.js +11 -10
  18. package/dist/lib/bundle/project.js +19 -16
  19. package/dist/lib/bundle/read.js +23 -20
  20. package/dist/lib/bundle/recorder.js +9 -8
  21. package/dist/lib/bundle/redact.js +6 -7
  22. package/dist/lib/bundle/trace-coverage.js +6 -7
  23. package/dist/lib/bundle/verify-integrity.js +8 -9
  24. package/dist/lib/bundle/verify-measurement.js +10 -11
  25. package/dist/lib/bundle/verify-report.js +11 -12
  26. package/dist/lib/bundle/verify.js +17 -18
  27. package/dist/lib/bundle/writer-lock.js +3 -1
  28. package/dist/lib/capture-manifest.js +3 -4
  29. package/dist/lib/checks/run-checks.js +10 -9
  30. package/dist/lib/chunks/chunk-2B5QF6UQ.js +159 -0
  31. package/dist/lib/chunks/{chunk-ZBDUE3A5.js → chunk-2GU6CNQI.js} +12 -7
  32. package/dist/lib/chunks/{chunk-CKUTDJAB.js → chunk-2ROXN2EC.js} +42 -7
  33. package/dist/lib/chunks/{chunk-XHWRSGX3.js → chunk-3JO5TXBA.js} +1 -1
  34. package/dist/lib/chunks/{chunk-XL4JIQ5X.js → chunk-4PD65FRJ.js} +7 -3
  35. package/dist/lib/chunks/{chunk-GMKF2FU4.js → chunk-5JPYM4MD.js} +1 -1
  36. package/dist/lib/chunks/{chunk-5VNYUCLL.js → chunk-622NMXN6.js} +6 -9
  37. package/dist/lib/chunks/{chunk-XNRSHATN.js → chunk-663HABKP.js} +5 -5
  38. package/dist/lib/chunks/{chunk-RMFT4KKK.js → chunk-6G25V4CF.js} +1 -1
  39. package/dist/lib/chunks/{chunk-GVC4LH2N.js → chunk-6GHHNPFJ.js} +1 -1
  40. package/dist/lib/chunks/{chunk-KMRQSIZW.js → chunk-6GOBBNDU.js} +16 -1
  41. package/dist/lib/chunks/{chunk-SBAZBOPI.js → chunk-6P7EZJI7.js} +4 -2
  42. package/dist/lib/chunks/chunk-7XO3SQAX.js +117 -0
  43. package/dist/lib/chunks/{chunk-SWS3K62X.js → chunk-7Z27HQWL.js} +3 -3
  44. package/dist/lib/chunks/{chunk-IPNK7FYT.js → chunk-AYY4MYTW.js} +1 -1
  45. package/dist/lib/chunks/{chunk-WDSCJEDG.js → chunk-BE4ENGUY.js} +10 -10
  46. package/dist/lib/chunks/{chunk-FKLNEB2P.js → chunk-BGOIPHJZ.js} +39 -11
  47. package/dist/lib/chunks/{chunk-7GXRDAUY.js → chunk-BLKLPUYR.js} +2 -2
  48. package/dist/lib/chunks/chunk-BSRKN6FU.js +93 -0
  49. package/dist/lib/chunks/{chunk-PCYNBDZ7.js → chunk-CO5T6WU5.js} +14 -9
  50. package/dist/lib/chunks/{chunk-E3OEE5XN.js → chunk-CUYVHXHI.js} +2 -2
  51. package/dist/lib/chunks/{chunk-2GY42RIJ.js → chunk-D3GE3OCB.js} +1 -1
  52. package/dist/lib/chunks/chunk-DVFFYY5G.js +74 -0
  53. package/dist/lib/chunks/{chunk-ZXGATMMH.js → chunk-EBUQPCKB.js} +1 -1
  54. package/dist/lib/chunks/{chunk-4E4NDGOZ.js → chunk-EE26FNSY.js} +1 -1
  55. package/dist/lib/chunks/{chunk-AUB5THIS.js → chunk-EJ655TVU.js} +1 -1
  56. package/dist/lib/chunks/{chunk-S2AM76LT.js → chunk-F4W5YHDZ.js} +2 -2
  57. package/dist/lib/chunks/chunk-FAUFE7MI.js +31 -0
  58. package/dist/lib/chunks/{chunk-FNDJUELJ.js → chunk-FOCJ7HPC.js} +7 -7
  59. package/dist/lib/chunks/{chunk-FPAN3VRW.js → chunk-FUAUPNRO.js} +26 -18
  60. package/dist/lib/chunks/{chunk-OQVIRYT5.js → chunk-G62E525I.js} +2 -2
  61. package/dist/lib/chunks/{chunk-2NJEWPCV.js → chunk-GDKGZQ3T.js} +2 -2
  62. package/dist/lib/chunks/{chunk-HSZ3DM74.js → chunk-GEFKDW7X.js} +15 -2
  63. package/dist/lib/chunks/{chunk-47IZBMP2.js → chunk-GESHTTSA.js} +2 -2
  64. package/dist/lib/chunks/chunk-GNMFJ2OK.js +321 -0
  65. package/dist/lib/chunks/{chunk-NVBMIPXR.js → chunk-HFRAHG5C.js} +44 -26
  66. package/dist/lib/chunks/{chunk-MHAKYFDF.js → chunk-HQG63ZKO.js} +11 -11
  67. package/dist/lib/chunks/{chunk-OORO55OM.js → chunk-HTOD4W4E.js} +21 -6
  68. package/dist/lib/chunks/{chunk-Q2PWES4B.js → chunk-I3XGRGXE.js} +1 -1
  69. package/dist/lib/chunks/{chunk-WUELMJ22.js → chunk-IE7NAL6B.js} +1 -1
  70. package/dist/lib/chunks/{chunk-KRFHQQS7.js → chunk-JXMDOAKA.js} +17 -17
  71. package/dist/lib/chunks/{chunk-S7KJZIUR.js → chunk-KJMU5KH4.js} +2 -2
  72. package/dist/lib/chunks/{chunk-POUSX3T4.js → chunk-L7MEIRJB.js} +1 -1
  73. package/dist/lib/chunks/{chunk-CPT2GKKW.js → chunk-LOBXOZ2R.js} +1 -1
  74. package/dist/lib/chunks/{chunk-IAR6XGEW.js → chunk-ML4W6KC6.js} +1 -1
  75. package/dist/lib/chunks/{chunk-WKH6BJAZ.js → chunk-MNWO7EHC.js} +4 -4
  76. package/dist/lib/chunks/{chunk-D2LPQO6Y.js → chunk-MRL5RUP7.js} +1 -1
  77. package/dist/lib/chunks/{chunk-IEVAFDW7.js → chunk-NCXSNHXX.js} +3 -3
  78. package/dist/lib/chunks/{chunk-HFOYASRQ.js → chunk-NGHAP2P5.js} +4 -4
  79. package/dist/lib/chunks/{chunk-ZLOOC46D.js → chunk-OKL7GN2F.js} +3 -3
  80. package/dist/lib/chunks/{chunk-3DG7GHFA.js → chunk-OQU5IXAJ.js} +5 -5
  81. package/dist/lib/chunks/{chunk-I7VNIW6Q.js → chunk-OU73OUX4.js} +16 -10
  82. package/dist/lib/chunks/{chunk-56VOFZ7T.js → chunk-QHUDJVPJ.js} +90 -24
  83. package/dist/lib/chunks/{chunk-KHU5DRBE.js → chunk-QSJ4IKUF.js} +9 -9
  84. package/dist/lib/chunks/{chunk-FBFZBLTY.js → chunk-R6XDZWUL.js} +7 -8
  85. package/dist/lib/chunks/{chunk-CJ5YD3CU.js → chunk-RJ5R6YYA.js} +5 -5
  86. package/dist/lib/chunks/{chunk-LPND3VNQ.js → chunk-RR46EDDR.js} +33 -25
  87. package/dist/lib/chunks/chunk-RYCRL3YA.js +106 -0
  88. package/dist/lib/chunks/{chunk-Z4LMDKBU.js → chunk-SHUMCKCS.js} +2 -2
  89. package/dist/lib/chunks/{chunk-3EBWDHPK.js → chunk-TJQ5OPLQ.js} +10 -12
  90. package/dist/lib/chunks/chunk-U64NCRRR.js +97 -0
  91. package/dist/lib/chunks/chunk-U772TN32.js +67 -0
  92. package/dist/lib/chunks/{chunk-YR67JG2V.js → chunk-UEMZYHYJ.js} +8 -3
  93. package/dist/lib/chunks/{chunk-J46W3EMQ.js → chunk-UZJSTJFP.js} +5 -5
  94. package/dist/lib/chunks/{chunk-XJVXASDD.js → chunk-V7OAPKNF.js} +3 -3
  95. package/dist/lib/chunks/{chunk-WE2WPNG2.js → chunk-VKM6MMA4.js} +66 -7
  96. package/dist/lib/chunks/{chunk-YWJPJI3W.js → chunk-VL253W5C.js} +3 -1
  97. package/dist/lib/chunks/{chunk-MD4AVTK2.js → chunk-VPZQGND4.js} +3 -3
  98. package/dist/lib/chunks/{chunk-X2Y2ZNG3.js → chunk-W2VGLWTS.js} +3 -3
  99. package/dist/lib/chunks/{chunk-6AUEDSTU.js → chunk-W5DC23OP.js} +1 -1
  100. package/dist/lib/chunks/chunk-W5X7WJYL.js +91 -0
  101. package/dist/lib/chunks/{chunk-QFVRCSJ2.js → chunk-WDOA5JEH.js} +2 -0
  102. package/dist/lib/chunks/{chunk-I3TMFPK4.js → chunk-WVACVWBL.js} +2 -2
  103. package/dist/lib/chunks/{chunk-MIF5IYNR.js → chunk-XDG6NPJB.js} +26 -29
  104. package/dist/lib/chunks/{chunk-X6E44EGV.js → chunk-XR44YSHT.js} +2 -2
  105. package/dist/lib/chunks/chunk-Y2CZ6FZY.js +61 -0
  106. package/dist/lib/chunks/{chunk-5KKLUM7M.js → chunk-YAAUWCJ4.js} +1 -1
  107. package/dist/lib/chunks/{chunk-3KQFLOC7.js → chunk-YRBIC5QH.js} +1 -1
  108. package/dist/lib/chunks/chunk-ZIGNJAPC.js +11 -0
  109. package/dist/lib/cli/bundle-commands.js +71 -65
  110. package/dist/lib/cli/guide-command.js +25 -0
  111. package/dist/lib/cli/io.js +1 -1
  112. package/dist/lib/cli/run-commands.js +270 -104
  113. package/dist/lib/cli/status-command.js +234 -0
  114. package/dist/lib/codex-workflow/aggregate.js +8 -9
  115. package/dist/lib/codex-workflow/author-tools.js +6 -7
  116. package/dist/lib/codex-workflow/author.js +17 -17
  117. package/dist/lib/codex-workflow/capture.js +10 -9
  118. package/dist/lib/codex-workflow/checkpoint.js +6 -7
  119. package/dist/lib/codex-workflow/checks.js +6 -7
  120. package/dist/lib/codex-workflow/codex-binary.js +13 -0
  121. package/dist/lib/codex-workflow/codex-home.js +6 -3
  122. package/dist/lib/codex-workflow/copy-editor.js +14 -14
  123. package/dist/lib/codex-workflow/copy-recovery.js +3 -4
  124. package/dist/lib/codex-workflow/copy.js +11 -11
  125. package/dist/lib/codex-workflow/finish.js +17 -18
  126. package/dist/lib/codex-workflow/host-models.js +7 -7
  127. package/dist/lib/codex-workflow/loop.js +42 -38
  128. package/dist/lib/codex-workflow/quality.js +3 -4
  129. package/dist/lib/codex-workflow/run-inputs.js +5 -6
  130. package/dist/lib/codex-workflow/run-source.js +14 -13
  131. package/dist/lib/codex-workflow/schemas.js +5 -6
  132. package/dist/lib/codex-workflow/session.js +7 -8
  133. package/dist/lib/codex-workflow/stage.js +26 -23
  134. package/dist/lib/codex-workflow/workdir.js +6 -7
  135. package/dist/lib/engine/audit-file.js +7 -6
  136. package/dist/lib/engine/author.js +37 -31
  137. package/dist/lib/engine/budget.js +7 -1
  138. package/dist/lib/engine/cost-estimate.js +41 -0
  139. package/dist/lib/engine/local-run.js +48 -42
  140. package/dist/lib/engine/preflight.js +10 -6
  141. package/dist/lib/engine/rejudge.js +56 -50
  142. package/dist/lib/engine/resources.js +1 -1
  143. package/dist/lib/engine/run-configuration.js +2 -1
  144. package/dist/lib/engine/run-status.js +151 -0
  145. package/dist/lib/engine/templates.js +8 -7
  146. package/dist/lib/grounding/controller.js +7 -7
  147. package/dist/lib/grounding/extract.js +6 -6
  148. package/dist/lib/grounding/grounding-runtime.js +18 -17
  149. package/dist/lib/grounding/model.js +5 -5
  150. package/dist/lib/grounding/recorded-tools.js +10 -9
  151. package/dist/lib/harness/report/artifacts.js +4 -5
  152. package/dist/lib/lib/checkpoint.js +3 -4
  153. package/dist/lib/models/batching.js +5 -5
  154. package/dist/lib/models/cost-coefficients.js +20 -0
  155. package/dist/lib/models/local-profile.js +10 -0
  156. package/dist/lib/models/pricing.js +6 -0
  157. package/dist/lib/models/profiles.js +7 -14
  158. package/dist/lib/models/structured-images.js +1 -1
  159. package/dist/lib/models/structured.js +4 -4
  160. package/dist/lib/models/supported-models.js +20 -0
  161. package/dist/lib/pipeline.js +9 -8
  162. package/dist/lib/probes/agent-cli-parsers.js +1 -1
  163. package/dist/lib/probes/agent-clis.js +6 -5
  164. package/dist/lib/probes/charged-trace.js +10 -0
  165. package/dist/lib/probes/probes.js +6 -6
  166. package/dist/lib/runner.js +10 -10
  167. package/dist/lib/schema.js +3 -4
  168. package/dist/lib/section-result.js +3 -4
  169. package/dist/lib/stores/artifacts.js +3 -4
  170. package/dist/lib/stores/files.js +9 -9
  171. package/dist/lib/stores/local-versions.js +4 -5
  172. package/dist/lib/stores/memory.js +6 -7
  173. package/dist/lib/stores/publication.js +5 -6
  174. package/dist/lib/viewer/server.js +18 -19
  175. package/dist/lib/workflow/schema.js +2 -3
  176. package/dist/types/agents/copy-validation.d.ts +4 -4
  177. package/dist/types/agents/verifier.d.ts +6 -6
  178. package/dist/types/bundle/contracts.d.ts +1 -1
  179. package/dist/types/bundle/isolation.d.ts +37 -0
  180. package/dist/types/bundle/project-journal.d.ts +2 -0
  181. package/dist/types/bundle/recorder.d.ts +4 -0
  182. package/dist/types/bundle/writer-lock.d.ts +9 -0
  183. package/dist/types/cli/guide-command.d.ts +4 -0
  184. package/dist/types/cli/status-command.d.ts +2 -0
  185. package/dist/types/codex-workflow/codex-binary.d.ts +26 -0
  186. package/dist/types/codex-workflow/codex-home.d.ts +24 -20
  187. package/dist/types/codex-workflow/copy-editor.d.ts +1 -1
  188. package/dist/types/codex-workflow/copy.d.ts +3 -4
  189. package/dist/types/codex-workflow/finish.d.ts +5 -3
  190. package/dist/types/codex-workflow/host-models.d.ts +7 -3
  191. package/dist/types/codex-workflow/loop.d.ts +10 -1
  192. package/dist/types/codex-workflow/run-inputs.d.ts +28 -113
  193. package/dist/types/codex-workflow/stage.d.ts +16 -5
  194. package/dist/types/engine/audit-file.d.ts +3 -2
  195. package/dist/types/engine/author.d.ts +7 -1
  196. package/dist/types/engine/budget.d.ts +46 -15
  197. package/dist/types/engine/cost-estimate.d.ts +40 -0
  198. package/dist/types/engine/local-run.d.ts +6 -0
  199. package/dist/types/engine/preflight.d.ts +5 -0
  200. package/dist/types/engine/resources.d.ts +2 -0
  201. package/dist/types/engine/run-configuration.d.ts +4 -3
  202. package/dist/types/engine/run-status.d.ts +75 -0
  203. package/dist/types/engine/templates.d.ts +1 -2
  204. package/dist/types/models/cost-coefficients.d.ts +106 -0
  205. package/dist/types/models/local-profile.d.ts +12 -0
  206. package/dist/types/models/pricing.d.ts +8 -0
  207. package/dist/types/models/profiles.d.ts +55 -160
  208. package/dist/types/models/served-model.d.ts +2 -3
  209. package/dist/types/models/structured.d.ts +3 -3
  210. package/dist/types/models/supported-models.d.ts +48 -0
  211. package/dist/types/probes/charged-trace.d.ts +8 -0
  212. package/dist/types/probes/probe-trace.d.ts +2 -0
  213. package/dist/types/schema.d.ts +28 -113
  214. package/dist/types/workflow/schema.d.ts +79 -152
  215. package/package.json +2 -1
  216. package/resources/guide/OPERATOR.md +180 -0
  217. package/src/agents/copy-validation.ts +8 -12
  218. package/src/agents/verifier.ts +10 -14
  219. package/src/bundle/contracts.ts +3 -3
  220. package/src/bundle/isolation.ts +157 -0
  221. package/src/bundle/project-journal.ts +4 -0
  222. package/src/bundle/project.ts +20 -7
  223. package/src/bundle/recorder.ts +5 -0
  224. package/src/bundle/writer-lock.ts +27 -0
  225. package/src/cli/guide-command.ts +28 -0
  226. package/src/cli/io.ts +2 -0
  227. package/src/cli/literally-aeo.ts +39 -19
  228. package/src/cli/run-commands.ts +236 -18
  229. package/src/cli/status-command.ts +113 -0
  230. package/src/codex-workflow/codex-binary.ts +105 -0
  231. package/src/codex-workflow/codex-home.ts +50 -40
  232. package/src/codex-workflow/copy.ts +7 -10
  233. package/src/codex-workflow/finish.ts +13 -8
  234. package/src/codex-workflow/host-models.ts +33 -24
  235. package/src/codex-workflow/loop.ts +36 -9
  236. package/src/codex-workflow/stage.ts +126 -17
  237. package/src/engine/audit-file.ts +10 -8
  238. package/src/engine/author.ts +47 -2
  239. package/src/engine/budget.ts +138 -43
  240. package/src/engine/cost-estimate.ts +178 -0
  241. package/src/engine/guide/OPERATOR.md +180 -0
  242. package/src/engine/local-run.ts +38 -8
  243. package/src/engine/preflight.ts +90 -7
  244. package/src/engine/resources.ts +9 -4
  245. package/src/engine/run-configuration.ts +19 -1
  246. package/src/engine/run-status.ts +452 -0
  247. package/src/engine/templates.ts +5 -2
  248. package/src/models/cost-coefficients.ts +140 -0
  249. package/src/models/local-profile.ts +150 -0
  250. package/src/models/pricing.ts +31 -0
  251. package/src/models/profiles.ts +58 -419
  252. package/src/models/served-model.ts +2 -3
  253. package/src/models/structured-images.ts +5 -4
  254. package/src/models/structured.ts +20 -7
  255. package/src/models/supported-models.ts +112 -0
  256. package/src/probes/agent-clis.ts +24 -2
  257. package/src/probes/charged-trace.ts +87 -0
  258. package/src/probes/probe-trace.ts +2 -0
  259. package/src/probes/probes.ts +48 -2
  260. package/dist/lib/chunks/chunk-CFFPOTP4.js +0 -356
  261. package/dist/lib/chunks/chunk-LIZX4N3H.js +0 -110
  262. package/dist/lib/chunks/chunk-OYKV5NDM.js +0 -28
@@ -1,6 +1,6 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { createWriteStream } from 'node:fs';
3
- import { createHash } from 'node:crypto';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
4
  import {
5
5
  appendFile,
6
6
  mkdir,
@@ -20,6 +20,13 @@ import { isAuthError } from '../probes/failure';
20
20
  import { isObject } from '../lib/type-guards';
21
21
  import { getEnvironment, readEnv } from '../lib/env';
22
22
  import type { ExecutionRecorder } from '../bundle/recorder';
23
+ import type { ModelCallAccounting } from '../models/accounting';
24
+ import {
25
+ sessionReservation,
26
+ type SessionCost,
27
+ } from '../models/cost-coefficients';
28
+ import { tokenCostUsd } from '../models/pricing';
29
+ import type { CodexStageModel } from '../models/profiles';
23
30
  import {
24
31
  mergeBatches,
25
32
  restoreQualificationQuotes,
@@ -27,8 +34,10 @@ import {
27
34
  type CheckScope,
28
35
  type StageValue,
29
36
  } from './checks';
37
+ import { codexArgs, codexBinaryAt, resolveCodexBinary } from './codex-binary';
30
38
  import {
31
- codexModel,
39
+ codexGateway,
40
+ codexStageConfig,
32
41
  prepareCodexHome,
33
42
  type ResearchServerConfig,
34
43
  } from './codex-home';
@@ -74,6 +83,13 @@ import { batchInput } from './batch-input';
74
83
  // prompts.ts.
75
84
  // ============================================================================
76
85
 
86
+ /** Tokens a Codex session reported: cached input is part of input. */
87
+ export type SessionUsage = {
88
+ inputTokens: number;
89
+ cachedInputTokens: number;
90
+ outputTokens: number;
91
+ };
92
+
77
93
  export type StageRun = {
78
94
  stage: StageName;
79
95
  model: string;
@@ -81,7 +97,7 @@ export type StageRun = {
81
97
  * `degraded` and their answers carry no judgment from this stage. */
82
98
  ok: boolean;
83
99
  durationMs: number;
84
- usage: { inputTokens: number; outputTokens: number } | null;
100
+ usage: SessionUsage | null;
85
101
  errors: string[];
86
102
  /** Answer files whose batch never validated: excluded from this stage
87
103
  * and every later one, recorded, never a reason to stop the run. */
@@ -107,7 +123,13 @@ export type StageContext = {
107
123
  ownedDomains?: readonly string[];
108
124
  /** The host stopping the work: sessions are killed and no batch starts. */
109
125
  signal?: AbortSignal;
110
- /** Overrides for tests: the command to run instead of `codex`. */
126
+ /** The model every session runs on (the run's pinned stage model). */
127
+ stageModel: CodexStageModel;
128
+ /** The run's ledger: every session is reserved before it starts and
129
+ * settled from its reported tokens. Absent, sessions are not charged. */
130
+ accounting?: ModelCallAccounting;
131
+ /** Overrides for tests: the command to run instead of the engine's own
132
+ * Codex. */
111
133
  command?: string;
112
134
  timeoutMs?: number;
113
135
  /** Answers per Codex session; the default fits the pinned model. */
@@ -186,6 +208,9 @@ export type Batch = {
186
208
  type StageSpec = {
187
209
  /** Partitioned by answer file, or one session over the whole report. */
188
210
  batched: boolean;
211
+ /** The calibrated workload a session is reserved at on the run's ledger
212
+ * (src/models/cost-coefficients.ts). */
213
+ sessionCost: SessionCost;
189
214
  /** Judged against the batch's own files, or every answer (the copy must
190
215
  * name every configured section). */
191
216
  judgedOn: 'batch' | 'all';
@@ -298,6 +323,7 @@ const stageSpecs: Record<StageName, StageSpec> = {
298
323
  analyze: {
299
324
  ...reportStage,
300
325
  batched: true,
326
+ sessionCost: 'answers',
301
327
  judgedOn: 'batch',
302
328
  persistent: false,
303
329
  sharedInputs: fixedInputs([
@@ -319,6 +345,7 @@ const stageSpecs: Record<StageName, StageSpec> = {
319
345
  qualify: {
320
346
  ...reportStage,
321
347
  batched: true,
348
+ sessionCost: 'answers',
322
349
  judgedOn: 'batch',
323
350
  persistent: false,
324
351
  sharedInputs: fixedInputs([
@@ -344,6 +371,7 @@ const stageSpecs: Record<StageName, StageSpec> = {
344
371
  review: {
345
372
  ...reportStage,
346
373
  batched: true,
374
+ sessionCost: 'answers',
347
375
  judgedOn: 'batch',
348
376
  persistent: true,
349
377
  sharedInputs: fixedInputs([
@@ -373,6 +401,7 @@ const stageSpecs: Record<StageName, StageSpec> = {
373
401
  write: {
374
402
  ...reportStage,
375
403
  batched: false,
404
+ sessionCost: 'report',
376
405
  judgedOn: 'all',
377
406
  persistent: true,
378
407
  // Everything under COPY/, listed at digest time.
@@ -406,6 +435,7 @@ const stageSpecs: Record<StageName, StageSpec> = {
406
435
  // read-only sandbox, judged by the host's verdict after it submits.
407
436
  author: {
408
437
  batched: false,
438
+ sessionCost: 'brief',
409
439
  judgedOn: 'all',
410
440
  persistent: true,
411
441
  sharedInputs: authorFiles,
@@ -435,6 +465,10 @@ const sumUsage = (usages: readonly StageRun['usage'][]): StageRun['usage'] => {
435
465
  (total, usage) => total + usage.inputTokens,
436
466
  0,
437
467
  ),
468
+ cachedInputTokens: reported.reduce(
469
+ (total, usage) => total + usage.cachedInputTokens,
470
+ 0,
471
+ ),
438
472
  outputTokens: reported.reduce(
439
473
  (total, usage) => total + usage.outputTokens,
440
474
  0,
@@ -514,7 +548,7 @@ const batchInputsDigest = async (
514
548
  ): Promise<string> => {
515
549
  const spec = stageSpecs[stage];
516
550
  const parts: Record<string, string> = {
517
- model: JSON.stringify(codexModel),
551
+ model: JSON.stringify(codexStageConfig(ctx.stageModel)),
518
552
  prompt: stagePrompts[stage],
519
553
  version: String(stageVersions[stage]),
520
554
  schema: JSON.stringify(stageJsonSchema(stage)),
@@ -596,7 +630,11 @@ const sessionSandbox = (spec: StageSpec) => {
596
630
  const eventText = z.string().optional().catch(undefined);
597
631
  const eventTokens = z.number().optional().catch(undefined);
598
632
  const eventUsage = z
599
- .looseObject({ input_tokens: eventTokens, output_tokens: eventTokens })
633
+ .looseObject({
634
+ input_tokens: eventTokens,
635
+ cached_input_tokens: eventTokens,
636
+ output_tokens: eventTokens,
637
+ })
600
638
  .optional()
601
639
  .catch(undefined);
602
640
 
@@ -666,6 +704,64 @@ type SessionTarget = {
666
704
  attempt?: number;
667
705
  };
668
706
 
707
+ type SessionCharge = {
708
+ settle: (usage: SessionUsage | null) => Promise<void>;
709
+ };
710
+
711
+ /** reserveSession charges one session to the run's ledger before it starts,
712
+ * at the high estimate for its stage's workload, and returns how to settle
713
+ * it from the tokens it reports at the stage model's list prices. A session
714
+ * that reports nothing is settled without a cost, so it keeps charging its
715
+ * reservation: nothing is recorded that Codex did not report. */
716
+ const reserveSession = async (
717
+ ctx: StageContext,
718
+ { stage, batch, attempt }: Pick<SessionTarget, 'stage' | 'batch' | 'attempt'>,
719
+ ): Promise<SessionCharge | undefined> => {
720
+ const { accounting, stageModel } = ctx;
721
+
722
+ if (!accounting) {
723
+ return undefined;
724
+ }
725
+
726
+ const pricing = stageModel.pricingUsdPerMillion;
727
+ const reserved = sessionReservation({
728
+ cost: stageSpecs[stage].sessionCost,
729
+ answers: batch.files.length,
730
+ });
731
+ // Unique per session: a resumed run never settles a session it lost
732
+ // under the old one's reservation.
733
+ const callId = `codex:${stage}-${batch.index}:${attempt ?? 1}:${randomUUID()}`;
734
+
735
+ await accounting.reserve({
736
+ callId,
737
+ role: `stage:${stage}`,
738
+ requestedModel: stageModel.model,
739
+ reasoningEffort: stageModel.reasoningEffort,
740
+ reservedUsd: tokenCostUsd(pricing, reserved),
741
+ inputTokens: reserved.inputTokens,
742
+ maxOutputTokens: reserved.outputTokens,
743
+ });
744
+
745
+ const charge: SessionCharge = {
746
+ settle: async (usage) => {
747
+ await accounting.settle(
748
+ callId,
749
+ usage
750
+ ? {
751
+ requestedModel: stageModel.model,
752
+ costUsd: tokenCostUsd(pricing, usage),
753
+ inputTokens: usage.inputTokens,
754
+ cachedInputTokens: usage.cachedInputTokens,
755
+ outputTokens: usage.outputTokens,
756
+ }
757
+ : { requestedModel: stageModel.model, valid: false },
758
+ );
759
+ },
760
+ };
761
+
762
+ return charge;
763
+ };
764
+
669
765
  /** Run `codex exec` for one session of a batch: a fresh conversation, or
670
766
  * the batch's saved one when the stage keeps it and the contract (what the
671
767
  * conversation has read) is unchanged. */
@@ -702,7 +798,7 @@ const execCodex = async (
702
798
  const contract = sha({
703
799
  stage,
704
800
  version: stageVersions[stage],
705
- model: codexModel,
801
+ model: codexStageConfig(ctx.stageModel),
706
802
  prompt: stagePrompts[stage],
707
803
  continuation: sessionPrompt(stage, batch.index, { continuation: true }),
708
804
  schema: stageJsonSchema(stage),
@@ -749,9 +845,16 @@ const execCodex = async (
749
845
  ];
750
846
 
751
847
  let threadId: string | null = session?.threadId ?? null;
848
+ const codexBinary = ctx.command
849
+ ? codexBinaryAt(ctx.command)
850
+ : resolveCodexBinary();
752
851
 
753
852
  ctx.signal?.throwIfAborted();
754
853
 
854
+ // Reserved before the child starts: a session the cap cannot afford is
855
+ // never started, and the run stops resumable at its budget.
856
+ const charge = await reserveSession(ctx, { stage, batch, attempt });
857
+
755
858
  // Recorded before the child starts: a session the host loses track of
756
859
  // stays an open operation, an unknown outcome, never a silent success.
757
860
  const operation = await ctx.recorder?.start({
@@ -765,9 +868,10 @@ const execCodex = async (
765
868
  arguments: JSON.stringify(args),
766
869
  },
767
870
  details: {
768
- requestedModel: codexModel.model,
769
- provider: codexModel.providerName,
770
- reasoningEffort: codexModel.reasoningEffort,
871
+ requestedModel: ctx.stageModel.model,
872
+ provider: codexGateway.providerName,
873
+ reasoningEffort: ctx.stageModel.reasoningEffort,
874
+ codex: { source: codexBinary.source, version: codexBinary.version },
771
875
  sandbox: sessionSandbox(spec),
772
876
  resumedThreadId: session?.threadId ?? null,
773
877
  },
@@ -782,7 +886,7 @@ const execCodex = async (
782
886
  }>((resolve) => {
783
887
  // Codex appends piped input to the instruction as context. End the pipe
784
888
  // immediately after the complete packet; an open stdin waits forever.
785
- const child = spawn(ctx.command ?? 'codex', args, {
889
+ const child = spawn(codexBinary.command, codexArgs(codexBinary, args), {
786
890
  cwd: ctx.dir,
787
891
  env,
788
892
  detached: true,
@@ -838,6 +942,7 @@ const execCodex = async (
838
942
  if (found) {
839
943
  usage = {
840
944
  inputTokens: found.input_tokens ?? 0,
945
+ cachedInputTokens: found.cached_input_tokens ?? 0,
841
946
  outputTokens: found.output_tokens ?? 0,
842
947
  };
843
948
  }
@@ -891,6 +996,8 @@ const execCodex = async (
891
996
  },
892
997
  });
893
998
 
999
+ await charge?.settle(result.usage);
1000
+
894
1001
  if (spec.persistent && threadId) {
895
1002
  const files = await saveSession(ctx.dir, label, { contract, threadId });
896
1003
 
@@ -2200,11 +2307,13 @@ export const runStage = async (
2200
2307
 
2201
2308
  const ctx: StageContext = {
2202
2309
  ...initial,
2203
- codexEnv: await prepareCodexHome(
2204
- initial.dir,
2205
- getEnvironment(),
2206
- spec.research ? initial.research : undefined,
2207
- ),
2310
+ codexEnv: await prepareCodexHome(initial.dir, {
2311
+ stageModel: initial.stageModel,
2312
+ env: getEnvironment(),
2313
+ ...(spec.research && initial.research
2314
+ ? { research: initial.research }
2315
+ : {}),
2316
+ }),
2208
2317
  };
2209
2318
 
2210
2319
  const batches = stageBatches(ctx, stage);
@@ -2317,7 +2426,7 @@ export const runStage = async (
2317
2426
 
2318
2427
  const result: StageRun = {
2319
2428
  stage,
2320
- model: codexModel.model,
2429
+ model: ctx.stageModel.model,
2321
2430
  ok: output !== undefined,
2322
2431
  durationMs: Date.now() - started,
2323
2432
  usage,
@@ -1,10 +1,8 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import { z } from 'zod';
3
- import {
4
- codexRunnerProfile,
5
- resolveInternalModelProfile,
6
- } from '../models/profiles';
7
3
  import type { ModelBudgetLimits } from '../models/accounting';
4
+ import { localModelProfile } from '../models/local-profile';
5
+ import { resolveSupportedModel } from '../models/supported-models';
8
6
  import { resolveDataForSeoLocale } from '../probes/dataforseo-locale';
9
7
  import { probeLimitsSchema } from '../probes/limits';
10
8
  import {
@@ -83,7 +81,8 @@ export const runPolicySchema = z
83
81
  limits: probeLimitsSchema.prefault({}),
84
82
  coverageThresholds: coverageThresholdsSchema.prefault({}),
85
83
  allowPartial: z.boolean().default(false),
86
- // Enforced for the host's model calls; see BudgetPolicy.
84
+ // Caps every paid call of the run: probes, Codex stage sessions, host
85
+ // model calls and searches (see BudgetPolicy).
87
86
  budget: budgetPolicySchema.prefault({}),
88
87
  })
89
88
  .strict();
@@ -91,6 +90,10 @@ export const runPolicySchema = z
91
90
  export const auditFileSchema = z
92
91
  .object({
93
92
  version: z.literal(auditFileVersion),
93
+ // The gateway model every text role and Codex stage runs on; absent
94
+ // means the engine's recommended model (src/models/supported-models.ts).
95
+ // Probe surfaces are what is measured and keep their own pinned models.
96
+ model: z.string().trim().min(1).optional(),
94
97
  brand: brandSchema,
95
98
  competitors: z.array(brandSchema).min(1),
96
99
  ownedDomains: z.array(z.string().min(1)).max(20).optional(),
@@ -235,13 +238,12 @@ export const toRunRequest = (
235
238
  runId,
236
239
  mode: 'resume',
237
240
  grounding: file.grounding,
238
- modelProfile: {
239
- ...resolveInternalModelProfile(codexRunnerProfile),
241
+ modelProfile: localModelProfile(resolveSupportedModel(file.model), {
240
242
  // Pinned by the audit, never inferred from which credentials happen to
241
243
  // be set: full grounding searches, and preflight requires its key.
242
244
  searchProvider:
243
245
  file.grounding === 'full' ? 'dataforseo-google-organic-v1' : 'disabled',
244
- },
246
+ }),
245
247
  ...(modelBudget && { modelBudget }),
246
248
  surfaces: file.surfaces,
247
249
  maxPlannedUnits: file.runPolicy.maxPlannedUnits,
@@ -15,6 +15,10 @@ import {
15
15
  } from '../codex-workflow/author';
16
16
  import { runStage, type StageValue } from '../codex-workflow/stage';
17
17
  import { mintRunId } from '../lib/run-id';
18
+ import { authorToolCaps } from '../codex-workflow/author-tools';
19
+ import { createFileModelAccounting } from '../models/accounting';
20
+ import { localStageModel } from '../models/local-profile';
21
+ import type { SupportedModel } from '../models/supported-models';
18
22
  import { normalizeDomain } from '../analysis/scoring';
19
23
  import { briefSchema } from '../workflow/schema';
20
24
  import { allSurfaces, chatSurfaces } from '../schema';
@@ -51,7 +55,14 @@ export type AuthorRecord = z.infer<typeof authorRecordSchema>;
51
55
  /** The measurement fields of an audit file, which the digest and the diff
52
56
  * compare; the author reference and run policy are not measurement. */
53
57
  const proposalOf = (file: AuditFile) => {
54
- const { author: _author, runPolicy: _runPolicy, ...measured } = file;
58
+ // The model is method, not measurement: judging the same answers with
59
+ // another model is the same measurement.
60
+ const {
61
+ author: _author,
62
+ runPolicy: _runPolicy,
63
+ model: _model,
64
+ ...measured
65
+ } = file;
55
66
 
56
67
  return measured;
57
68
  };
@@ -73,10 +84,15 @@ export type LocalAuthorResult = {
73
84
  research: Awaited<ReturnType<typeof readAuthorResearch>>['summary'];
74
85
  };
75
86
 
76
- /** runLocalAuthor runs the author session over a brief into `dir`. */
87
+ /** runLocalAuthor runs the author session over a brief into `dir`, on
88
+ * `model`, under the approved cap: the draft directory's ledger reserves
89
+ * the research tools' whole search allowance before the session, and the
90
+ * session itself, so neither can take the run past the cap. */
77
91
  export const runLocalAuthor = async (args: {
78
92
  brief: AuthorBrief;
79
93
  dir: string;
94
+ model: SupportedModel;
95
+ maxUsd: number;
80
96
  secrets: readonly string[];
81
97
  signal?: AbortSignal;
82
98
  }): Promise<LocalAuthorResult> => {
@@ -86,6 +102,16 @@ export const runLocalAuthor = async (args: {
86
102
  try {
87
103
  await materializeAuthorWorkdir({ dir, brief });
88
104
 
105
+ const ledger = createFileModelAccounting({
106
+ filename: path.join(dir, 'BANK', 'model-budget.json'),
107
+ limits: {
108
+ maxUsd: args.maxUsd,
109
+ maxTokens: 20_000_000,
110
+ deadlineAt: new Date(Date.now() + 2 * 3_600_000).toISOString(),
111
+ },
112
+ assertOwned: () => Promise.resolve(),
113
+ });
114
+
89
115
  const domain = normalizeDomain(brief.website).replace(/^www\./, '');
90
116
  const reportKey = `local-${domain.replace(/[^a-z0-9]+/g, '-')}`;
91
117
  const runId = mintRunId();
@@ -115,11 +141,26 @@ export const runLocalAuthor = async (args: {
115
141
  ? { errors: [result.fatal, ...result.errors], fatal: true }
116
142
  : { errors: result.errors };
117
143
  };
144
+ // The research searches spend inside the tool server, which stops at
145
+ // its own allowance: that allowance is reserved first, and settled
146
+ // with what the searches cost once the session is over.
147
+ const researchCallId = `author-research:${runId}`;
148
+
149
+ await ledger.reserve({
150
+ callId: researchCallId,
151
+ role: 'search:author_research',
152
+ reservedUsd: authorToolCaps.searchSpendUsd,
153
+ inputTokens: 0,
154
+ maxOutputTokens: 0,
155
+ });
156
+
118
157
  const run = await runStage(
119
158
  {
120
159
  dir,
121
160
  brand: authorBrand(brief),
122
161
  answers: [],
162
+ stageModel: localStageModel(args.model),
163
+ accounting: ledger,
123
164
  timeoutMs: 30 * 60_000,
124
165
  research: await researchServerConfig(dir),
125
166
  verdict,
@@ -129,6 +170,9 @@ export const runLocalAuthor = async (args: {
129
170
  'author',
130
171
  );
131
172
  const research = (await readAuthorResearch(dir)).summary;
173
+
174
+ await ledger.settle(researchCallId, { costUsd: research.spendUsd });
175
+
132
176
  const output = await readAuthorOutput(dir);
133
177
 
134
178
  if (!run.ok || !output) {
@@ -140,6 +184,7 @@ export const runLocalAuthor = async (args: {
140
184
  const { config } = output;
141
185
  const proposed = auditFileSchema.parse({
142
186
  version: auditFileVersion,
187
+ model: args.model.id,
143
188
  brand: config.brand,
144
189
  competitors: config.competitors,
145
190
  sections: config.sections,