@remnic/core 10.0.26 → 10.0.27

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 (229) hide show
  1. package/dist/access-admin-ops-surface.js +23 -23
  2. package/dist/access-authorization-probe.js +24 -24
  3. package/dist/access-boundary.js +23 -23
  4. package/dist/access-cli.js +66 -66
  5. package/dist/access-extraction-force-flush.js +23 -23
  6. package/dist/access-http-briefing.js +24 -24
  7. package/dist/access-http-query.js +25 -25
  8. package/dist/access-http.js +39 -39
  9. package/dist/access-identity-continuity-surface.js +23 -23
  10. package/dist/access-lcm-surface.js +23 -23
  11. package/dist/access-mcp.js +32 -32
  12. package/dist/access-namespace-preflight.js +23 -23
  13. package/dist/access-observe-write-surface.js +23 -23
  14. package/dist/access-operations-batch.js +24 -24
  15. package/dist/access-operations.js +31 -31
  16. package/dist/access-recall-concurrency.js +23 -23
  17. package/dist/access-recall-response.js +23 -23
  18. package/dist/access-recall-surface.js +23 -23
  19. package/dist/access-service.js +23 -23
  20. package/dist/access-surface-catalog.js +25 -25
  21. package/dist/active-recall.js +4 -4
  22. package/dist/{auto-sync-7WWAKW6F.js → auto-sync-UQESPLCB.js} +5 -5
  23. package/dist/briefing.js +5 -5
  24. package/dist/buffer.js +3 -3
  25. package/dist/calibration.js +4 -4
  26. package/dist/causal-consolidation.js +6 -6
  27. package/dist/{chunk-AAQA6ZUP.js → chunk-23ZLN5X6.js} +13 -2
  28. package/dist/{chunk-AAQA6ZUP.js.map → chunk-23ZLN5X6.js.map} +1 -1
  29. package/dist/{chunk-NKGI7JWP.js → chunk-27LPB4NS.js} +2 -2
  30. package/dist/{chunk-E2I5FVEU.js → chunk-27SAUQ5R.js} +2 -2
  31. package/dist/{chunk-NJAFC244.js → chunk-2HLMFRZ7.js} +2 -2
  32. package/dist/{chunk-US4WUDQR.js → chunk-33UAWCBN.js} +2 -2
  33. package/dist/{chunk-OL7LAGBG.js → chunk-36DZ242S.js} +2 -2
  34. package/dist/{chunk-MRRLXXWA.js → chunk-4WT6I4VG.js} +2 -2
  35. package/dist/{chunk-VBINQDWP.js → chunk-5HT35H4L.js} +4 -4
  36. package/dist/{chunk-LO76EF3Y.js → chunk-7EJCAFMS.js} +2 -2
  37. package/dist/{chunk-DFL3MBL5.js → chunk-7IOB5F7Y.js} +3 -3
  38. package/dist/{chunk-YUZRI3QU.js → chunk-AN3G5DZH.js} +2 -2
  39. package/dist/{chunk-5BNDPLGI.js → chunk-AQ52ZFBC.js} +2 -2
  40. package/dist/{chunk-4B7JO3LG.js → chunk-AYHPSYZI.js} +2 -2
  41. package/dist/{chunk-FT4UQYOV.js → chunk-BDLOEODO.js} +2 -2
  42. package/dist/{chunk-G7QUQILS.js → chunk-BDQMMX3M.js} +2 -2
  43. package/dist/{chunk-B2BAZPVQ.js → chunk-BHQPOCQE.js} +2 -2
  44. package/dist/{chunk-BGG5BP3M.js → chunk-CCDHRDQ3.js} +2 -2
  45. package/dist/{chunk-QP5GYLMS.js → chunk-COGLFRXT.js} +17 -17
  46. package/dist/{chunk-EP6BA7VV.js → chunk-CU5TILGD.js} +2 -5
  47. package/dist/chunk-CU5TILGD.js.map +1 -0
  48. package/dist/{chunk-HWMK3QHK.js → chunk-EET24NSB.js} +3 -3
  49. package/dist/{chunk-2DT7PIDZ.js → chunk-EPOYPPOW.js} +2 -2
  50. package/dist/{chunk-JT7GSF3T.js → chunk-ERAVI25Z.js} +2 -2
  51. package/dist/{chunk-ECBAENW7.js → chunk-FFGHFU7A.js} +10 -10
  52. package/dist/{chunk-XSEVBFMD.js → chunk-FJJWA7NL.js} +21 -6
  53. package/dist/chunk-FJJWA7NL.js.map +1 -0
  54. package/dist/{chunk-2NQD4N42.js → chunk-G6XEYFCO.js} +10 -10
  55. package/dist/{chunk-Z2XUE3VT.js → chunk-GCZHKBY2.js} +2 -2
  56. package/dist/{chunk-JNLEJE4A.js → chunk-GEHIRZXF.js} +2 -2
  57. package/dist/{chunk-CZURNXGO.js → chunk-GMZNJZRP.js} +2 -2
  58. package/dist/{chunk-7BFE2UD4.js → chunk-H2X22KZW.js} +2 -2
  59. package/dist/{chunk-FI6CUYMJ.js → chunk-H75L4ZOH.js} +32 -32
  60. package/dist/{chunk-CT5YXLVB.js → chunk-HNEOLXRF.js} +2 -2
  61. package/dist/{chunk-BWOLINYY.js → chunk-I27WOMJ7.js} +2 -2
  62. package/dist/{chunk-KD73Q7EN.js → chunk-IHGLQJW6.js} +2 -2
  63. package/dist/{chunk-5A4QMATS.js → chunk-IHS2UGYM.js} +2 -2
  64. package/dist/{chunk-I75TTE7D.js → chunk-JHQAXATW.js} +2 -2
  65. package/dist/{chunk-HNZTKT4J.js → chunk-JX32ROLZ.js} +3 -3
  66. package/dist/{chunk-CA35LZAE.js → chunk-JYZLDZ2R.js} +7 -7
  67. package/dist/{chunk-DIHJ2QWP.js → chunk-JZIZBJCW.js} +2 -2
  68. package/dist/{chunk-UFUWKKCV.js → chunk-L3IP56F4.js} +17 -17
  69. package/dist/{chunk-XE5QLP3P.js → chunk-L5TJWQEF.js} +5 -5
  70. package/dist/{chunk-PIN5OPBA.js → chunk-LVU7FP27.js} +1 -1
  71. package/dist/{chunk-QM2SPLKQ.js → chunk-MLED254J.js} +1 -1
  72. package/dist/chunk-MLED254J.js.map +1 -0
  73. package/dist/{chunk-MKP4W52S.js → chunk-MPZYCRC6.js} +3 -3
  74. package/dist/{chunk-M47LM554.js → chunk-MSMGQDVW.js} +2 -2
  75. package/dist/{chunk-IXUEFTK4.js → chunk-N34ZW6E4.js} +2 -2
  76. package/dist/{chunk-Q35L7TYB.js → chunk-NYPQHFC3.js} +2 -2
  77. package/dist/{chunk-G2OYFTUD.js → chunk-O6S5FLZB.js} +2 -2
  78. package/dist/{chunk-5ALVWXQG.js → chunk-PLD6SOU7.js} +2 -2
  79. package/dist/{chunk-YBO2WGCV.js → chunk-PM72NSEW.js} +2 -2
  80. package/dist/{chunk-DUPHIZBY.js → chunk-PUDYANAX.js} +2 -2
  81. package/dist/{chunk-ROF3JORU.js → chunk-PXTLPC3P.js} +2 -2
  82. package/dist/{chunk-3F3HA3R2.js → chunk-RN7HPFYS.js} +2 -2
  83. package/dist/{chunk-HGSERGFX.js → chunk-S36KJNQH.js} +2 -2
  84. package/dist/{chunk-TRG3A2AW.js → chunk-SU5V2LWR.js} +2 -2
  85. package/dist/{chunk-ZXVLOKN4.js → chunk-SYUNCM26.js} +2 -2
  86. package/dist/{chunk-TKC5LZ43.js → chunk-UIDWASOS.js} +2 -2
  87. package/dist/{chunk-X3ZLVGGX.js → chunk-UJPGQCXD.js} +3 -3
  88. package/dist/{chunk-BO3F4X5U.js → chunk-UKWRCQWT.js} +2 -2
  89. package/dist/{chunk-D3I4P2SX.js → chunk-VMHCC7LO.js} +2 -2
  90. package/dist/{chunk-KDMZZSL4.js → chunk-VN3GHPBU.js} +2 -2
  91. package/dist/{chunk-SA7NPDWJ.js → chunk-W6MOLW5S.js} +9 -7
  92. package/dist/chunk-W6MOLW5S.js.map +1 -0
  93. package/dist/{chunk-DVE7B2IR.js → chunk-WFUO7NWX.js} +2 -2
  94. package/dist/{chunk-H53F22SJ.js → chunk-WJAGO5LL.js} +3 -3
  95. package/dist/{chunk-CJRENHVZ.js → chunk-XNAOCY67.js} +2 -2
  96. package/dist/{chunk-B45WUQUU.js → chunk-XSXM5LYZ.js} +2 -2
  97. package/dist/{chunk-EQAIXC4Q.js → chunk-Z3XVYXQ3.js} +2 -2
  98. package/dist/cli.js +49 -49
  99. package/dist/coding/export-okf-codegraph.js +4 -4
  100. package/dist/compounding/engine.js +6 -6
  101. package/dist/config.js +4 -4
  102. package/dist/connectors/codex-materialize-runner.js +5 -5
  103. package/dist/connectors/index.js +5 -5
  104. package/dist/convergence-refresh.js +7 -7
  105. package/dist/corpus-watermark.js +7 -7
  106. package/dist/deep-recall-policy-llm.js +3 -3
  107. package/dist/entity-retrieval.js +5 -5
  108. package/dist/external-wiki-access.js +24 -24
  109. package/dist/extraction-faithfulness.js +3 -3
  110. package/dist/extraction-judge.js +3 -3
  111. package/dist/extraction-span-wire.d.ts +8 -0
  112. package/dist/extraction-span-wire.d.ts.map +1 -1
  113. package/dist/extraction-span-wire.js +5 -3
  114. package/dist/extraction.js +12 -12
  115. package/dist/fallback-llm-codex-subscription.d.ts.map +1 -1
  116. package/dist/fallback-llm-codex-subscription.js +1 -1
  117. package/dist/fallback-llm.js +2 -2
  118. package/dist/harmonic-retrieval.js +5 -5
  119. package/dist/index.js +66 -66
  120. package/dist/local-llm-helpers.d.ts +2 -1
  121. package/dist/local-llm-helpers.d.ts.map +1 -1
  122. package/dist/local-llm-helpers.js +1 -1
  123. package/dist/local-llm.d.ts.map +1 -1
  124. package/dist/local-llm.js +6 -2
  125. package/dist/location/index.js +7 -7
  126. package/dist/maintenance/memory-governance.js +5 -5
  127. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +5 -5
  128. package/dist/maintenance/rebuild-memory-projection-runner.js +7 -7
  129. package/dist/maintenance/rebuild-memory-projection.js +6 -6
  130. package/dist/memory-browse-operations.js +24 -24
  131. package/dist/memory-browse.js +3 -3
  132. package/dist/namespaces/migrate.js +6 -6
  133. package/dist/namespaces/storage.js +5 -5
  134. package/dist/operator-doctor-corpus.js +8 -8
  135. package/dist/operator-toolkit.js +13 -13
  136. package/dist/orchestration/maintenance.js +17 -17
  137. package/dist/orchestrator.js +66 -66
  138. package/dist/recall-navigation-operations.js +24 -24
  139. package/dist/recall-navigation.js +23 -23
  140. package/dist/recall-planner-llm.js +2 -2
  141. package/dist/recall-state-view-admission.js +3 -3
  142. package/dist/recall-why-service.js +3 -3
  143. package/dist/resume-bundles.js +4 -4
  144. package/dist/semantic-consolidation.js +6 -6
  145. package/dist/semantic-rule-promotion.js +5 -5
  146. package/dist/semantic-rule-verifier.js +5 -5
  147. package/dist/source-agent-qualifier.js +8 -8
  148. package/dist/standup/build.js +5 -5
  149. package/dist/storage.js +4 -4
  150. package/dist/summarizer.js +5 -5
  151. package/dist/support-passport/index.js +26 -26
  152. package/dist/transfer/export-okf.js +5 -5
  153. package/dist/verified-recall.js +5 -5
  154. package/dist/who-knows-cli.js +6 -6
  155. package/dist/who-knows.js +5 -5
  156. package/package.json +2 -2
  157. package/src/ambient-provenance.test.ts +21 -3
  158. package/src/extraction-span-wire.ts +11 -0
  159. package/src/extraction.ts +2 -2
  160. package/src/fallback-llm-codex-subscription.ts +6 -9
  161. package/src/local-llm-helpers.ts +2 -1
  162. package/src/local-llm-json-schema-fallback.test.ts +278 -0
  163. package/src/local-llm.ts +22 -4
  164. package/dist/chunk-EP6BA7VV.js.map +0 -1
  165. package/dist/chunk-QM2SPLKQ.js.map +0 -1
  166. package/dist/chunk-SA7NPDWJ.js.map +0 -1
  167. package/dist/chunk-XSEVBFMD.js.map +0 -1
  168. /package/dist/{auto-sync-7WWAKW6F.js.map → auto-sync-UQESPLCB.js.map} +0 -0
  169. /package/dist/{chunk-NKGI7JWP.js.map → chunk-27LPB4NS.js.map} +0 -0
  170. /package/dist/{chunk-E2I5FVEU.js.map → chunk-27SAUQ5R.js.map} +0 -0
  171. /package/dist/{chunk-NJAFC244.js.map → chunk-2HLMFRZ7.js.map} +0 -0
  172. /package/dist/{chunk-US4WUDQR.js.map → chunk-33UAWCBN.js.map} +0 -0
  173. /package/dist/{chunk-OL7LAGBG.js.map → chunk-36DZ242S.js.map} +0 -0
  174. /package/dist/{chunk-MRRLXXWA.js.map → chunk-4WT6I4VG.js.map} +0 -0
  175. /package/dist/{chunk-VBINQDWP.js.map → chunk-5HT35H4L.js.map} +0 -0
  176. /package/dist/{chunk-LO76EF3Y.js.map → chunk-7EJCAFMS.js.map} +0 -0
  177. /package/dist/{chunk-DFL3MBL5.js.map → chunk-7IOB5F7Y.js.map} +0 -0
  178. /package/dist/{chunk-YUZRI3QU.js.map → chunk-AN3G5DZH.js.map} +0 -0
  179. /package/dist/{chunk-5BNDPLGI.js.map → chunk-AQ52ZFBC.js.map} +0 -0
  180. /package/dist/{chunk-4B7JO3LG.js.map → chunk-AYHPSYZI.js.map} +0 -0
  181. /package/dist/{chunk-FT4UQYOV.js.map → chunk-BDLOEODO.js.map} +0 -0
  182. /package/dist/{chunk-G7QUQILS.js.map → chunk-BDQMMX3M.js.map} +0 -0
  183. /package/dist/{chunk-B2BAZPVQ.js.map → chunk-BHQPOCQE.js.map} +0 -0
  184. /package/dist/{chunk-BGG5BP3M.js.map → chunk-CCDHRDQ3.js.map} +0 -0
  185. /package/dist/{chunk-QP5GYLMS.js.map → chunk-COGLFRXT.js.map} +0 -0
  186. /package/dist/{chunk-HWMK3QHK.js.map → chunk-EET24NSB.js.map} +0 -0
  187. /package/dist/{chunk-2DT7PIDZ.js.map → chunk-EPOYPPOW.js.map} +0 -0
  188. /package/dist/{chunk-JT7GSF3T.js.map → chunk-ERAVI25Z.js.map} +0 -0
  189. /package/dist/{chunk-ECBAENW7.js.map → chunk-FFGHFU7A.js.map} +0 -0
  190. /package/dist/{chunk-2NQD4N42.js.map → chunk-G6XEYFCO.js.map} +0 -0
  191. /package/dist/{chunk-Z2XUE3VT.js.map → chunk-GCZHKBY2.js.map} +0 -0
  192. /package/dist/{chunk-JNLEJE4A.js.map → chunk-GEHIRZXF.js.map} +0 -0
  193. /package/dist/{chunk-CZURNXGO.js.map → chunk-GMZNJZRP.js.map} +0 -0
  194. /package/dist/{chunk-7BFE2UD4.js.map → chunk-H2X22KZW.js.map} +0 -0
  195. /package/dist/{chunk-FI6CUYMJ.js.map → chunk-H75L4ZOH.js.map} +0 -0
  196. /package/dist/{chunk-CT5YXLVB.js.map → chunk-HNEOLXRF.js.map} +0 -0
  197. /package/dist/{chunk-BWOLINYY.js.map → chunk-I27WOMJ7.js.map} +0 -0
  198. /package/dist/{chunk-KD73Q7EN.js.map → chunk-IHGLQJW6.js.map} +0 -0
  199. /package/dist/{chunk-5A4QMATS.js.map → chunk-IHS2UGYM.js.map} +0 -0
  200. /package/dist/{chunk-I75TTE7D.js.map → chunk-JHQAXATW.js.map} +0 -0
  201. /package/dist/{chunk-HNZTKT4J.js.map → chunk-JX32ROLZ.js.map} +0 -0
  202. /package/dist/{chunk-CA35LZAE.js.map → chunk-JYZLDZ2R.js.map} +0 -0
  203. /package/dist/{chunk-DIHJ2QWP.js.map → chunk-JZIZBJCW.js.map} +0 -0
  204. /package/dist/{chunk-UFUWKKCV.js.map → chunk-L3IP56F4.js.map} +0 -0
  205. /package/dist/{chunk-XE5QLP3P.js.map → chunk-L5TJWQEF.js.map} +0 -0
  206. /package/dist/{chunk-PIN5OPBA.js.map → chunk-LVU7FP27.js.map} +0 -0
  207. /package/dist/{chunk-MKP4W52S.js.map → chunk-MPZYCRC6.js.map} +0 -0
  208. /package/dist/{chunk-M47LM554.js.map → chunk-MSMGQDVW.js.map} +0 -0
  209. /package/dist/{chunk-IXUEFTK4.js.map → chunk-N34ZW6E4.js.map} +0 -0
  210. /package/dist/{chunk-Q35L7TYB.js.map → chunk-NYPQHFC3.js.map} +0 -0
  211. /package/dist/{chunk-G2OYFTUD.js.map → chunk-O6S5FLZB.js.map} +0 -0
  212. /package/dist/{chunk-5ALVWXQG.js.map → chunk-PLD6SOU7.js.map} +0 -0
  213. /package/dist/{chunk-YBO2WGCV.js.map → chunk-PM72NSEW.js.map} +0 -0
  214. /package/dist/{chunk-DUPHIZBY.js.map → chunk-PUDYANAX.js.map} +0 -0
  215. /package/dist/{chunk-ROF3JORU.js.map → chunk-PXTLPC3P.js.map} +0 -0
  216. /package/dist/{chunk-3F3HA3R2.js.map → chunk-RN7HPFYS.js.map} +0 -0
  217. /package/dist/{chunk-HGSERGFX.js.map → chunk-S36KJNQH.js.map} +0 -0
  218. /package/dist/{chunk-TRG3A2AW.js.map → chunk-SU5V2LWR.js.map} +0 -0
  219. /package/dist/{chunk-ZXVLOKN4.js.map → chunk-SYUNCM26.js.map} +0 -0
  220. /package/dist/{chunk-TKC5LZ43.js.map → chunk-UIDWASOS.js.map} +0 -0
  221. /package/dist/{chunk-X3ZLVGGX.js.map → chunk-UJPGQCXD.js.map} +0 -0
  222. /package/dist/{chunk-BO3F4X5U.js.map → chunk-UKWRCQWT.js.map} +0 -0
  223. /package/dist/{chunk-D3I4P2SX.js.map → chunk-VMHCC7LO.js.map} +0 -0
  224. /package/dist/{chunk-KDMZZSL4.js.map → chunk-VN3GHPBU.js.map} +0 -0
  225. /package/dist/{chunk-DVE7B2IR.js.map → chunk-WFUO7NWX.js.map} +0 -0
  226. /package/dist/{chunk-H53F22SJ.js.map → chunk-WJAGO5LL.js.map} +0 -0
  227. /package/dist/{chunk-CJRENHVZ.js.map → chunk-XNAOCY67.js.map} +0 -0
  228. /package/dist/{chunk-B45WUQUU.js.map → chunk-XSXM5LYZ.js.map} +0 -0
  229. /package/dist/{chunk-EQAIXC4Q.js.map → chunk-Z3XVYXQ3.js.map} +0 -0
@@ -11,6 +11,8 @@ import {
11
11
  import { parseConfig } from "./config.js";
12
12
  import { bufferTurnsEqual, copyBufferTurn } from "./buffer-turn-helpers.js";
13
13
  import { ExtractionEngine } from "./extraction.js";
14
+ import { extractionProviderJsonSchema } from "./extraction-span-wire.js";
15
+ import type { LocalLlmChatCompletionOptions } from "./local-llm-helpers.js";
14
16
  import { SUMMARY_SYSTEM_PROMPT } from "./meetings/summary-extractor.js";
15
17
  import { emptySpeakerRegistry } from "./wearables/speakers.js";
16
18
  import { buildExtractionTurns } from "./wearables/memory-gen.js";
@@ -77,20 +79,26 @@ const MODEL_REGISTRY_FIXTURE = {
77
79
  };
78
80
 
79
81
  /** Run the local-LLM path, returning the prompt the model saw + the result. */
80
- async function runLocal(turns: BufferTurn[]): Promise<{ prompt: string; result: ExtractionResult }> {
82
+ async function runLocal(turns: BufferTurn[]): Promise<{
83
+ prompt: string;
84
+ result: ExtractionResult;
85
+ options: LocalLlmChatCompletionOptions;
86
+ }> {
81
87
  const engine = new ExtractionEngine(
82
88
  parseConfig({ localLlmEnabled: true, localLlmModel: "fixture-local", localLlmFallback: false }),
83
89
  );
84
90
  let prompt = "";
91
+ let options: LocalLlmChatCompletionOptions = {};
85
92
  const localLlm = {
86
- async chatCompletion(messages: ChatMessage[], _options: { signal?: AbortSignal } = {}) {
93
+ async chatCompletion(messages: ChatMessage[], seen: LocalLlmChatCompletionOptions = {}) {
87
94
  prompt = messages[1]?.content ?? "";
95
+ options = seen;
88
96
  return { content: JSON.stringify(HIGH_IMPACT_EXTRACTION) };
89
97
  },
90
98
  };
91
99
  assert.equal(Reflect.set(engine, "localLlm", localLlm), true);
92
100
  assert.equal(Reflect.set(engine, "modelRegistry", MODEL_REGISTRY_FIXTURE), true);
93
- return { result: await engine.extract(turns), prompt };
101
+ return { result: await engine.extract(turns), prompt, options };
94
102
  }
95
103
 
96
104
  /** Run the gateway-fallback path. */
@@ -169,6 +177,16 @@ for (const [name, run] of PATHS) {
169
177
  });
170
178
  }
171
179
 
180
+ test("local extraction supplies the provider JSON schema as responseFormat with an object root", async () => {
181
+ const { options } = await runLocal([TYPED_TURN]);
182
+ const schema = extractionProviderJsonSchema("off");
183
+ assert.deepEqual(options.responseFormat, {
184
+ type: "json_schema",
185
+ json_schema: { name: "extraction_result", strict: false, schema },
186
+ });
187
+ assert.equal(schema.type, "object");
188
+ });
189
+
172
190
  test("an ambient turn marked context-only does not trigger the ambient prompt", async () => {
173
191
  const { prompt } = await runGateway([
174
192
  { ...AMBIENT_TURN, extractionContextOnly: true },
@@ -58,3 +58,14 @@ export function extractionProviderJsonSchema(
58
58
  ? EXTRACTION_PROVIDER_JSON_SCHEMA_WITHOUT_SPAN
59
59
  : EXTRACTION_PROVIDER_JSON_SCHEMA_WITH_SPAN;
60
60
  }
61
+
62
+ export function extractionProviderResponseFormat(spanMode: ExtractionSpanConfig["spanMode"] = "off") {
63
+ return {
64
+ type: "json_schema" as const,
65
+ json_schema: {
66
+ name: "extraction_result",
67
+ schema: extractionProviderJsonSchema(spanMode),
68
+ strict: false,
69
+ },
70
+ };
71
+ }
package/src/extraction.ts CHANGED
@@ -54,7 +54,7 @@ import {
54
54
  } from "./extraction-prompt.js";
55
55
  import { containsExtractionPlaceholder, extractionAttributes, extractionCueAnchors, extractionText, isPlainRecord } from "./extraction-normalization.js";
56
56
  import { applyExtractionSpanMaterialization, bindLocalExtractionPrompt, buildSpanMaterializeTurns, stripUntrustedFactSpans, truncateLocalExtractionConversation, type SpanMaterializeTurn } from "./extraction-span-materialize.js";
57
- import { extractionProviderJsonSchema } from "./extraction-span-wire.js";
57
+ import { extractionProviderJsonSchema, extractionProviderResponseFormat } from "./extraction-span-wire.js";
58
58
  import { resolveLocalLlmCapabilities, resolveMemoryLifecycleCapabilities, resolvePipelineProcessingCapabilities, resolveRecallAuxiliaryCapabilities } from "./capabilities.js";
59
59
  type ExtractionQuestion = ExtractionResult["questions"][number];
60
60
  type ExtractedFactResult = ExtractionResult["facts"][number];
@@ -1506,6 +1506,7 @@ ${truncatedConversation}`;
1506
1506
  temperature: 0.1,
1507
1507
  maxTokens: contextSizes.maxOutputTokens,
1508
1508
  operation: "extraction",
1509
+ responseFormat: extractionProviderResponseFormat(this.config.extraction?.spanMode ?? "off"),
1509
1510
  disableThinking: shouldEnableLocalExtractionThinking(this.config, conversation.length)
1510
1511
  ? false
1511
1512
  : undefined,
@@ -1513,7 +1514,6 @@ ${truncatedConversation}`;
1513
1514
  signal,
1514
1515
  },
1515
1516
  );
1516
-
1517
1517
  if (!response?.content) {
1518
1518
  log.debug("extractWithLocalLlm: chatCompletion returned null or empty content");
1519
1519
  return null;
@@ -194,18 +194,15 @@ export function withCodexRuntimeShutdown<T extends { signal?: AbortSignal }>(
194
194
 
195
195
  export function isUnsupportedJsonSchemaError(error: unknown): boolean {
196
196
  const message = error instanceof Error ? error.message : String(error);
197
- // Require an HTTP status plus explicit schema/format context. A bare
198
- // "unsupported" (e.g. "'temperature' is unsupported with this model") must
199
- // NOT trigger the schema-stripping retry, or we pay a duplicate request
200
- // for unrelated provider errors.
197
+ // An echoed request format is not a capability rejection.
201
198
  if (!/\b(?:400|404|422)\b/.test(message)) {
202
199
  return false;
203
200
  }
204
- if (/(?:response[_ ]?format|json[_ ]?schema|structured[_ ]?output)/i.test(message)) {
205
- return true;
206
- }
207
- // "unsupported" only counts when adjacent to schema/format terminology.
208
- return /\bunsupported\b[\s\S]{0,40}\b(?:schema|format)\b/i.test(message);
201
+ return (
202
+ /(?:response[_ ]?format|json[_ ]?schema|structured[_ ]?output)\b[^;,\n]{0,60}\b(?:unsupported|not supported|not implemented|not available)\b/i.test(message) ||
203
+ /\b(?:unsupported|unknown|unrecognized)(?:[\s:"'=]|parameter|argument|request|supplied|field|type|value){1,40}\b(?:response[_ ]?format|json[_ ]?schema|structured[_ ]?output|schema|format)\b/i.test(message) ||
204
+ /\b(?:does not|doesn't|cannot|can't) support(?:[\s:"'=]|the|native|type){1,20}\b(?:response[_ ]?format|json[_ ]?schema|structured[_ ]?output|schema|format)\b/i.test(message)
205
+ );
209
206
  }
210
207
 
211
208
  export function extractResponsesOutputText(data: {
@@ -1,10 +1,11 @@
1
+ import type { ResponseFormatJSONSchema } from "openai/resources/shared";
1
2
  import { log } from "./logger.js";
2
3
  import type { LocalLlmRequestPriority } from "./local-llm.js";
3
4
 
4
5
  export interface LocalLlmChatCompletionOptions {
5
6
  temperature?: number;
6
7
  maxTokens?: number;
7
- responseFormat?: { type: string };
8
+ responseFormat?: { type: string } | ResponseFormatJSONSchema;
8
9
  timeoutMs?: number;
9
10
  operation?: string;
10
11
  forceDisableThinking?: boolean;
@@ -0,0 +1,278 @@
1
+ import assert from "node:assert/strict";
2
+ import http from "node:http";
3
+ import type { AddressInfo } from "node:net";
4
+ import test, { mock } from "node:test";
5
+
6
+ import { LocalLlmClient } from "./local-llm.js";
7
+ import { ChatTransport } from "./local-llm-transport.js";
8
+ import { parseConfig } from "./config.js";
9
+ import type { LocalLlmChatCompletionOptions } from "./local-llm-helpers.js";
10
+ import type { PluginConfig } from "./types.js";
11
+
12
+ function createConfig(overrides: Partial<PluginConfig> = {}): PluginConfig {
13
+ return parseConfig({
14
+ localLlmEnabled: true,
15
+ localLlmModel: "test-local-model",
16
+ localLlmUrl: "http://127.0.0.1:1234",
17
+ localLlmTimeoutMs: 5_000,
18
+ localLlmRetry5xxCount: 0,
19
+ localLlmRateLimitRetryCount: 0,
20
+ localLlmRetryBackoffMs: 1,
21
+ localLlmHeaders: { "X-Test": "yes" },
22
+ localLlmApiKey: undefined,
23
+ localLlmAuthHeader: false,
24
+ localLlm400TripThreshold: 50,
25
+ localLlm400CooldownMs: 60_000,
26
+ debug: false,
27
+ localLlmReasoningEffort: "none",
28
+ slowLogEnabled: false,
29
+ slowLogThresholdMs: 60_000,
30
+ ...overrides,
31
+ });
32
+ }
33
+
34
+ function primeClient(client: LocalLlmClient): void {
35
+ mock.method(client, "checkAvailability", async () => true);
36
+ }
37
+
38
+ interface RecordedRequest {
39
+ headers: http.IncomingHttpHeaders;
40
+ body: { model: string; response_format?: LocalLlmChatCompletionOptions["responseFormat"] };
41
+ }
42
+
43
+ async function startRecordingServer(
44
+ respond: (req: http.IncomingMessage, requestCount: number) => {
45
+ status: number;
46
+ body: unknown;
47
+ },
48
+ ): Promise<{
49
+ url: string;
50
+ requests: RecordedRequest[];
51
+ close: () => Promise<void>;
52
+ }> {
53
+ const requests: RecordedRequest[] = [];
54
+ const server = http.createServer((req, res) => {
55
+ let raw = "";
56
+ req.setEncoding("utf8");
57
+ req.on("data", (chunk: string) => {
58
+ raw += chunk;
59
+ });
60
+ req.on("end", () => {
61
+ requests.push({ headers: req.headers, body: JSON.parse(raw) });
62
+ const { status, body } = respond(req, requests.length);
63
+ res.writeHead(status, { "content-type": "application/json" });
64
+ res.end(JSON.stringify(body));
65
+ });
66
+ });
67
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
68
+ // SAFETY: listen(0, "127.0.0.1") above binds TCP, so its address is AddressInfo.
69
+ const { port } = server.address() as AddressInfo;
70
+ return {
71
+ url: `http://127.0.0.1:${port}/v1`,
72
+ requests,
73
+ close: async () => {
74
+ await new Promise<void>((resolve) => server.close(() => resolve()));
75
+ },
76
+ };
77
+ }
78
+
79
+ const okCompletion = {
80
+ choices: [{ message: { content: "done" } }],
81
+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
82
+ };
83
+
84
+ const responseFormat = {
85
+ type: "json_schema",
86
+ json_schema: {
87
+ name: "result",
88
+ schema: { type: "object", properties: { ok: { type: "boolean" } } },
89
+ },
90
+ };
91
+
92
+ test("forwards json_schema response_format when the backend accepts it", async () => {
93
+ const server = await startRecordingServer(() => ({ status: 200, body: okCompletion }));
94
+ try {
95
+ const client = new LocalLlmClient(createConfig({ localLlmUrl: server.url }));
96
+ primeClient(client);
97
+ const result = await client.chatCompletion([{ role: "user", content: "hello" }], {
98
+ responseFormat,
99
+ });
100
+ assert.equal(result?.content, "done");
101
+ assert.equal(server.requests.length, 1);
102
+ assert.deepEqual(server.requests[0].body.response_format, responseFormat);
103
+ } finally {
104
+ await server.close();
105
+ }
106
+ });
107
+
108
+ test("400 rejecting json_schema triggers exactly one retry without the format", async (t) => {
109
+ const server = await startRecordingServer((_req, count) =>
110
+ count === 1
111
+ ? {
112
+ status: 400,
113
+ body: {
114
+ error: { message: "response_format type json_schema is not supported" },
115
+ },
116
+ }
117
+ : { status: 200, body: okCompletion },
118
+ );
119
+ try {
120
+ const client = new LocalLlmClient(createConfig({ localLlmUrl: server.url }));
121
+ primeClient(client);
122
+ const post = ChatTransport.prototype.post;
123
+ const attempts: Array<Parameters<ChatTransport["post"]>[0]> = [];
124
+ t.mock.method(ChatTransport.prototype, "post", async function (this: ChatTransport, request: Parameters<ChatTransport["post"]>[0]) {
125
+ attempts.push(request);
126
+ return post.call(this, request);
127
+ });
128
+ const result = await client.chatCompletion([{ role: "user", content: "hello" }], {
129
+ responseFormat,
130
+ });
131
+ assert.equal(result?.content, "done");
132
+ assert.equal(server.requests.length, 2, "exactly one strip-and-retry");
133
+ assert.deepEqual(server.requests[0].body.response_format, responseFormat);
134
+ assert.equal(server.requests[1].body.response_format, undefined);
135
+ // headers/model/deadline preserved on the retry
136
+ assert.equal(server.requests[1].headers["x-test"], "yes");
137
+ assert.equal(server.requests[1].body.model, "test-local-model");
138
+ assert.equal(attempts[0].signal, attempts[1].signal, "retry shares the attempt deadline and caller abort");
139
+ assert.equal(attempts[0].budgetMs, attempts[1].budgetMs);
140
+ assert.deepEqual(attempts[0].headers, attempts[1].headers);
141
+ } finally {
142
+ await server.close();
143
+ }
144
+ });
145
+
146
+ test("timeout before strip-retry headers uses the configured transport retry", async (t) => {
147
+ const bodies: RecordedRequest["body"][] = [];
148
+ t.mock.method(ChatTransport.prototype, "post", async (request: Parameters<ChatTransport["post"]>[0]) => {
149
+ bodies.push(JSON.parse(request.body));
150
+ if (bodies.length === 1) return new Response("json_schema is not supported", { status: 400 });
151
+ if (bodies.length === 2) throw new DOMException("Timed out before headers", "AbortError");
152
+ return new Response(JSON.stringify(okCompletion), { status: 200 });
153
+ });
154
+ const client = new LocalLlmClient(createConfig({ localLlmRetry5xxCount: 1, localLlm400TripThreshold: 1 }));
155
+ primeClient(client);
156
+ const result = await client.chatCompletion([{ role: "user", content: "hello" }], { responseFormat });
157
+ assert.equal(result?.content, "done");
158
+ assert.equal(bodies.length, 3);
159
+ assert.deepEqual(bodies[0].response_format, responseFormat);
160
+ assert.equal(bodies[1].response_format, undefined);
161
+ assert.equal(bodies[2].response_format, undefined);
162
+ });
163
+
164
+ test("a diagnostic echo of the format is not a schema capability rejection", async () => {
165
+ for (const message of [
166
+ "Context length exceeded; request included response_format json_schema",
167
+ "Unsupported parameter temperature; request included response_format json_schema",
168
+ ]) {
169
+ const server = await startRecordingServer(() => ({ status: 400, body: { error: { message } } }));
170
+ try {
171
+ const client = new LocalLlmClient(createConfig({ localLlmUrl: server.url }));
172
+ primeClient(client);
173
+ assert.equal(await client.chatCompletion([{ role: "user", content: "hello" }], { responseFormat }), null);
174
+ assert.equal(server.requests.length, 1, "unrelated provider errors must not strip the format");
175
+ } finally {
176
+ await server.close();
177
+ }
178
+ }
179
+ });
180
+
181
+ test("an explicit unknown response_format field retries without the format", async () => {
182
+ const server = await startRecordingServer((_req, count) => count === 1
183
+ ? { status: 400, body: { error: { message: "Unknown field response_format" } } }
184
+ : { status: 200, body: okCompletion });
185
+ try {
186
+ const client = new LocalLlmClient(createConfig({ localLlmUrl: server.url }));
187
+ primeClient(client);
188
+ assert.equal((await client.chatCompletion([{ role: "user", content: "hello" }], { responseFormat }))?.content, "done");
189
+ assert.equal(server.requests.length, 2);
190
+ assert.deepEqual(server.requests[0].body.response_format, responseFormat);
191
+ assert.equal(server.requests[1].body.response_format, undefined);
192
+ } finally {
193
+ await server.close();
194
+ }
195
+ });
196
+
197
+ test("format removal persists for later 5xx attempts", async () => {
198
+ const server = await startRecordingServer((_req, count) =>
199
+ count === 1
200
+ ? { status: 400, body: { error: { message: "json_schema unsupported by backend" } } }
201
+ : count === 2
202
+ ? { status: 500, body: { error: { message: "boom" } } }
203
+ : { status: 200, body: okCompletion },
204
+ );
205
+ try {
206
+ const client = new LocalLlmClient(
207
+ createConfig({ localLlmUrl: server.url, localLlmRetry5xxCount: 2 }),
208
+ );
209
+ primeClient(client);
210
+ const result = await client.chatCompletion([{ role: "user", content: "hello" }], {
211
+ responseFormat,
212
+ });
213
+ assert.equal(result?.content, "done");
214
+ assert.equal(server.requests.length, 3);
215
+ assert.equal(server.requests[2].body.response_format, undefined);
216
+ } finally {
217
+ await server.close();
218
+ }
219
+ });
220
+
221
+ test("unrelated 400 and 429 are not retried with a stripped format", async () => {
222
+ for (const status of [400, 429]) {
223
+ const server = await startRecordingServer(() => ({
224
+ status,
225
+ body: { error: { message: "some other problem" } },
226
+ }));
227
+ try {
228
+ const client = new LocalLlmClient(createConfig({ localLlmUrl: server.url }));
229
+ primeClient(client);
230
+ const result = await client.chatCompletion([{ role: "user", content: "hello" }], {
231
+ responseFormat,
232
+ });
233
+ assert.equal(result, null);
234
+ assert.equal(server.requests.length, 1);
235
+ assert.ok(server.requests[0].body.response_format, "format still present");
236
+ } finally {
237
+ await server.close();
238
+ }
239
+ }
240
+ });
241
+
242
+ test("caller abort still fails closed during the strip retry", async () => {
243
+ const controller = new AbortController();
244
+ const server = await startRecordingServer((_req, count) => {
245
+ if (count === 2) controller.abort();
246
+ return count === 1
247
+ ? { status: 400, body: { error: { message: "response_format json_schema is not supported" } } }
248
+ : { status: 200, body: okCompletion };
249
+ });
250
+ try {
251
+ const client = new LocalLlmClient(createConfig({ localLlmUrl: server.url }));
252
+ primeClient(client);
253
+ const pending = client.chatCompletion([{ role: "user", content: "hello" }], {
254
+ responseFormat,
255
+ signal: controller.signal,
256
+ });
257
+ const result = await pending;
258
+ assert.equal(result, null);
259
+ assert.equal(server.requests.length, 2, "caller abort happens during the strip retry, not before the first request");
260
+ } finally {
261
+ await server.close();
262
+ }
263
+ });
264
+
265
+ test("request without response_format is unchanged", async () => {
266
+ const server = await startRecordingServer(() => ({ status: 200, body: okCompletion }));
267
+ try {
268
+ const client = new LocalLlmClient(createConfig({ localLlmUrl: server.url }));
269
+ primeClient(client);
270
+ const result = await client.chatCompletion([{ role: "user", content: "hello" }]);
271
+ assert.equal(result?.content, "done");
272
+ assert.equal(server.requests.length, 1);
273
+ assert.equal(server.requests[0].body.response_format, undefined);
274
+ } finally {
275
+ await server.close();
276
+ }
277
+ });
278
+
package/src/local-llm.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { log } from "./logger.js";
2
+ import { isUnsupportedJsonSchemaError } from "./fallback-llm-codex-subscription.js";
2
3
  import { estimateTokenCount } from "./token-estimate.js";
3
4
  import type { PluginConfig } from "./types.js";
4
5
  import fs from "node:fs";
@@ -953,7 +954,7 @@ export class LocalLlmClient {
953
954
  ? `${baseUrl}/chat/completions`
954
955
  : `${baseUrl}/v1/chat/completions`;
955
956
 
956
- const requestBodyJson = JSON.stringify(requestBody);
957
+ let requestBodyJson = JSON.stringify(requestBody);
957
958
  log.debug(
958
959
  `local LLM: sending request to ${chatUrl} with model ${this.config.localLlmModel}`,
959
960
  );
@@ -1004,14 +1005,31 @@ export class LocalLlmClient {
1004
1005
  try {
1005
1006
  response = await this.chatTransport.post({
1006
1007
  url: chatUrl,
1007
- headers: this.buildRequestHeaders({
1008
- "Content-Type": "application/json",
1009
- }),
1008
+ headers: this.buildRequestHeaders({ "Content-Type": "application/json" }),
1010
1009
  body: requestBodyJson,
1011
1010
  signal: attemptAbort.signal,
1012
1011
  budgetMs: this.config.localLlmTimeoutMs,
1013
1012
  });
1014
1013
  responseBody = await response.text();
1014
+ if (
1015
+ response.status === 400 &&
1016
+ requestBody.response_format &&
1017
+ isUnsupportedJsonSchemaError(`400 ${responseBody}`)
1018
+ ) {
1019
+ // Match gateway degradation without extending this attempt's deadline.
1020
+ delete requestBody.response_format;
1021
+ requestBodyJson = JSON.stringify(requestBody);
1022
+ log.debug("local LLM rejected native JSON schema; retrying without it");
1023
+ response = null;
1024
+ response = await this.chatTransport.post({
1025
+ url: chatUrl,
1026
+ headers: this.buildRequestHeaders({ "Content-Type": "application/json" }),
1027
+ body: requestBodyJson,
1028
+ signal: attemptAbort.signal,
1029
+ budgetMs: this.config.localLlmTimeoutMs,
1030
+ });
1031
+ responseBody = await response.text();
1032
+ }
1015
1033
  } catch (err) {
1016
1034
  const error = err instanceof Error ? err : new Error(String(err));
1017
1035
  if (options.signal?.aborted) {
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/fallback-llm-codex-subscription.ts","../src/providers/codex-subscription.ts"],"sourcesContent":["/**\n * Helpers extracted from FallbackLlmClient so fallback-llm.ts stays under\n * the 1200-line cap: Codex-subscription lifecycle (issue #2833) plus\n * generic chain helpers used by the same client.\n */\n\nimport path from \"node:path\";\nimport { raceAbort } from \"./abort-error.js\";\nimport { callCodexCliFallback, isCodexCliFallbackRunnerRegistered } from \"./cli-fallback.js\";\nimport type { CodexCliFallbackRunner } from \"./cli-fallback.js\";\nimport {\n CODEX_SUBSCRIPTION_PROVIDER_ID,\n CodexSubscriptionAuthError,\n CodexSubscriptionConfigError,\n CodexSubscriptionTimeoutError,\n assertNoApiKeyConfig,\n ensureCodexSubscriptionRunnerRegistered,\n getCodexSubscriptionRunnerForOwner,\n getCodexSubscriptionShutdownSignal,\n isDefaultRegisteredCodexSubscriptionRunner,\n} from \"./providers/codex-subscription.js\";\nimport type { GetRuntimeAuthForModelFn, ResolveApiKeyFn } from \"./resolve-provider-secret.js\";\nimport { resolveHomeDir } from \"./runtime/env.js\";\nimport type { GatewayConfig, ModelProviderConfig } from \"./types.js\";\nimport { expandTildePath } from \"./utils/path.js\";\n\ntype CodexSubscriptionAttemptResult = {\n content: string;\n usage?: {\n inputTokens?: number;\n outputTokens?: number;\n totalTokens?: number;\n };\n};\n\n/**\n * Terminal codex-subscription failures (timeout, auth, config contract).\n * These carry documented caller guidance (`TimeoutError` name, `codex login`\n * steps), so they must survive the chain instead of collapsing into a\n * generic empty/http_error result (issue #2833).\n */\nexport function isTerminalCodexSubscriptionError(error: unknown): boolean {\n return (\n error instanceof CodexSubscriptionTimeoutError ||\n error instanceof CodexSubscriptionAuthError ||\n error instanceof CodexSubscriptionConfigError\n );\n}\n\n/**\n * Single bounded headroom shared by both sides of the Codex deadline\n * (issue #2890): the provider gets it as SIGTERM lead time\n * (`timeoutMs - headroom`) and the outer race as settle grace, so the hard\n * outer bound stays `timeoutMs + headroom` (<= 25 ms past the deadline).\n */\nexport function codexDeadlineHeadroomMs(timeoutMs: number): number {\n return Math.min(25, Math.max(1, Math.floor(timeoutMs / 10)));\n}\n\n/**\n * Settle a fallback-LLM chain at the caller deadline. Abort the in-flight\n * work, then wait a bounded settle grace for the chain to surface a typed\n * provider timeout (default: one event-loop turn). A chain that settles\n * within the grace wins with its own result or error; one that never\n * settles still cannot exceed `timeoutMs + settleGraceMs`. The abandoned\n * promise is observed so a late rejection cannot become unhandled.\n */\nexport async function raceFallbackLlmDeadline<T>(\n work: Promise<T>,\n timeoutMs: number,\n abortOnTimeout: () => void,\n settleGraceMs = 0,\n): Promise<{ timedOut: true } | { timedOut: false; value: T }> {\n const deadline = new AbortController();\n const timer = setTimeout(() => deadline.abort(), timeoutMs);\n deadline.signal.addEventListener(\"abort\", abortOnTimeout, { once: true });\n try {\n const value = await raceAbort(\n work,\n deadline.signal,\n `fallback LLM timed out after ${timeoutMs}ms`,\n );\n return { timedOut: false, value };\n } catch (error) {\n if (!deadline.signal.aborted) throw error;\n let graceTimer: NodeJS.Timeout | undefined;\n const afterAbort = await Promise.race([\n work.then(\n (value) => ({ state: \"value\" as const, value }),\n (lateError) => ({ state: \"error\" as const, error: lateError }),\n ),\n new Promise<{ state: \"pending\" }>((resolve) => {\n if (settleGraceMs > 0) {\n graceTimer = setTimeout(() => resolve({ state: \"pending\" }), settleGraceMs);\n } else {\n setImmediate(() => resolve({ state: \"pending\" }));\n }\n }),\n ]);\n clearTimeout(graceTimer);\n if (afterAbort.state === \"value\") return { timedOut: false, value: afterAbort.value };\n if (afterAbort.state === \"error\") throw afterAbort.error;\n void work.then(\n () => undefined,\n () => undefined,\n );\n return { timedOut: true };\n } finally {\n clearTimeout(timer);\n deadline.signal.removeEventListener(\"abort\", abortOnTimeout);\n }\n}\n\n/**\n * Attempt the Codex CLI / subscription provider. Returns `undefined` when the\n * model is not `api: \"codex-cli\"` so the generic FallbackLlmClient path runs.\n *\n * Subscription ids reject a configured apiKey before generic secret resolution\n * — otherwise an unresolvable ref throws a generic error and the provider's\n * `codex login` guidance never surfaces (issue #2833). Other `codex-cli`\n * providers still resolve a configured key. Runtime auth is skipped: the CLI\n * login is the credential.\n */\nexport async function tryCodexSubscriptionProvider(\n model: {\n providerId: string;\n modelId: string;\n providerConfig: ModelProviderConfig;\n },\n messages: Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n options: { timeoutMs?: number; signal?: AbortSignal },\n resolveFallbackApiKey: () => Promise<string | undefined>,\n runner?: CodexCliFallbackRunner,\n): Promise<CodexSubscriptionAttemptResult | undefined> {\n if (model.providerConfig.api !== \"codex-cli\") return undefined;\n\n if (model.providerId === CODEX_SUBSCRIPTION_PROVIDER_ID) {\n assertNoApiKeyConfig(model.providerConfig);\n }\n\n const resolvedApiKey =\n model.providerConfig.apiKey === undefined ? undefined : await resolveFallbackApiKey();\n const rawKey = model.providerConfig.apiKey;\n const needsResolution =\n rawKey === \"secretref-managed\" || (typeof rawKey === \"object\" && rawKey !== null);\n if (needsResolution && !resolvedApiKey) {\n throw new Error(`API key for provider \"${model.providerId}\" could not be resolved from secret ref`);\n }\n\n const effectiveConfig: ModelProviderConfig = {\n ...model.providerConfig,\n ...(resolvedApiKey ? { apiKey: resolvedApiKey } : {}),\n };\n\n // Let the provider surface its typed timeout before the generic outer\n // deadline: the shared bounded headroom is SIGTERM lead time here and\n // settle grace in raceFallbackLlmDeadline (issue #2890).\n const callOptions = {\n timeoutMs: options.timeoutMs === undefined\n ? undefined\n : Math.max(1, options.timeoutMs - codexDeadlineHeadroomMs(options.timeoutMs)),\n signal: options.signal,\n };\n // A host/benchmark runner on the process seam still wins. The core\n // default runner does not: prefer the owning runtime so shutdown\n // terminates the request that runtime started.\n if (isCodexCliFallbackRunnerRegistered() && !(runner && isDefaultRegisteredCodexSubscriptionRunner())) {\n return await callCodexCliFallback(effectiveConfig, model.modelId, messages, callOptions);\n }\n if (runner) {\n return await callCodexCliFallback(effectiveConfig, model.modelId, messages, callOptions, runner);\n }\n ensureCodexSubscriptionRunnerRegistered();\n return await callCodexCliFallback(effectiveConfig, model.modelId, messages, callOptions);\n}\n\nexport function abortReason(signal: AbortSignal | undefined): Error {\n const reason = signal?.reason;\n return reason instanceof Error ? reason : new Error(\"task LLM request aborted\");\n}\n\nexport function withCodexRuntimeShutdown<T extends { signal?: AbortSignal }>(\n options: T,\n runner: CodexCliFallbackRunner | undefined,\n): T {\n if (!runner) return options;\n const shutdown = getCodexSubscriptionShutdownSignal(runner);\n if (!shutdown) return options;\n return {\n ...options,\n signal: options.signal ? AbortSignal.any([options.signal, shutdown]) : shutdown,\n };\n}\n\nexport function isUnsupportedJsonSchemaError(error: unknown): boolean {\n const message = error instanceof Error ? error.message : String(error);\n // Require an HTTP status plus explicit schema/format context. A bare\n // \"unsupported\" (e.g. \"'temperature' is unsupported with this model\") must\n // NOT trigger the schema-stripping retry, or we pay a duplicate request\n // for unrelated provider errors.\n if (!/\\b(?:400|404|422)\\b/.test(message)) {\n return false;\n }\n if (/(?:response[_ ]?format|json[_ ]?schema|structured[_ ]?output)/i.test(message)) {\n return true;\n }\n // \"unsupported\" only counts when adjacent to schema/format terminology.\n return /\\bunsupported\\b[\\s\\S]{0,40}\\b(?:schema|format)\\b/i.test(message);\n}\n\nexport function extractResponsesOutputText(data: {\n output_text?: string;\n output?: Array<{\n type?: string;\n text?: string;\n content?: Array<{\n type?: string;\n text?: string;\n }>;\n }>;\n}): string | null {\n if (typeof data.output_text === \"string\" && data.output_text.trim().length > 0) {\n return data.output_text;\n }\n\n const chunks: string[] = [];\n for (const item of data.output ?? []) {\n if (typeof item.text === \"string\" && item.text.trim().length > 0) {\n chunks.push(item.text);\n }\n for (const part of item.content ?? []) {\n if (\n (part.type === \"output_text\" || part.type === \"text\") &&\n typeof part.text === \"string\" &&\n part.text.trim().length > 0\n ) {\n chunks.push(part.text);\n }\n }\n }\n\n const joined = chunks.join(\"\\n\").trim();\n return joined.length > 0 ? joined : null;\n}\n\nexport type StructuredParseFailureReason =\n | \"no_models\"\n | \"empty\"\n | \"http_error\"\n | \"schema_rejection\"\n | \"timeout\";\n\nexport interface StructuredParseFailure {\n result: null;\n failureReason: StructuredParseFailureReason;\n /** Model string of the last attempt, when one was selected. Not `modelUsed`. */\n attemptedModel?: string;\n /** HTTP status when known. Never a response body. */\n httpStatus?: number;\n /** Coarse class: http_4xx / http_5xx / timeout / network / empty / schema_rejection / no_models. */\n errorClass?: string;\n}\n\nexport type StructuredParseResult<T> =\n | { result: T; modelUsed: string }\n | StructuredParseFailure;\n\nexport interface FallbackLlmRuntimeContext {\n agentDir?: string;\n getRuntimeAuthForModel?: GetRuntimeAuthForModelFn | null;\n resolveApiKeyForProvider?: ResolveApiKeyFn | null;\n workspaceDir?: string;\n /** Per-runtime Codex child owner. Shutdown must terminate only this runner. */\n codexSubscriptionRunner?: CodexCliFallbackRunner;\n}\n\ntype GatewayBackedRuntimeConfig = {\n providerApiKeyResolver?: ResolveApiKeyFn | null;\n runtimeAuthForModelResolver?: GetRuntimeAuthForModelFn | null;\n workspaceDir?: string;\n};\n\nexport function fallbackLlmRuntimeContextFromConfig(\n config: Pick<\n GatewayBackedRuntimeConfig,\n \"providerApiKeyResolver\" | \"runtimeAuthForModelResolver\" | \"workspaceDir\"\n >,\n overrides: FallbackLlmRuntimeContext = {},\n): FallbackLlmRuntimeContext {\n return {\n workspaceDir: config.workspaceDir,\n resolveApiKeyForProvider: config.providerApiKeyResolver,\n getRuntimeAuthForModel: config.runtimeAuthForModelResolver,\n codexSubscriptionRunner: getCodexSubscriptionRunnerForOwner(config),\n ...overrides,\n };\n}\n\nconst HTTP_STATUS_IN_MESSAGE = /\\b([1-5]\\d{2})\\b/;\n\nexport function isTimeoutError(err: unknown): boolean {\n const msg = err instanceof Error ? err.message : String(err);\n return /timed out after \\d+ms/i.test(msg) || /timed out before request started/i.test(msg);\n}\n\nfunction isEmptyProviderResponse(err: unknown): boolean {\n const msg = err instanceof Error ? err.message : String(err);\n return /^Empty response from /i.test(msg);\n}\n\nfunction finiteHttpStatus(value: unknown): number | undefined {\n if (typeof value !== \"number\" || !Number.isFinite(value) || !Number.isInteger(value)) return undefined;\n if (value < 100 || value > 599) return undefined;\n return value;\n}\n\nfunction httpStatusFromProviderError(err: unknown): number | undefined {\n if (err && typeof err === \"object\") {\n if (\"status\" in err) {\n const status = finiteHttpStatus(err.status);\n if (status !== undefined) return status;\n }\n if (\"statusCode\" in err) {\n const status = finiteHttpStatus(err.statusCode);\n if (status !== undefined) return status;\n }\n }\n const msg = err instanceof Error ? err.message : String(err);\n const match = HTTP_STATUS_IN_MESSAGE.exec(msg);\n if (!match) return undefined;\n return finiteHttpStatus(Number(match[1]));\n}\n\nfunction errorClassForHttpStatus(status: number): string {\n if (status >= 500) return \"http_5xx\";\n if (status >= 400) return \"http_4xx\";\n return `http_${status}`;\n}\n\nexport function classifyThrownProviderError(err: unknown): Omit<StructuredParseFailure, \"result\"> {\n if (isTimeoutError(err)) {\n return { failureReason: \"timeout\", errorClass: \"timeout\" };\n }\n if (isEmptyProviderResponse(err)) {\n return { failureReason: \"empty\", errorClass: \"empty\" };\n }\n const httpStatus = httpStatusFromProviderError(err);\n if (httpStatus !== undefined) {\n return {\n failureReason: \"http_error\",\n httpStatus,\n errorClass: errorClassForHttpStatus(httpStatus),\n };\n }\n return { failureReason: \"http_error\", errorClass: \"network\" };\n}\n\nexport function normalizeRuntimePath(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n return trimmed.length > 0 ? expandTildePath(trimmed) : undefined;\n}\n\nexport function readGatewayWorkspaceDir(gatewayConfig: GatewayConfig | undefined): string | undefined {\n if (!gatewayConfig || typeof gatewayConfig !== \"object\") return undefined;\n const raw = gatewayConfig as Record<string, unknown>;\n return (\n normalizeRuntimePath(raw.workspaceDir) ??\n normalizeRuntimePath(raw.workspacePath) ??\n normalizeRuntimePath(raw.workspace)\n );\n}\n\nexport function defaultOpenClawWorkspaceDir(): string {\n return path.join(resolveHomeDir(), \".openclaw\", \"workspace\");\n}\n","/**\n * Codex subscription extraction provider (issue #2784).\n *\n * Routes extraction/consolidation LLM calls through the `codex` CLI so the\n * operator's Codex subscription (ChatGPT OAuth login) authenticates the\n * request — no OpenAI API key and no codex-openai-proxy. Credentials stay in\n * the CLI's own auth store; this module never reads, accepts, or logs tokens.\n *\n * Transport contract mirrors `packages/bench/src/providers/codex-cli.ts`\n * (`codex exec --json --output-last-message`, env allowlist, login-status\n * precheck) but lives in core so the standalone daemon and host plugins get\n * a working `api: \"codex-cli\"` transport without importing the optional\n * bench package. Registered through the existing\n * `setCodexCliFallbackRunnerForProcess` seam, and only when no host or\n * benchmark runner has claimed it first.\n */\n\nimport { mkdir, mkdtemp, readFile, rm, stat } from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\n\nimport type {\n CodexCliFallbackConfig,\n CodexCliFallbackMessage,\n CodexCliFallbackRequest,\n CodexCliFallbackResult,\n CodexCliFallbackRunner,\n} from \"../cli-fallback.js\";\nimport { getCodexCliFallbackRunnerForProcess, isCodexCliFallbackRunnerRegistered, normalizeCodexCliTimeoutMs, setCodexCliFallbackRunnerForProcess } from \"../cli-fallback.js\";\nimport { log } from \"../logger.js\";\nimport { launchProcess } from \"../runtime/child-process.js\";\nimport type { CodexCliReasoningEffort, ModelProviderConfig } from \"../types.js\";\nimport { expandTildePath } from \"../utils/path.js\";\n\nexport const CODEX_SUBSCRIPTION_PROVIDER_ID = \"codex-subscription\";\n\n/** Env var overriding the codex executable (mirrors the bench provider). */\nconst CODEX_EXECUTABLE_ENV = \"REMNIC_CODEX_EXECUTABLE\";\n\nconst DEFAULT_REASONING_EFFORT: CodexCliReasoningEffort = \"medium\";\nconst DEFAULT_TIMEOUT_MS = 120_000;\nconst LOGIN_STATUS_TIMEOUT_MS = 10_000;\nconst LOGIN_STATUS_CACHE_TTL_MS = 10 * 60_000;\nconst STDIO_LIMIT = 64_000;\nconst OUTPUT_SUMMARY_LIMIT = 500;\n/**\n * Env keys whose value is a filesystem path. Relative values resolve against\n * the original process cwd before either child launches, because the exec\n * child runs with cwd = the ephemeral workspace (same rule as executables).\n */\nconst PATH_BEARING_ENV_KEYS: Readonly<Record<string, true>> = Object.freeze({ CODEX_HOME: true, HOME: true, USERPROFILE: true });\n\n/**\n * Environment keys forwarded to the codex child. Everything else — including\n * ambient `OPENAI_API_KEY` / `OPENAI_BASE_URL` — is stripped so the CLI cannot\n * silently fall back to metered API-key auth instead of the subscription\n * login. Mirrors the bench provider's allowlist.\n */\nconst CODEX_RUNTIME_ENV_ALLOWLIST: Readonly<Record<string, true>> = Object.freeze({\n ALL_PROXY: true,\n APPDATA: true,\n CODEX_HOME: true,\n COLORTERM: true,\n COMSPEC: true,\n FORCE_COLOR: true,\n HOME: true,\n HOMEDRIVE: true,\n HOMEPATH: true,\n LANG: true,\n LOCALAPPDATA: true,\n LOGNAME: true,\n NO_COLOR: true,\n NODE_EXTRA_CA_CERTS: true,\n NO_PROXY: true,\n NUMBER_OF_PROCESSORS: true,\n OS: true,\n PATH: true,\n PATHEXT: true,\n PROGRAMDATA: true,\n PROCESSOR_ARCHITECTURE: true,\n HTTP_PROXY: true,\n HTTPS_PROXY: true,\n SHELL: true,\n SSL_CERT_DIR: true,\n SSL_CERT_FILE: true,\n SYSTEMDRIVE: true,\n SYSTEMROOT: true,\n TEMP: true,\n TERM: true,\n TMP: true,\n TMPDIR: true,\n USER: true,\n USERNAME: true,\n USERPROFILE: true,\n WINDIR: true,\n XDG_CACHE_HOME: true,\n XDG_CONFIG_HOME: true,\n XDG_DATA_HOME: true,\n XDG_RUNTIME_DIR: true,\n});\n\nconst LOGIN_OK_PATTERN = /logged in using chatgpt/i;\nconst LOGIN_API_KEY_PATTERN = /api key/i;\n/** CLI output shapes that mean the subscription session was rejected. */\nconst AUTH_FAILURE_PATTERN =\n /\\b401\\b|\\b403\\b|unauthorized|forbidden|not logged in|no active|re-?authenticat|token expired|session expired|please log ?in/i;\nconst TIMEOUT_PATTERN = /timed out after \\d+ms/i;\n/** Secret shapes a codex CLI could echo into errors; replaced before surfacing. */\nconst SECRET_ECHO_PATTERNS: readonly RegExp[] = [\n /sk-[A-Za-z0-9_-]{8,}/g,\n /Bearer\\s+[A-Za-z0-9._-]{8,}/g,\n /eyJ[A-Za-z0-9._-]{10,}/g,\n];\n\n/**\n * Built-in provider entry so `\"codex-subscription/<model>\"` chains resolve\n * with no models.json and no apiKey — the transport owns authentication.\n */\nexport function codexSubscriptionBuiltinProviderConfig(): ModelProviderConfig {\n return {\n baseUrl: \"codex-cli://subscription\",\n api: \"codex-cli\",\n models: [],\n };\n}\n\nexport type CodexSubscriptionAuthReason = \"unauthenticated\" | \"expired_or_revoked\";\n\n/** Login/authorization failure with actionable re-auth guidance. */\nexport class CodexSubscriptionAuthError extends Error {\n readonly reason: CodexSubscriptionAuthReason;\n\n constructor(reason: CodexSubscriptionAuthReason, message: string) {\n super(message);\n this.name = \"CodexSubscriptionAuthError\";\n this.reason = reason;\n }\n}\n\n/** Provider config violated the no-raw-credentials contract. */\nexport class CodexSubscriptionConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CodexSubscriptionConfigError\";\n }\n}\n\n/** Request exceeded its deadline. Abort-driven cancellations rethrow the\n * caller's own abort reason instead, preserving the AbortError contract. */\nexport class CodexSubscriptionTimeoutError extends Error {\n constructor(timeoutMs: number) {\n super(`codex-subscription request timed out after ${timeoutMs}ms`);\n this.name = \"TimeoutError\";\n }\n}\n\nexport interface CodexSubscriptionExecRequest {\n executable: string;\n args: string[];\n input: string;\n env: NodeJS.ProcessEnv;\n outputPath: string;\n workspacePath: string;\n timeoutMs?: number;\n signal?: AbortSignal;\n}\n\nexport interface CodexSubscriptionExecResult {\n status: number | null;\n signal?: NodeJS.Signals | null;\n stdout: string;\n stderr: string;\n outputText: string;\n}\n\nexport interface CodexSubscriptionRunnerDeps {\n /** Runs `codex exec`. Default: isolated subprocess via launchProcess. */\n runCodexExec?: (request: CodexSubscriptionExecRequest) => Promise<CodexSubscriptionExecResult>;\n /** Runs `codex login status`. Default: isolated subprocess. Receives the\n * shared login-status ceiling (not any one caller's deadline) and the\n * shared-check abort signal (fires when the last waiter leaves). */\n runLoginStatus?: (\n executable: string,\n env: NodeJS.ProcessEnv,\n timeoutMs: number,\n signal?: AbortSignal\n ) => Promise<{ status: number | null; stdout: string; stderr: string }>;\n /** Environment the isolated child env is filtered from. Tests inject fakes. */\n env?: NodeJS.ProcessEnv;\n tmpdir?: () => string;\n now?: () => number;\n}\n\ninterface CommandOutput {\n status: number | null;\n signal?: NodeJS.Signals | null;\n stdout: string;\n stderr: string;\n}\n\ninterface LoginStatusCacheEntry {\n at: number;\n promise: Promise<void>;\n /** Auth-store fingerprint at check time; a mismatch invalidates the entry. */\n fingerprint: string | null;\n /** Live waiters. The in-flight check aborts when the last waiter leaves. */\n waiters: number;\n settled: boolean;\n controller: AbortController;\n}\n\nconst loginStatusCache = new Map<string, LoginStatusCacheEntry>();\nconst inFlightLoginByRunner = new WeakMap<CodexCliFallbackRunner, Map<string, LoginStatusCacheEntry>>();\nconst childrenByRunner = new WeakMap<CodexCliFallbackRunner, Set<number>>();\nconst runnerByOwner = new WeakMap<object, CodexCliFallbackRunner>();\nconst shutdownByRunner = new WeakMap<CodexCliFallbackRunner, AbortController>();\nlet defaultRegisteredRunner: CodexCliFallbackRunner | undefined;\nlet coreRunnerRegistered = false;\n\nexport function createCodexSubscriptionRunner(deps: CodexSubscriptionRunnerDeps = {}): CodexCliFallbackRunner {\n const envSource = deps.env ?? process.env;\n const children = new Set<number>();\n const shutdown = new AbortController();\n const runnerDeps: CodexSubscriptionRunnerDeps = {\n ...deps,\n runCodexExec: deps.runCodexExec ?? ((request) => runCodexExecSubprocess(request, children)),\n runLoginStatus:\n deps.runLoginStatus ??\n ((executable, env, timeoutMs, signal) =>\n runLoginStatusSubprocess(executable, env, timeoutMs, signal, children)),\n };\n const runner: CodexCliFallbackRunner = (request) => {\n const signal = request.options.signal\n ? AbortSignal.any([request.options.signal, shutdown.signal])\n : shutdown.signal;\n if (signal.aborted) {\n return Promise.reject(abortErrorOf(signal));\n }\n return runCodexSubscriptionRequest(\n { ...request, options: { ...request.options, signal } },\n runnerDeps,\n envSource,\n runner,\n );\n };\n childrenByRunner.set(runner, children);\n shutdownByRunner.set(runner, shutdown);\n return runner;\n}\n\n/** One runner per owning runtime/config object so teardown cannot cross instances. */\nexport function getCodexSubscriptionRunnerForOwner(owner: object): CodexCliFallbackRunner {\n let runner = runnerByOwner.get(owner);\n const shutdown = runner ? shutdownByRunner.get(runner) : undefined;\n if (!runner || shutdown?.signal.aborted) {\n runner = createCodexSubscriptionRunner();\n runnerByOwner.set(owner, runner);\n }\n return runner;\n}\n\n/** Shutdown signal for the owning runner, if this function is a core runner. */\nexport function getCodexSubscriptionShutdownSignal(\n runner: CodexCliFallbackRunner,\n): AbortSignal | undefined {\n return shutdownByRunner.get(runner)?.signal;\n}\n\n/**\n * Registers the core subprocess transport on the codex-cli seam, but only\n * when no runner is registered yet — a host or benchmark runner that claimed\n * the seam first always wins. If the seam was cleared afterwards\n * (setCodexCliFallbackRunnerForProcess(undefined)), the core runner is\n * re-registered so the next call still routes. Idempotent.\n */\nexport function ensureCodexSubscriptionRunnerRegistered(deps: CodexSubscriptionRunnerDeps = {}): boolean {\n if (isCodexCliFallbackRunnerRegistered()) return false;\n defaultRegisteredRunner = createCodexSubscriptionRunner(deps);\n setCodexCliFallbackRunnerForProcess(defaultRegisteredRunner);\n coreRunnerRegistered = true;\n return true;\n}\n\n/** True when the process seam still holds the core default runner. */\nexport function isDefaultRegisteredCodexSubscriptionRunner(): boolean {\n return defaultRegisteredRunner !== undefined\n && getCodexCliFallbackRunnerForProcess() === defaultRegisteredRunner;\n}\n/** Host shutdown hook: terminate this runtime's detached Codex children. Does not exit. */\nexport function terminateActiveCodexSubscriptionChildren(\n signal: NodeJS.Signals = \"SIGTERM\",\n runner?: CodexCliFallbackRunner,\n): void {\n const target = runner ?? defaultRegisteredRunner;\n if (!target) return;\n const shutdown = shutdownByRunner.get(target);\n if (shutdown && !shutdown.signal.aborted) {\n shutdown.abort(new DOMException(\"The operation was aborted.\", \"AbortError\"));\n }\n const pids = childrenByRunner.get(target);\n if (!pids) return;\n for (const pid of pids) {\n terminateCodexChildPid(pid, signal);\n }\n}\n\n/** SIGTERM now, SIGKILL after a bound, even if the caller later awaits drain. */\nexport function beginCodexSubscriptionShutdown(\n runner?: CodexCliFallbackRunner,\n forceKillAfterMs = 1_000,\n): () => void {\n terminateActiveCodexSubscriptionChildren(\"SIGTERM\", runner);\n const timer = setTimeout(() => {\n terminateActiveCodexSubscriptionChildren(\"SIGKILL\", runner);\n }, forceKillAfterMs);\n timer.unref();\n return () => {\n clearTimeout(timer);\n terminateActiveCodexSubscriptionChildren(\"SIGKILL\", runner);\n };\n}\nasync function runCodexSubscriptionRequest(\n request: CodexCliFallbackRequest,\n deps: CodexSubscriptionRunnerDeps,\n envSource: NodeJS.ProcessEnv,\n runner: CodexCliFallbackRunner,\n): Promise<CodexCliFallbackResult> {\n const { config } = request;\n assertNoApiKeyConfig(config);\n const executable = resolveExecutable(config, envSource);\n const env = buildIsolatedEnv(envSource);\n\n const providerTimeoutMs = config.retryOptions?.timeoutMs !== undefined\n ? normalizeCodexCliTimeoutMs(config.retryOptions.timeoutMs)\n : undefined;\n const timeoutMs = request.options.timeoutMs ?? providerTimeoutMs ?? DEFAULT_TIMEOUT_MS;\n // The effective deadline starts BEFORE the login-status precheck: login\n // consumes the same call/provider timeout budget, it is not additive.\n const now = deps.now ?? Date.now;\n const deadlineStartedAt = now();\n if (request.options.signal?.aborted) {\n throw abortErrorOf(request.options.signal);\n }\n await assertSubscriptionLogin(executable, env, deps, {\n runner,\n callerTimeoutMs: timeoutMs,\n deadlineStartedAt,\n signal: request.options.signal,\n });\n\n if (request.options.signal?.aborted) {\n throw abortErrorOf(request.options.signal);\n }\n\n const remainingTimeoutMs = timeoutMs - (now() - deadlineStartedAt);\n if (remainingTimeoutMs <= 0) {\n throw new CodexSubscriptionTimeoutError(timeoutMs);\n }\n let tempDir: string | undefined;\n try {\n tempDir = await mkdtemp(path.join(deps.tmpdir?.() ?? os.tmpdir(), \"remnic-codex-sub-\"));\n const workspacePath = path.join(tempDir, \"workspace\");\n const outputPath = path.join(tempDir, \"last-message.txt\");\n await mkdir(workspacePath, { recursive: true });\n\n const runCodexExec = deps.runCodexExec!;\n const result = await runCodexExec({\n executable,\n args: buildExecArgs(request.modelId, config, workspacePath, outputPath),\n input: buildPrompt(request.messages),\n env,\n outputPath,\n workspacePath,\n timeoutMs: remainingTimeoutMs,\n signal: request.options.signal,\n });\n\n if (result.status !== 0) {\n const failure = execFailureError(result, remainingTimeoutMs, executable, env);\n if (failure instanceof CodexSubscriptionTimeoutError) {\n throw failure;\n }\n if (request.options.signal?.aborted) {\n throw abortErrorOf(request.options.signal);\n }\n throw failure;\n }\n if (request.options.signal?.aborted) {\n throw abortErrorOf(request.options.signal);\n }\n\n const content = result.outputText.trim();\n if (content.length === 0) {\n throw new Error(\n `codex-subscription: codex exec returned no final message (${summarizeOutput(result.stderr, result.stdout)})`\n );\n }\n return { content, ...usageFrom(result) };\n } finally {\n if (tempDir) {\n await rm(tempDir, { force: true, recursive: true }).catch(() => {});\n }\n }\n}\n\n/**\n * This provider authenticates exclusively through the codex CLI login, so a\n * configured apiKey is a configuration mistake — reject it without echoing\n * the value.\n */\nexport function assertNoApiKeyConfig(config: CodexCliFallbackConfig): void {\n if (config.apiKey !== undefined && config.apiKey !== \"\") {\n throw new CodexSubscriptionConfigError(\n `${CODEX_SUBSCRIPTION_PROVIDER_ID} does not accept apiKey configuration: it authenticates through the Codex CLI login. Remove the apiKey field and run \\`codex login\\` with a ChatGPT account instead.`\n );\n }\n}\n\nfunction resolveExecutable(config: CodexCliFallbackConfig, env: NodeJS.ProcessEnv): string {\n const configured = config.codexCliExecutable ?? config.executable ?? env[CODEX_EXECUTABLE_ENV] ?? \"codex\";\n const expanded = expandTildePath(String(configured).trim());\n if (expanded.trim().length === 0) {\n throw new CodexSubscriptionConfigError(`${CODEX_EXECUTABLE_ENV} / executable must not be empty`);\n }\n // The exec child runs with cwd = the temp workspace, and spawn resolves a\n // relative executable against the CHILD cwd. Resolve relative paths against\n // the original process cwd now so `./codex` stays valid; bare names keep\n // PATH lookup.\n if (expanded.includes(\"/\") || expanded.includes(\"\\\\\")) {\n return path.resolve(expanded);\n }\n return expanded;\n}\n\nfunction buildIsolatedEnv(source: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const env: NodeJS.ProcessEnv = {};\n for (const [key, value] of Object.entries(source)) {\n if (value !== undefined && isAllowedEnvKey(key)) {\n env[key] = PATH_BEARING_ENV_KEYS[key.toUpperCase()] === true\n ? normalizePathEnvValue(value)\n : value;\n }\n }\n return env;\n}\n\n/**\n * The exec child runs with cwd = the ephemeral workspace while the login\n * child runs with cwd = this process, so a relative HOME/CODEX_HOME would\n * resolve differently per child. Anchor both to the original process cwd.\n */\nfunction normalizePathEnvValue(value: string): string {\n const trimmed = value.trim();\n if (trimmed.length === 0) {\n return value;\n }\n const expanded = expandTildePath(trimmed);\n return path.isAbsolute(expanded) ? expanded : path.resolve(expanded);\n}\nfunction isAllowedEnvKey(key: string): boolean {\n const normalized = key.toUpperCase();\n return CODEX_RUNTIME_ENV_ALLOWLIST[normalized] === true || normalized.startsWith(\"LC_\");\n}\n\ninterface LoginCheckContext {\n runner: CodexCliFallbackRunner;\n /** The caller's overall effective deadline (login + exec). */\n callerTimeoutMs: number;\n deadlineStartedAt: number;\n signal?: AbortSignal;\n}\n\n/**\n * Verifies the operator's Codex subscription login via `codex login status`.\n * Success is cached briefly; failures are never cached so a re-login takes\n * effect on the next request. A cached success is also invalidated when the\n * auth store changes on disk (e.g. another process switches the same Codex\n * home from a ChatGPT login to an API key), so the cache can never mask a\n * later non-subscription login mode.\n */\nasync function assertSubscriptionLogin(\n executable: string,\n env: NodeJS.ProcessEnv,\n deps: CodexSubscriptionRunnerDeps,\n ctx: LoginCheckContext\n): Promise<void> {\n const now = deps.now ?? Date.now;\n const cacheKey = loginCacheKey(executable, env);\n const inflight = inFlightLoginsFor(ctx.runner).get(cacheKey);\n if (inflight && now() - inflight.at < LOGIN_STATUS_CACHE_TTL_MS) {\n await waitForLoginEntry(inflight, cacheKey, ctx, now);\n return;\n }\n const cached = loginStatusCache.get(cacheKey);\n if (cached && now() - cached.at < LOGIN_STATUS_CACHE_TTL_MS) {\n if (!cached.settled || (await authStoreFingerprint(env)) === cached.fingerprint) {\n await waitForLoginEntry(cached, cacheKey, ctx, now);\n return;\n }\n if (loginStatusCache.get(cacheKey) === cached) {\n loginStatusCache.delete(cacheKey);\n }\n }\n const raced = inFlightLoginsFor(ctx.runner).get(cacheKey);\n if (raced && now() - raced.at < LOGIN_STATUS_CACHE_TTL_MS) {\n await waitForLoginEntry(raced, cacheKey, ctx, now);\n return;\n }\n const published = loginStatusCache.get(cacheKey);\n if (published && now() - published.at < LOGIN_STATUS_CACHE_TTL_MS) {\n await waitForLoginEntry(published, cacheKey, ctx, now);\n return;\n }\n if (ctx.signal?.aborted) {\n throw abortErrorOf(ctx.signal);\n }\n const entry: LoginStatusCacheEntry = {\n at: now(),\n fingerprint: null,\n waiters: 0,\n settled: false,\n controller: new AbortController(),\n promise: Promise.resolve(undefined),\n };\n entry.promise = runLoginStatusCheck(executable, env, deps, entry);\n entry.promise.then(\n () => {\n entry.settled = true;\n loginStatusCache.set(cacheKey, entry);\n dropInFlightLogin(ctx.runner, cacheKey, entry);\n },\n () => {\n entry.settled = true;\n dropInFlightLogin(ctx.runner, cacheKey, entry);\n }\n );\n inFlightLoginsFor(ctx.runner).set(cacheKey, entry);\n await waitForLoginEntry(entry, cacheKey, ctx, now);\n}\n\nasync function runLoginStatusCheck(\n executable: string,\n env: NodeJS.ProcessEnv,\n deps: CodexSubscriptionRunnerDeps,\n entry: LoginStatusCacheEntry\n): Promise<void> {\n const runLoginStatus = deps.runLoginStatus!;\n const result = await runLoginStatus(executable, env, LOGIN_STATUS_TIMEOUT_MS, entry.controller.signal);\n const output = `${result.stdout}\\n${result.stderr}`.trim();\n if (TIMEOUT_PATTERN.test(output)) {\n // A login-status subprocess timeout is a deadline expiry, not an auth\n // failure — never report it as \"unauthenticated\".\n throw new CodexSubscriptionTimeoutError(LOGIN_STATUS_TIMEOUT_MS);\n }\n if (result.status === 0 && LOGIN_OK_PATTERN.test(output)) {\n entry.fingerprint = await authStoreFingerprint(env);\n return;\n }\n const apiKeyNote = LOGIN_API_KEY_PATTERN.test(output)\n ? \" The CLI currently reports an API-key login; subscription extraction needs a ChatGPT login.\"\n : \"\";\n throw new CodexSubscriptionAuthError(\n \"unauthenticated\",\n `codex-subscription: no ChatGPT-backed Codex login found. Run \\`codex login\\` and choose the ChatGPT account option, then retry.${apiKeyNote}`\n );\n}\n\n/**\n * Waits on a shared login check with this caller's own budget. A deadline or\n * caller abort rejects immediately — without cancelling the shared check\n * while other callers still wait on it. When the LAST waiter leaves an\n * in-flight check, the subprocess is aborted and the entry dropped so a later\n * caller starts a fresh check.\n */\nasync function waitForLoginEntry(\n entry: LoginStatusCacheEntry,\n cacheKey: string,\n ctx: LoginCheckContext,\n now: () => number\n): Promise<void> {\n const remainingMs = ctx.callerTimeoutMs - (now() - ctx.deadlineStartedAt);\n if (remainingMs <= 0) {\n throw new CodexSubscriptionTimeoutError(ctx.callerTimeoutMs);\n }\n const signal = ctx.signal;\n let rejectOnAbort!: (reason?: unknown) => void;\n const abortWait = new Promise<never>((_resolve, reject) => {\n rejectOnAbort = reject;\n });\n // Identity matters: the same reference is removed in the finally below.\n const onAbort = (): void => {\n if (signal === undefined) return;\n rejectOnAbort(abortErrorOf(signal));\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n entry.waiters++;\n // The deadline timer intentionally holds the event loop: this caller's\n // await is backed by nothing else while the shared check is in flight.\n let deadlineTimer: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n entry.promise,\n abortWait,\n new Promise<never>((_resolve, reject) => {\n deadlineTimer = setTimeout(\n () => reject(new CodexSubscriptionTimeoutError(ctx.callerTimeoutMs)),\n remainingMs\n );\n }),\n ]);\n } catch (err) {\n if (signal?.aborted) {\n throw abortErrorOf(signal);\n }\n throw err;\n } finally {\n clearTimeout(deadlineTimer);\n signal?.removeEventListener(\"abort\", onAbort);\n entry.waiters--;\n if (entry.waiters <= 0 && !entry.settled) {\n entry.controller.abort();\n dropInFlightLogin(ctx.runner, cacheKey, entry);\n if (loginStatusCache.get(cacheKey) === entry) {\n loginStatusCache.delete(cacheKey);\n }\n }\n }\n}\n\n/**\n * `mtimeMs:size` of the Codex auth store, read as metadata only — the\n * provider never reads the store's contents. A change between the cached\n * check and now invalidates the cached login mode.\n */\nasync function authStoreFingerprint(env: NodeJS.ProcessEnv): Promise<string | null> {\n const home = resolveCodexAuthHome(env);\n if (!home) {\n return null;\n }\n try {\n const stats = await stat(path.join(home, \"auth.json\"));\n return `${stats.mtimeMs}:${stats.size}`;\n } catch {\n return null;\n }\n}\n\nfunction resolveCodexAuthHome(env: NodeJS.ProcessEnv): string | undefined {\n if (env.CODEX_HOME) return env.CODEX_HOME;\n const profile = env.HOME ?? env.USERPROFILE;\n return profile ? path.join(profile, \".codex\") : undefined;\n}\n\nfunction loginCacheKey(executable: string, env: NodeJS.ProcessEnv): string {\n return `${executable}\\0${resolveCodexAuthHome(env) ?? \"\"}`;\n}\n\nfunction inFlightLoginsFor(runner: CodexCliFallbackRunner): Map<string, LoginStatusCacheEntry> {\n let map = inFlightLoginByRunner.get(runner);\n if (!map) {\n map = new Map();\n inFlightLoginByRunner.set(runner, map);\n }\n return map;\n}\n\nfunction dropInFlightLogin(\n runner: CodexCliFallbackRunner,\n cacheKey: string,\n entry: LoginStatusCacheEntry,\n): void {\n const map = inFlightLoginByRunner.get(runner);\n if (map?.get(cacheKey) === entry) map.delete(cacheKey);\n}\n\n/**\n * Args mirror the bench provider: fully sandboxed, ephemeral, no tools/hooks/\n * plugins/memories — extraction must behave as a plain completion endpoint.\n */\nfunction buildExecArgs(\n modelId: string,\n config: CodexCliFallbackConfig,\n workspacePath: string,\n outputPath: string\n): string[] {\n const reasoningEffort = readReasoningEffort(config) ?? DEFAULT_REASONING_EFFORT;\n return [\n \"exec\",\n \"--strict-config\",\n \"--model\",\n modelId,\n \"--config\",\n `model_reasoning_effort=${JSON.stringify(reasoningEffort)}`,\n \"--config\",\n 'approval_policy=\"never\"',\n \"--config\",\n 'web_search=\"disabled\"',\n \"--disable\",\n \"hooks\",\n \"--disable\",\n \"shell_tool\",\n \"--disable\",\n \"unified_exec\",\n \"--disable\",\n \"apps\",\n \"--disable\",\n \"plugins\",\n \"--disable\",\n \"remote_plugin\",\n \"--disable\",\n \"multi_agent\",\n \"--disable\",\n \"browser_use\",\n \"--disable\",\n \"browser_use_external\",\n \"--disable\",\n \"computer_use\",\n \"--disable\",\n \"image_generation\",\n \"--disable\",\n \"in_app_browser\",\n \"--disable\",\n \"goals\",\n \"--disable\",\n \"memories\",\n \"--disable\",\n \"chronicle\",\n \"--disable\",\n \"tool_suggest\",\n \"--disable\",\n \"workspace_dependencies\",\n \"--disable\",\n \"shell_snapshot\",\n \"--ephemeral\",\n \"--ignore-user-config\",\n \"--ignore-rules\",\n \"--sandbox\",\n \"read-only\",\n \"--cd\",\n workspacePath,\n \"--skip-git-repo-check\",\n \"--json\",\n \"--output-last-message\",\n outputPath,\n \"-\",\n ];\n}\n\nfunction readReasoningEffort(config: CodexCliFallbackConfig): CodexCliReasoningEffort | undefined {\n for (const value of [config.codexCliReasoningEffort, config.reasoningEffort]) {\n if (typeof value === \"string\") {\n const normalized = value.trim().toLowerCase();\n if (normalized === \"low\" || normalized === \"medium\" || normalized === \"high\" || normalized === \"xhigh\") {\n return normalized;\n }\n throw new CodexSubscriptionConfigError(\n \"codex-subscription reasoningEffort must be one of low, medium, high, xhigh (got unrecognized value)\"\n );\n }\n }\n return undefined;\n}\n\n/**\n * One JSON object per message: role boundaries are structural (JSON string\n * escaping), so literal `[system]`/role-marker text inside message content\n * can never forge another role's turn. Content stays model-visible verbatim.\n */\nfunction buildPrompt(messages: readonly CodexCliFallbackMessage[]): string {\n const transcript = messages\n .map((message) => JSON.stringify({ role: message.role, content: message.content }))\n .join(\"\\n\");\n return [\n \"You are acting as an LLM completion endpoint for a memory-extraction pipeline, not as a coding agent.\",\n \"Answer the request in the transcript below. Do not inspect files, run commands, browse, or use tools.\",\n \"Return only the final answer text. If the request asks for JSON, return raw JSON only.\",\n \"\",\n 'TRANSCRIPT (JSON Lines: one {\"role\":\"...\",\"content\":\"...\"} object per message; newlines inside content are escaped):',\n transcript,\n ].join(\"\\n\");\n}\n\nfunction execFailureError(\n result: CodexSubscriptionExecResult,\n timeoutMs: number,\n executable: string,\n env: NodeJS.ProcessEnv\n): Error {\n const combined = `${result.stderr}\\n${result.stdout}`;\n // The authoritative timeout marker wins over auth-pattern text: a timed-out\n // exec may have already printed model/diagnostic output containing 401/403\n // before the deadline fired (issue #2833).\n if (TIMEOUT_PATTERN.test(combined)) {\n return new CodexSubscriptionTimeoutError(timeoutMs);\n }\n if (AUTH_FAILURE_PATTERN.test(combined)) {\n // Re-check login on the next request; the cached status is now stale.\n loginStatusCache.delete(loginCacheKey(executable, env));\n return new CodexSubscriptionAuthError(\n \"expired_or_revoked\",\n \"codex-subscription: the Codex CLI rejected the request as unauthenticated \" +\n \"(session expired or revoked). Run `codex login` again to re-authenticate, then retry.\"\n );\n }\n\n const exitLabel = result.signal ? `signal ${result.signal}` : `exit ${result.status ?? \"unknown\"}`;\n return new Error(\n `codex-subscription: codex exec failed (${exitLabel}): ${summarizeOutput(result.stderr, result.stdout)}`\n );\n}\n\n/** Secret-redacted, then bounded tail of child output — the only child text\n * that ever reaches a thrown error. Redaction runs BEFORE bounding so a\n * secret straddling the cutoff cannot survive as an unmatchable fragment. */\nfunction summarizeOutput(stderr: string, stdout: string): string {\n const summary = [stderr.trim(), stdout.trim()].filter((part) => part.length > 0).join(\"\\n\");\n if (summary.length === 0) {\n return \"no process output\";\n }\n return redactSecretEchoes(summary).slice(-OUTPUT_SUMMARY_LIMIT);\n}\n\nexport function redactSecretEchoes(value: string): string {\n let redacted = value;\n for (const pattern of SECRET_ECHO_PATTERNS) {\n redacted = redacted.replace(pattern, \"[redacted]\");\n }\n return redacted;\n}\ntype CodexSubscriptionUsage = Pick<CodexCliFallbackResult, \"usage\">;\n\nfunction usageFrom(result: CodexSubscriptionExecResult): CodexSubscriptionUsage {\n const usage = parseCodexJsonlUsage(`${result.stdout}\\n${result.stderr}`);\n if (!usage) {\n return {};\n }\n return {\n usage: {\n inputTokens: usage.inputTokens,\n outputTokens: usage.outputTokens,\n totalTokens: usage.inputTokens + usage.outputTokens,\n },\n };\n}\n\nexport function parseCodexJsonlUsage(output: string): { inputTokens: number; outputTokens: number } | undefined {\n let usage: { inputTokens: number; outputTokens: number } | undefined;\n for (const line of output.split(/\\r?\\n/)) {\n const trimmed = line.trim();\n if (!trimmed.startsWith(\"{\")) continue;\n try {\n const event = JSON.parse(trimmed) as {\n type?: unknown;\n usage?: Record<string, unknown>;\n };\n if (event.type !== \"turn.completed\" || !event.usage) continue;\n const inputTokens = readCounter(event.usage.input_tokens);\n const outputTokens = readCounter(event.usage.output_tokens);\n if (inputTokens !== undefined && outputTokens !== undefined) {\n usage = { inputTokens, outputTokens };\n }\n } catch {\n // codex exec prints non-JSON status text alongside JSONL; ignore it\n }\n }\n return usage;\n}\n\nfunction readCounter(value: unknown): number | undefined {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < 0) {\n return undefined;\n }\n return value;\n}\n\nfunction abortErrorOf(signal: AbortSignal): Error {\n if (signal.reason instanceof CodexSubscriptionTimeoutError) return signal.reason;\n const reason =\n signal.reason instanceof Error\n ? signal.reason\n : signal.reason !== undefined\n ? new Error(String(signal.reason))\n : new DOMException(\"The operation was aborted.\", \"AbortError\");\n const match = /fallback LLM timed out after (\\d+)ms/i.exec(reason.message);\n if (match) {\n return new CodexSubscriptionTimeoutError(Number(match[1]));\n }\n return reason;\n}\n\n/** Bounds streamed child output to STDIO_LIMIT, keeping the TAIL — codex\n * prints its final error or turn.completed result last. Secrets are redacted\n * BEFORE bounding so one straddling the cutoff cannot leak a fragment. */\nfunction appendBounded(existing: string, next: string): string {\n const redacted = redactSecretEchoes(existing + next);\n return redacted.length > STDIO_LIMIT ? redacted.slice(-STDIO_LIMIT) : redacted;\n}\n\nasync function runLoginStatusSubprocess(\n executable: string,\n env: NodeJS.ProcessEnv,\n timeoutMs: number,\n signal: AbortSignal | undefined,\n children: Set<number>,\n): Promise<{ status: number | null; stdout: string; stderr: string }> {\n return await runSubprocess(executable, [\"login\", \"status\"], {\n env,\n stdin: undefined,\n timeoutMs,\n timeoutLabel: \"login status\",\n signal,\n children,\n });\n}\n\nasync function runCodexExecSubprocess(\n request: CodexSubscriptionExecRequest,\n children: Set<number>,\n): Promise<CodexSubscriptionExecResult> {\n const result = await runSubprocess(request.executable, request.args, {\n env: request.env,\n stdin: request.input,\n timeoutMs: request.timeoutMs,\n timeoutLabel: \"exec\",\n signal: request.signal,\n cwd: request.workspacePath,\n children,\n });\n if (result.status === 124) return { ...result, outputText: \"\" };\n let outputText = \"\";\n try {\n outputText = (await readFile(request.outputPath, \"utf8\")).trim();\n } catch {\n // Missing output file surfaces as the no-final-message error path.\n }\n return { ...result, outputText };\n}\n\ninterface SubprocessOptions {\n env: NodeJS.ProcessEnv;\n stdin?: string;\n timeoutMs?: number;\n timeoutLabel: string;\n signal?: AbortSignal;\n cwd?: string;\n children: Set<number>;\n}\n\nasync function runSubprocess(executable: string, args: string[], options: SubprocessOptions): Promise<CommandOutput> {\n return await new Promise<CommandOutput>((resolve, reject) => {\n if (options.signal?.aborted) {\n reject(abortErrorOf(options.signal));\n return;\n }\n const child = launchProcess(executable, args, {\n ...(options.cwd ? { cwd: options.cwd } : {}),\n env: options.env,\n stdio: [options.stdin === undefined ? \"ignore\" : \"pipe\", \"pipe\", \"pipe\"],\n detached: process.platform !== \"win32\",\n windowsHide: true,\n });\n registerActiveCodexChild(child.pid, options.children);\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n let settled = false;\n let killTimeout: ReturnType<typeof setTimeout> | undefined;\n const clearKillTimeout = (): void => {\n if (killTimeout) {\n clearTimeout(killTimeout);\n killTimeout = undefined;\n }\n };\n const terminate = (signal: NodeJS.Signals): void => {\n if (child.pid && process.platform !== \"win32\") {\n try {\n process.kill(-child.pid, signal);\n return;\n } catch {\n // fall through to killing the direct child\n }\n }\n child.kill(signal);\n };\n const scheduleForcedKill = (): void => {\n clearKillTimeout();\n killTimeout = setTimeout(() => terminate(\"SIGKILL\"), 1_000);\n killTimeout.unref();\n };\n const finish = (fn: () => void): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timeout);\n options.signal?.removeEventListener(\"abort\", onAbort);\n fn();\n };\n const settleTimeout = (): void => {\n timedOut = true;\n stderr = appendBounded(\n stderr,\n `\\ncodex-subscription: ${options.timeoutLabel} timed out after ${options.timeoutMs}ms.`\n );\n finish(() => {\n resolve({\n status: 124,\n signal: \"SIGTERM\",\n stdout,\n stderr,\n });\n });\n };\n const onAbort = (): void => {\n const reasonText =\n options.signal?.reason instanceof Error\n ? options.signal.reason.message\n : String(options.signal?.reason ?? \"\");\n terminate(\"SIGTERM\");\n scheduleForcedKill();\n if (/fallback LLM timed out after \\d+ms/i.test(reasonText)) {\n settleTimeout();\n return;\n }\n finish(() => reject(abortErrorOf(options.signal!)));\n };\n options.signal?.addEventListener(\"abort\", onAbort, { once: true });\n const timeout = options.timeoutMs\n ? setTimeout(() => {\n terminate(\"SIGTERM\");\n scheduleForcedKill();\n settleTimeout();\n }, options.timeoutMs)\n : undefined;\n timeout?.unref();\n child.stdout?.setEncoding(\"utf8\");\n child.stderr?.setEncoding(\"utf8\");\n child.stdout?.on(\"data\", (chunk: string) => {\n stdout = appendBounded(stdout, chunk);\n });\n child.stderr?.on(\"data\", (chunk: string) => {\n stderr = appendBounded(stderr, chunk);\n });\n child.stdin?.on(\"error\", (error: NodeJS.ErrnoException) => {\n stderr = appendBounded(stderr, `\\ncodex-subscription: stdin error: ${error.code ?? error.message}`);\n });\n child.on(\"error\", (error) => {\n unregisterActiveCodexChild(child.pid, options.children);\n finish(() => {\n reject(\n child.pid\n ? new Error(`codex-subscription: codex CLI failed after start: ${safeMessage(error)}`, { cause: error })\n : new CodexSubscriptionAuthError(\n \"unauthenticated\",\n `codex-subscription: codex CLI not found at \\`${executable}\\` — install the Codex CLI and run \\`codex login\\` with a ChatGPT account, then retry.`\n )\n );\n });\n });\n child.on(\"close\", (status, signal) => {\n clearKillTimeout();\n unregisterActiveCodexChild(child.pid, options.children);\n finish(() => {\n resolve({\n status: timedOut ? (status === null || status === 0 ? 124 : status) : status,\n signal: timedOut ? (signal ?? \"SIGTERM\") : signal,\n stdout,\n stderr,\n });\n });\n });\n if (options.stdin !== undefined) {\n try {\n child.stdin?.end(options.stdin);\n } catch (error) {\n log.debug(`codex-subscription: failed writing prompt to stdin: ${safeMessage(error)}`);\n }\n }\n });\n}\n\nfunction safeMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nexport const __codexSubscriptionTestHooks = {\n activeCodexChildCount: (runner?: CodexCliFallbackRunner): number => {\n const target = runner ?? defaultRegisteredRunner;\n return target ? (childrenByRunner.get(target)?.size ?? 0) : 0;\n },\n appendBounded,\n resetLoginStatusCache: (): void => {\n loginStatusCache.clear();\n },\n isCoreRunnerRegistered: (): boolean => coreRunnerRegistered,\n resetCoreRunnerRegistered: (): void => {\n coreRunnerRegistered = false;\n defaultRegisteredRunner = undefined;\n },\n};\n\nfunction registerActiveCodexChild(pid: number | undefined, children: Set<number>): void {\n if (pid === undefined) return;\n children.add(pid);\n}\n\nfunction unregisterActiveCodexChild(pid: number | undefined, children: Set<number>): void {\n if (pid === undefined) return;\n children.delete(pid);\n}\n\nfunction terminateCodexChildPid(pid: number, signal: NodeJS.Signals): void {\n if (process.platform !== \"win32\") {\n try {\n process.kill(-pid, signal);\n return;\n } catch {\n // Fall back to killing the direct child below.\n }\n }\n\n try {\n process.kill(pid, signal);\n } catch {\n // The child may already have exited.\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAMA,OAAOA,WAAU;;;ACWjB,SAAS,OAAO,SAAS,UAAU,IAAI,YAAY;AACnD,OAAO,QAAQ;AACf,OAAO,UAAU;AAeV,IAAM,iCAAiC;AAG9C,IAAM,uBAAuB;AAE7B,IAAM,2BAAoD;AAC1D,IAAM,qBAAqB;AAC3B,IAAM,0BAA0B;AAChC,IAAM,4BAA4B,KAAK;AACvC,IAAM,cAAc;AACpB,IAAM,uBAAuB;AAM7B,IAAM,wBAAwD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