nexus-agents 8.86.3 → 8.88.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 (131) hide show
  1. package/dist/{ast-rule-runner-USLLC3XL.js → ast-rule-runner-FESCBZGZ.js} +3 -3
  2. package/dist/{child-mcp-config-K563PP6S.js → child-mcp-config-KQA7OCJV.js} +2 -2
  3. package/dist/{chunk-FNL4J77P.js → chunk-2Z4QWGZD.js} +2 -2
  4. package/dist/chunk-2Z4QWGZD.js.map +1 -0
  5. package/dist/{chunk-SX77QPB2.js → chunk-3HRKK3TB.js} +2 -2
  6. package/dist/{chunk-64IJKT4I.js → chunk-56SU2GM2.js} +100 -20
  7. package/dist/chunk-56SU2GM2.js.map +1 -0
  8. package/dist/{chunk-QW6J2UV4.js → chunk-5KCWILZF.js} +5 -5
  9. package/dist/{chunk-T4E72Z3G.js → chunk-67OZBQA6.js} +3 -3
  10. package/dist/{chunk-P6D7S7CY.js → chunk-AV4CN3CJ.js} +2 -2
  11. package/dist/{chunk-NNYVXSQF.js → chunk-BWPBKKEP.js} +2 -2
  12. package/dist/{chunk-EGEI5FK3.js → chunk-C3ZXAGKS.js} +18 -10
  13. package/dist/chunk-C3ZXAGKS.js.map +1 -0
  14. package/dist/{chunk-QCDYJYGB.js → chunk-CII3XR4K.js} +52 -22
  15. package/dist/chunk-CII3XR4K.js.map +1 -0
  16. package/dist/{chunk-GKLTEUFU.js → chunk-CKZQOPTD.js} +2 -2
  17. package/dist/{chunk-XWPZZEBX.js → chunk-D6HCACOH.js} +4 -4
  18. package/dist/{chunk-J6GIJFV4.js → chunk-DOYDWGKY.js} +2 -2
  19. package/dist/{chunk-S6MNVNQB.js → chunk-FDPKOY5E.js} +2 -2
  20. package/dist/{chunk-ZE73MT66.js → chunk-FUSECEOU.js} +4 -4
  21. package/dist/{chunk-OOIZ3IQD.js → chunk-G6HDZ6B7.js} +2 -2
  22. package/dist/{chunk-XFQINKET.js → chunk-GMAA62YN.js} +68 -49
  23. package/dist/{chunk-XFQINKET.js.map → chunk-GMAA62YN.js.map} +1 -1
  24. package/dist/{chunk-V66MMBO4.js → chunk-H2MER5LS.js} +5 -5
  25. package/dist/{chunk-2SQO4FET.js → chunk-JDC252T4.js} +2 -2
  26. package/dist/{chunk-XNNNDQLK.js → chunk-LVMAPILY.js} +2 -2
  27. package/dist/{chunk-CBZAMHBA.js → chunk-NXWC7OLE.js} +2 -2
  28. package/dist/{chunk-IXKFIO6O.js → chunk-ON2J7TBZ.js} +2 -2
  29. package/dist/{chunk-KXFPJOPL.js → chunk-PEPOVKYR.js} +2 -2
  30. package/dist/{chunk-EVYZZL7J.js → chunk-PMX3GH6F.js} +2 -2
  31. package/dist/{chunk-Q75P5CVJ.js → chunk-QM4HMMSJ.js} +2 -2
  32. package/dist/{chunk-ZSFRB2S4.js → chunk-STZL32RV.js} +3 -3
  33. package/dist/{chunk-DSVMQVJZ.js → chunk-TMM6ZN2H.js} +4 -4
  34. package/dist/{chunk-3PBPP5TA.js → chunk-TUGETJYE.js} +3 -3
  35. package/dist/{chunk-VIXN77S5.js → chunk-UU2GS25J.js} +9 -9
  36. package/dist/{chunk-KX7A23JM.js → chunk-UVZBOQJZ.js} +2 -2
  37. package/dist/{chunk-YPJRVA2H.js → chunk-W3GYTKPK.js} +4 -4
  38. package/dist/{chunk-O24ENDHN.js → chunk-XSNDGIJR.js} +3 -3
  39. package/dist/{chunk-5U4XTYAB.js → chunk-XX3ESMYC.js} +2 -2
  40. package/dist/{chunk-XARB7ITD.js → chunk-YBQO5XCI.js} +8 -8
  41. package/dist/{cli-circuit-breaker-4ASNTBDP.js → cli-circuit-breaker-FTX357KY.js} +3 -3
  42. package/dist/cli.d.ts +1 -1
  43. package/dist/cli.js +144 -79
  44. package/dist/cli.js.map +1 -1
  45. package/dist/{composite-router-V45AK6WD.js → composite-router-VL7VKVAI.js} +2 -2
  46. package/dist/{consensus-vote-OMUEYZ7Q.js → consensus-vote-NQ7EXVJX.js} +16 -16
  47. package/dist/{consensus-vote-types-DkRs8FbB.d.ts → consensus-vote-types-ptxFNv55.d.ts} +20 -1
  48. package/dist/{context-retriever-NZOSGG6S.js → context-retriever-7T56LVZN.js} +8 -8
  49. package/dist/{doctor-deep-JRY3D7BP.js → doctor-deep-YJWA4BU3.js} +3 -3
  50. package/dist/{doctor-live-NSRHMHMG.js → doctor-live-MWTFQRPQ.js} +10 -10
  51. package/dist/{expert-bridge-Q4SEPVTE.js → expert-bridge-J5IUE2Y5.js} +4 -4
  52. package/dist/{factory-JBK45P7G.js → factory-IUMI3NYA.js} +5 -5
  53. package/dist/{factory-ZV4MR3VM.js → factory-R726DTSS.js} +9 -9
  54. package/dist/{improvement-review-Y6EJPMGU.js → improvement-review-2KWRZHI3.js} +5 -5
  55. package/dist/index.d.ts +31 -2
  56. package/dist/index.js +30 -30
  57. package/dist/{init-opencode-6WGN5J6J.js → init-opencode-IKD4A5XD.js} +5 -5
  58. package/dist/issue-triage-Z2JY62F4.js +16 -0
  59. package/dist/{pr-reviewer-helpers-UMNMOUAO.js → pr-reviewer-helpers-DPI5AGZL.js} +4 -4
  60. package/dist/{registry-command-QRBAKWRK.js → registry-command-UUUUNJ5W.js} +2 -2
  61. package/dist/{repo-security-plan-UM6WX5PN.js → repo-security-plan-N6VXMUAJ.js} +3 -3
  62. package/dist/{research-helpers-synthesize-DUOVXI5V.js → research-helpers-synthesize-AB46YY4W.js} +4 -4
  63. package/dist/{routing-memory-OKYSDPXT.js → routing-memory-6GL2DVPI.js} +2 -2
  64. package/dist/{session-memory-ONUSRMYV.js → session-memory-YBIA3SM5.js} +3 -3
  65. package/dist/{setup-config-BAZRBFN3.js → setup-config-MQZUOBDV.js} +3 -3
  66. package/dist/{setup-custom-api-LSMLWGKW.js → setup-custom-api-KHT7K6V3.js} +4 -4
  67. package/dist/setup-data-dir-5N43EHFC.js +32 -0
  68. package/dist/{tool-memory-Q5UWNVN3.js → tool-memory-R22BAPWZ.js} +5 -5
  69. package/dist/{unified-registry-Y327PN6R.js → unified-registry-V5N44N4X.js} +10 -10
  70. package/dist/{weather-report-C2VIAC2Q.js → weather-report-3EPVTET2.js} +2 -2
  71. package/package.json +1 -1
  72. package/dist/chunk-64IJKT4I.js.map +0 -1
  73. package/dist/chunk-EGEI5FK3.js.map +0 -1
  74. package/dist/chunk-FNL4J77P.js.map +0 -1
  75. package/dist/chunk-QCDYJYGB.js.map +0 -1
  76. package/dist/issue-triage-XVDXOZRW.js +0 -16
  77. package/dist/setup-data-dir-IH3KUCZU.js +0 -32
  78. /package/dist/{ast-rule-runner-USLLC3XL.js.map → ast-rule-runner-FESCBZGZ.js.map} +0 -0
  79. /package/dist/{child-mcp-config-K563PP6S.js.map → child-mcp-config-KQA7OCJV.js.map} +0 -0
  80. /package/dist/{chunk-SX77QPB2.js.map → chunk-3HRKK3TB.js.map} +0 -0
  81. /package/dist/{chunk-QW6J2UV4.js.map → chunk-5KCWILZF.js.map} +0 -0
  82. /package/dist/{chunk-T4E72Z3G.js.map → chunk-67OZBQA6.js.map} +0 -0
  83. /package/dist/{chunk-P6D7S7CY.js.map → chunk-AV4CN3CJ.js.map} +0 -0
  84. /package/dist/{chunk-NNYVXSQF.js.map → chunk-BWPBKKEP.js.map} +0 -0
  85. /package/dist/{chunk-GKLTEUFU.js.map → chunk-CKZQOPTD.js.map} +0 -0
  86. /package/dist/{chunk-XWPZZEBX.js.map → chunk-D6HCACOH.js.map} +0 -0
  87. /package/dist/{chunk-J6GIJFV4.js.map → chunk-DOYDWGKY.js.map} +0 -0
  88. /package/dist/{chunk-S6MNVNQB.js.map → chunk-FDPKOY5E.js.map} +0 -0
  89. /package/dist/{chunk-ZE73MT66.js.map → chunk-FUSECEOU.js.map} +0 -0
  90. /package/dist/{chunk-OOIZ3IQD.js.map → chunk-G6HDZ6B7.js.map} +0 -0
  91. /package/dist/{chunk-V66MMBO4.js.map → chunk-H2MER5LS.js.map} +0 -0
  92. /package/dist/{chunk-2SQO4FET.js.map → chunk-JDC252T4.js.map} +0 -0
  93. /package/dist/{chunk-XNNNDQLK.js.map → chunk-LVMAPILY.js.map} +0 -0
  94. /package/dist/{chunk-CBZAMHBA.js.map → chunk-NXWC7OLE.js.map} +0 -0
  95. /package/dist/{chunk-IXKFIO6O.js.map → chunk-ON2J7TBZ.js.map} +0 -0
  96. /package/dist/{chunk-KXFPJOPL.js.map → chunk-PEPOVKYR.js.map} +0 -0
  97. /package/dist/{chunk-EVYZZL7J.js.map → chunk-PMX3GH6F.js.map} +0 -0
  98. /package/dist/{chunk-Q75P5CVJ.js.map → chunk-QM4HMMSJ.js.map} +0 -0
  99. /package/dist/{chunk-ZSFRB2S4.js.map → chunk-STZL32RV.js.map} +0 -0
  100. /package/dist/{chunk-DSVMQVJZ.js.map → chunk-TMM6ZN2H.js.map} +0 -0
  101. /package/dist/{chunk-3PBPP5TA.js.map → chunk-TUGETJYE.js.map} +0 -0
  102. /package/dist/{chunk-VIXN77S5.js.map → chunk-UU2GS25J.js.map} +0 -0
  103. /package/dist/{chunk-KX7A23JM.js.map → chunk-UVZBOQJZ.js.map} +0 -0
  104. /package/dist/{chunk-YPJRVA2H.js.map → chunk-W3GYTKPK.js.map} +0 -0
  105. /package/dist/{chunk-O24ENDHN.js.map → chunk-XSNDGIJR.js.map} +0 -0
  106. /package/dist/{chunk-5U4XTYAB.js.map → chunk-XX3ESMYC.js.map} +0 -0
  107. /package/dist/{chunk-XARB7ITD.js.map → chunk-YBQO5XCI.js.map} +0 -0
  108. /package/dist/{cli-circuit-breaker-4ASNTBDP.js.map → cli-circuit-breaker-FTX357KY.js.map} +0 -0
  109. /package/dist/{composite-router-V45AK6WD.js.map → composite-router-VL7VKVAI.js.map} +0 -0
  110. /package/dist/{consensus-vote-OMUEYZ7Q.js.map → consensus-vote-NQ7EXVJX.js.map} +0 -0
  111. /package/dist/{context-retriever-NZOSGG6S.js.map → context-retriever-7T56LVZN.js.map} +0 -0
  112. /package/dist/{doctor-deep-JRY3D7BP.js.map → doctor-deep-YJWA4BU3.js.map} +0 -0
  113. /package/dist/{doctor-live-NSRHMHMG.js.map → doctor-live-MWTFQRPQ.js.map} +0 -0
  114. /package/dist/{expert-bridge-Q4SEPVTE.js.map → expert-bridge-J5IUE2Y5.js.map} +0 -0
  115. /package/dist/{factory-JBK45P7G.js.map → factory-IUMI3NYA.js.map} +0 -0
  116. /package/dist/{factory-ZV4MR3VM.js.map → factory-R726DTSS.js.map} +0 -0
  117. /package/dist/{improvement-review-Y6EJPMGU.js.map → improvement-review-2KWRZHI3.js.map} +0 -0
  118. /package/dist/{init-opencode-6WGN5J6J.js.map → init-opencode-IKD4A5XD.js.map} +0 -0
  119. /package/dist/{issue-triage-XVDXOZRW.js.map → issue-triage-Z2JY62F4.js.map} +0 -0
  120. /package/dist/{pr-reviewer-helpers-UMNMOUAO.js.map → pr-reviewer-helpers-DPI5AGZL.js.map} +0 -0
  121. /package/dist/{registry-command-QRBAKWRK.js.map → registry-command-UUUUNJ5W.js.map} +0 -0
  122. /package/dist/{repo-security-plan-UM6WX5PN.js.map → repo-security-plan-N6VXMUAJ.js.map} +0 -0
  123. /package/dist/{research-helpers-synthesize-DUOVXI5V.js.map → research-helpers-synthesize-AB46YY4W.js.map} +0 -0
  124. /package/dist/{routing-memory-OKYSDPXT.js.map → routing-memory-6GL2DVPI.js.map} +0 -0
  125. /package/dist/{session-memory-ONUSRMYV.js.map → session-memory-YBIA3SM5.js.map} +0 -0
  126. /package/dist/{setup-config-BAZRBFN3.js.map → setup-config-MQZUOBDV.js.map} +0 -0
  127. /package/dist/{setup-custom-api-LSMLWGKW.js.map → setup-custom-api-KHT7K6V3.js.map} +0 -0
  128. /package/dist/{setup-data-dir-IH3KUCZU.js.map → setup-data-dir-5N43EHFC.js.map} +0 -0
  129. /package/dist/{tool-memory-Q5UWNVN3.js.map → tool-memory-R22BAPWZ.js.map} +0 -0
  130. /package/dist/{unified-registry-Y327PN6R.js.map → unified-registry-V5N44N4X.js.map} +0 -0
  131. /package/dist/{weather-report-C2VIAC2Q.js.map → weather-report-3EPVTET2.js.map} +0 -0
@@ -9,8 +9,8 @@ import {
9
9
  getBuiltInAstRulesPath,
10
10
  loadRules,
11
11
  runAstQaRules
12
- } from "./chunk-J6GIJFV4.js";
13
- import "./chunk-64IJKT4I.js";
12
+ } from "./chunk-DOYDWGKY.js";
13
+ import "./chunk-56SU2GM2.js";
14
14
  import "./chunk-RQLIPUQK.js";
15
15
  import "./chunk-RNDHNRSX.js";
16
16
  import "./chunk-PX6F3LHL.js";
@@ -26,4 +26,4 @@ export {
26
26
  loadRules,
27
27
  runAstQaRules
28
28
  };
29
- //# sourceMappingURL=ast-rule-runner-USLLC3XL.js.map
29
+ //# sourceMappingURL=ast-rule-runner-FESCBZGZ.js.map
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-HERI7LXN.js";
4
4
  import {
5
5
  createLogger
6
- } from "./chunk-64IJKT4I.js";
6
+ } from "./chunk-56SU2GM2.js";
7
7
  import "./chunk-RQLIPUQK.js";
8
8
  import "./chunk-RNDHNRSX.js";
9
9
  import "./chunk-PX6F3LHL.js";
@@ -56,4 +56,4 @@ async function generateMcpConfig(options) {
56
56
  export {
57
57
  generateMcpConfig
58
58
  };
59
- //# sourceMappingURL=child-mcp-config-K563PP6S.js.map
59
+ //# sourceMappingURL=child-mcp-config-KQA7OCJV.js.map
@@ -13,7 +13,7 @@ import {
13
13
  lookupInTreeCapability,
14
14
  ok,
15
15
  resolveRetryAfterMs
16
- } from "./chunk-64IJKT4I.js";
16
+ } from "./chunk-56SU2GM2.js";
17
17
 
18
18
  // src/config/model-parameter-support.ts
19
19
  function parseClaudeMajorMinor(bareId) {
@@ -834,4 +834,4 @@ export {
834
834
  DEFAULT_COLLECT_STREAM_MAX_CHUNKS,
835
835
  collectStream
836
836
  };
837
- //# sourceMappingURL=chunk-FNL4J77P.js.map
837
+ //# sourceMappingURL=chunk-2Z4QWGZD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/config/model-parameter-support.ts","../src/config/temperature-support.ts","../src/adapters/optional-params.ts","../src/adapters/base-adapter.ts","../src/adapters/streaming-types.ts","../src/adapters/stream-operators-helpers.ts","../src/adapters/stream-operators.ts","../src/adapters/streaming.ts"],"sourcesContent":["/**\n * nexus-agents/config — data-driven model request-parameter capability resolver\n * (#4067, epic #4066 layer 1).\n *\n * Generalizes the ad-hoc `temperatureUnsupportedForModel` (#4061/#4062) into a\n * registry-first resolver. Two questions every adapter param-builder asks before\n * forwarding a request parameter:\n *\n * 1. Does this model REJECT a given parameter (so the adapter must omit it)?\n * {@link unsupportedParametersForModel} / {@link modelSupportsParameter}.\n * 2. Which max-tokens param name does it expect — `max_tokens` (chat-completions\n * default) or `max_completion_tokens` (OpenAI reasoning models, #4049)?\n * {@link getMaxTokensParamForModel}.\n *\n * RESOLUTION ORDER (each function): (a) registry capability data — the in-tree\n * `ModelCapability.unsupportedParameters` / `.maxTokensParam` looked up via\n * `lookupInTreeCapability`; if present, it WINS; (b) otherwise the regex fallback\n * below, preserving the EXACT logic that lived in `temperature-support.ts` so\n * unregistered ids (Claude 4.7/4.8, bare o-series) keep resolving correctly.\n *\n * Deterministic: a given id (with a stable registry) yields the same result every\n * call. Biased AGAINST false-positive stripping — a missed rejection is a 400\n * outage, a wrongly-stripped param only loses a tuning knob (the same bias the\n * temperature predicate documented). `temperature-support.ts` is now a thin shim\n * over {@link modelSupportsParameter}.\n *\n * @module config/model-parameter-support\n */\n\nimport { lookupInTreeCapability } from './model-config-helpers.js';\n\n// ---------------------------------------------------------------------------\n// Regex fallback internals (moved verbatim from temperature-support.ts, #4061)\n// ---------------------------------------------------------------------------\n\ninterface ClaudeMajorMinor {\n readonly major: number;\n readonly minor: number;\n}\n\n/**\n * Parse the FIRST numeric version from a (provider-prefix-stripped) Claude model\n * id — a major with an OPTIONAL minor, tolerating `-`, `_`, and `.` separators.\n *\n * A trailing snapshot date (`-20250514`, 6+ digits) is stripped FIRST so it cannot\n * be mistaken for a minor: `claude-opus-4-20250514` is Opus **4.0**, not 4.20250514.\n * A bare major with no minor is treated as `.0` (`claude-opus-4` → 4.0,\n * `claude-fable-5` → 5.0). major/minor are kept as separate integers so `4.10`\n * compares ABOVE `4.6` (a `parseFloat` would collapse to 4.1). Returns `null` only\n * when the id carries no version digits at all (e.g. `claude-instant`,\n * `claude-newfamily`).\n */\nfunction parseClaudeMajorMinor(bareId: string): ClaudeMajorMinor | null {\n const undated = bareId.replace(/[-_]\\d{6,}$/, '');\n const match = /(\\d+)(?:[-_.](\\d+))?/.exec(undated);\n if (match === null) return null;\n const major = Number.parseInt(match[1] as string, 10);\n const minor = match[2] !== undefined ? Number.parseInt(match[2], 10) : 0;\n if (Number.isNaN(major) || Number.isNaN(minor)) return null;\n return { major, minor };\n}\n\n/** Recognized LEGACY Claude families that still support `temperature` (pre-4.x). */\nconst LEGACY_TEMPERATURE_SUPPORTING = /claude[-_](?:instant|1|2|3)(?:[-_.]|$)/;\n\n/**\n * Claude branch of the temperature regex fallback (#4061). `bare` is the id\n * sliced from the first `claude` (provider prefix stripped). Unsupported when the\n * version is after Opus 4.6, or the family is unrecognized/non-numbered\n * (`claude-fable-5`, future) — a deliberate SAFE-DROP, since a benign fall-back to\n * the API default beats a 400.\n */\nfunction claudeTemperatureUnsupported(bare: string): boolean {\n const version = parseClaudeMajorMinor(bare);\n if (version !== null) {\n // \"after Opus 4.6\": major > 4, or 4.7+ within the 4.x line.\n return version.major > 4 || (version.major === 4 && version.minor >= 7);\n }\n if (LEGACY_TEMPERATURE_SUPPORTING.test(bare)) return false;\n return true;\n}\n\n/**\n * OpenAI REASONING-model detection (#4062). True ONLY for the reasoning models\n * documented to reject `temperature` and to use `max_completion_tokens`;\n * everything else (gpt-4o, gpt-4, gpt-3.5, gemini, openrouter-*, …) returns false.\n * `id` is the full lower-cased model id.\n *\n * - o-series: `o1`/`o3`/`o3-mini`/`o4-mini` — `o` + digit at the START of the last\n * path segment (so `claude-opus`/`openrouter-*` cannot match).\n * - codex: all current `codex…` routes are GPT-5-reasoning-based.\n * - GPT-5 family: `gpt-5` / `gpt5` (anchored after the `5` so `gpt-50`/`gpt-512`\n * do NOT match) — EXCEPT the non-reasoning `gpt-5-chat` variant.\n */\nfunction openAiReasoning(id: string): boolean {\n const segment = id.includes('/') ? id.slice(id.lastIndexOf('/') + 1) : id;\n if (/^o[0-9]/.test(segment)) return true;\n if (segment.includes('codex')) return true;\n if (/gpt-?5(?![0-9])/.test(segment) && !segment.includes('gpt-5-chat')) return true;\n return false;\n}\n\n/**\n * Regex fallback for whether `modelId` rejects a non-default `temperature`. The\n * EXACT predicate that was `temperatureUnsupportedForModel` before #4067 — Claude\n * after Opus 4.6, OpenAI o-series / GPT-5 family / codex; everything else false.\n * Robust to gateway id variants (provider prefixes, `-`/`_` separators, dated\n * suffixes).\n */\nfunction regexRejectsTemperature(modelId: string): boolean {\n const id = modelId.toLowerCase();\n const claudeAt = id.indexOf('claude');\n if (claudeAt !== -1) {\n return claudeTemperatureUnsupported(id.slice(claudeAt)); // strip provider prefix\n }\n return openAiReasoning(id);\n}\n\n/** Regex fallback for OpenAI-reasoning detection (Claude ids are never reasoning here). */\nfunction regexIsOpenAiReasoning(modelId: string): boolean {\n const id = modelId.toLowerCase();\n if (id.includes('claude')) return false;\n return openAiReasoning(id);\n}\n\n// ---------------------------------------------------------------------------\n// Public resolver API\n// ---------------------------------------------------------------------------\n\n/**\n * Parameters `modelId` REJECTS. Registry capability data first\n * (`ModelCapability.unsupportedParameters`), else the regex fallback for\n * unregistered models (Claude>4.6, OpenAI o-series/codex/gpt-5 reject\n * `'temperature'`; nothing else, for now). Deterministic.\n */\nexport function unsupportedParametersForModel(modelId: string): readonly string[] {\n const cap = lookupInTreeCapability(modelId);\n if (cap?.unsupportedParameters !== undefined) return cap.unsupportedParameters;\n return regexRejectsTemperature(modelId) ? ['temperature'] : [];\n}\n\n/** True iff `modelId` accepts `param`. */\nexport function modelSupportsParameter(modelId: string, param: string): boolean {\n return !unsupportedParametersForModel(modelId).includes(param);\n}\n\n/**\n * The max-tokens param name `modelId` expects: registry `maxTokensParam` first,\n * else regex fallback (OpenAI reasoning → `'max_completion_tokens'`, else\n * `'max_tokens'`).\n */\nexport function getMaxTokensParamForModel(modelId: string): 'max_tokens' | 'max_completion_tokens' {\n const cap = lookupInTreeCapability(modelId);\n if (cap?.maxTokensParam !== undefined) return cap.maxTokensParam;\n return regexIsOpenAiReasoning(modelId) ? 'max_completion_tokens' : 'max_tokens';\n}\n\n// ---------------------------------------------------------------------------\n// Known-incompatibility registry — the drift guard's source of truth (#4070)\n// ---------------------------------------------------------------------------\n\n/**\n * One DOCUMENTED model-parameter incompatibility — a real incident the resolver\n * MUST keep handling. A `param` entry asserts the model rejects that request\n * parameter ({@link modelSupportsParameter} must be false); a `maxTokensParam`\n * entry asserts the max-tokens field name ({@link getMaxTokensParamForModel}).\n */\nexport interface KnownParameterIncompatibility {\n /** A model id that hits the case (registry-encoded OR regex-fallback). */\n readonly modelId: string;\n /** The rejected request parameter (mutually exclusive with `maxTokensParam`). */\n readonly param?: string;\n /** The expected max-tokens field name (mutually exclusive with `param`). */\n readonly maxTokensParam?: 'max_tokens' | 'max_completion_tokens';\n /** The GitHub incident this case locks in, so a reviewer sees WHY it matters. */\n readonly issue: number;\n}\n\n/**\n * The documented model-parameter incompatibilities (#4061/#4062/#4049) as a single\n * declarative, greppable source of truth. The layer-4 drift guard (#4070) asserts\n * every entry against the resolver, so the next param drift — a bumped Claude\n * threshold, an edited regex, a removed `unsupportedParameters` on a registered\n * model — fails CI instead of silently 400-ing in production. Exported so it doubles\n * as documentation and as the anchor the (deferred) provider-reality reconciliation\n * checks against. Spans BOTH the registry data path and the regex fallback path.\n */\nexport const KNOWN_PARAMETER_INCOMPATIBILITIES: readonly KnownParameterIncompatibility[] = [\n // #4061 — Claude after Opus 4.6 rejects a non-1.0 temperature with a 400 (regex fallback; unregistered concrete id).\n { modelId: 'claude-opus-4-8', param: 'temperature', issue: 4061 },\n // #4176 — Claude Fable 5 (frontier) rejects temperature; registry-encoded via `unsupportedParameters` on the in-tree entry (regex fallback also covers it: fable→5.0 > 4.6).\n { modelId: 'claude-fable-5', param: 'temperature', issue: 4176 },\n // #4062 — OpenAI reasoning families reject temperature (o-series/gpt-5 via regex fallback; codex via registry data).\n { modelId: 'o3-mini', param: 'temperature', issue: 4062 },\n { modelId: 'gpt-5', param: 'temperature', issue: 4062 },\n { modelId: 'codex-5.3', param: 'temperature', issue: 4062 },\n // #4176 — GPT-5.5 (frontier reasoning) rejects temperature and expects `max_completion_tokens`; registry-encoded, mirroring codex-5.3.\n { modelId: 'gpt-5.5', param: 'temperature', issue: 4176 },\n { modelId: 'gpt-5.5', maxTokensParam: 'max_completion_tokens', issue: 4176 },\n // #6516 — GPT-5.6 Sol (codex default, gpt-5.5 successor) carries the same registry encoding.\n { modelId: 'gpt-5.6-sol', param: 'temperature', issue: 6516 },\n { modelId: 'gpt-5.6-sol', maxTokensParam: 'max_completion_tokens', issue: 6516 },\n // #4049 — OpenAI reasoning models expect `max_completion_tokens`, not `max_tokens` (codex via registry; o-series via fallback).\n { modelId: 'codex-5.3', maxTokensParam: 'max_completion_tokens', issue: 4049 },\n { modelId: 'o3-mini', maxTokensParam: 'max_completion_tokens', issue: 4049 },\n];\n","/**\n * nexus-agents/config — model `temperature` support (#4061, #4062).\n *\n * Some models reject a custom `temperature` with a hard 400, so both adapters\n * must OMIT the param for them. Two families:\n *\n * 1. Anthropic Claude AFTER Opus 4.6 (#4061). Per the installed `@anthropic-ai/sdk`\n * (messages.d.ts): \"Models released after Claude Opus 4.6 do not support setting\n * temperature. A value of 1.0 will be accepted for backwards compatibility, all\n * other values will be rejected with a 400 error.\"\n * 2. OpenAI REASONING models (#4062): the o-series (o1/o3/o3-mini/o4-mini) reject\n * `temperature` outright (\"Unsupported parameter\"), and the GPT-5 family accepts\n * only the default (\"Only the default (1) value is supported\") — except the\n * non-reasoning `gpt-5-chat` variant. This repo routes codex-5.3→gpt-5.6-terra,\n * codex-5.2→gpt-5.6-luna, codex-5.1-mini→gpt-6-luna (#5091, remapped\n * 2026-09-23), so gateway voters at the default 0.3 400 on all of them. The\n * regex fallback does not match `gpt-6-*`; those slugs are covered by the\n * registry's `unsupportedParameters` data.\n *\n * {@link temperatureUnsupportedForModel} is the single source of truth both the\n * native Claude adapter and the OpenAI-compatible gateway adapter consult before\n * forwarding `temperature`. When it returns true the adapter OMITS the param\n * (value 1.0 is the API default, so omitting is equivalent). It returns FALSE for\n * every model NOT known to reject temperature (gpt-4o, gpt-4, gemini, …), biasing\n * AGAINST false-positive stripping — a false negative is a 400, a false positive\n * only loses the consistency setting.\n *\n * As of #4067 the predicate is a THIN SHIM over the data-driven resolver in\n * `model-parameter-support.ts` (registry `unsupportedParameters` first, then the\n * same regex fallback that used to live here). The three adapter call sites and\n * the `warnTemperatureDropped` / `_resetTemperatureWarnings` surface are unchanged.\n *\n * @module config/temperature-support\n */\n\nimport { createLogger } from '../core/index.js';\nimport { modelSupportsParameter } from './model-parameter-support.js';\n\nconst logger = createLogger({ component: 'temperature-support' });\n\n/**\n * Models we have ALREADY warned about dropping `temperature` for, so the loud\n * warning fires once per model per process rather than on every request (a voter\n * panel makes many calls). Repeats log at debug.\n */\nconst warnedDroppedModels = new Set<string>();\n\n/**\n * FAIL LOUDLY when `temperature` is omitted because the target model rejects it\n * (#4066 layer 3). `temperature` is a BEHAVIORAL parameter — silently dropping it\n * means a determinism/consistency setting is ignored with no signal (e.g. 0.0 and\n * 0.7 yield identical output), the canonical footgun. So the first drop per model\n * is a WARN that says the param was omitted and the request runs at the provider\n * default; subsequent drops for that model log at debug to avoid per-call spam.\n */\nexport function warnTemperatureDropped(modelId: string): void {\n if (warnedDroppedModels.has(modelId)) {\n logger.debug('Omitted unsupported temperature (already warned for this model)', {\n modelId,\n parameter: 'temperature',\n });\n return;\n }\n warnedDroppedModels.add(modelId);\n logger.warn(\n `Model \"${modelId}\" does not support a custom \\`temperature\\` (the provider rejects ` +\n `non-default values with a 400). nexus-agents omitted it; the request runs at the ` +\n `provider default. Any determinism/consistency you expected from temperature has NO ` +\n `effect on this model.`,\n { modelId, parameter: 'temperature', severity: 'behavioral' }\n );\n}\n\n/** Test seam: clear the once-per-model warning dedupe set. */\nexport function _resetTemperatureWarnings(): void {\n warnedDroppedModels.clear();\n}\n\n/**\n * Whether `modelId` REJECTS a non-default `temperature` and the param must be\n * dropped before the request is sent. Single source of truth for both adapters.\n *\n * Thin shim over {@link modelSupportsParameter} (#4067): registry\n * `unsupportedParameters` data wins, else the regex fallback (Claude after Opus\n * 4.6 #4061; OpenAI o-series / GPT-5 family / codex #4062; everything else\n * `false`). Biased AGAINST false positives: a missed model is a 400 outage, a\n * wrongly matched one only loses the consistency setting. Robust to gateway id\n * variants — provider prefixes (`anthropic/…`, `openai/…`), `-`/`_` separators,\n * dated suffixes.\n */\nexport function temperatureUnsupportedForModel(modelId: string): boolean {\n return !modelSupportsParameter(modelId, 'temperature');\n}\n","/**\n * nexus-agents/adapters — shared optional-parameter decision seam (#4068, epic #4066 layer 2).\n *\n * The claude / openai / sdk adapters each inlined an IDENTICAL temperature\n * drop-decision before forwarding a request: consult the layer-1 capability\n * resolver, drop `temperature` (and warn once) when the model rejects it, else\n * pass it through. This module is the single seam for that decision so the three\n * call sites stop duplicating it.\n *\n * It returns DECISION METADATA, not a provider-neutral params dict: each adapter\n * still owns its own wire shape (field names + nesting for stop/tools/\n * response_format/max-tokens), so the seam only decides the shared bit\n * (temperature) and records what it dropped/transformed for the layer-3 telemetry\n * child (#4069). Behavior-preserving by construction.\n *\n * @module adapters/optional-params\n */\n\nimport { modelSupportsParameter } from '../config/model-parameter-support.js';\nimport { warnTemperatureDropped } from '../config/temperature-support.js';\nimport type { CompletionRequest } from '../core/index.js';\n\n/**\n * Severity of a dropped param (#4069, epic #4066 layer 3). Behavioral params\n * (temperature/seed/top_p) affect determinism/output — dropping one silently is\n * the canonical footgun, so it is surfaced LOUDLY (WARN). Everything else is\n * cosmetic — dropping it is quiet (DEBUG).\n */\nexport type ParamSeverity = 'behavioral' | 'cosmetic';\n\n/** Params whose silent drop changes model output/determinism — loud when dropped. */\nconst BEHAVIORAL_PARAMS = new Set<string>(['temperature', 'seed', 'top_p']);\n\n/** Classify a request param as behavioral (loud-on-drop) or cosmetic (quiet). */\nexport function parameterSeverity(param: string): ParamSeverity {\n return BEHAVIORAL_PARAMS.has(param) ? 'behavioral' : 'cosmetic';\n}\n\n/** A request param the seam dropped, with why (feeds the layer-3 telemetry child #4069). */\nexport interface DroppedParam {\n readonly param: string;\n readonly reason: string;\n /** Behavioral (loud) vs cosmetic (quiet) — see {@link parameterSeverity}. */\n readonly severity: ParamSeverity;\n}\n\n/**\n * Would-have-self-healed counter (#4069, epic #4066 layer 3). Keyed\n * `${modelId}:${param}`. Counts every PROACTIVE drop (this module) AND every\n * REACTIVE param-naming 400 the adapter classifies as MODEL_PARAMETER_UNSUPPORTED\n * (base-adapter). Both are exactly the events the reactive self-heal path (#4071)\n * would catch, so this single counter measures how often #4071 would have fired.\n */\nconst wouldHaveSelfHealed = new Map<string, number>();\n\n/** Record one would-have-self-healed event for `modelId`'s `param` (#4069). */\nexport function recordWouldHaveSelfHealed(modelId: string, param: string): void {\n const key = `${modelId}:${param}`;\n wouldHaveSelfHealed.set(key, (wouldHaveSelfHealed.get(key) ?? 0) + 1);\n}\n\n/** Snapshot of the would-have-self-healed counts (defensive copy). */\nexport function getWouldHaveSelfHealedCounts(): ReadonlyMap<string, number> {\n return new Map(wouldHaveSelfHealed);\n}\n\n/** Test seam: clear the would-have-self-healed counter. */\nexport function _resetWouldHaveSelfHealed(): void {\n wouldHaveSelfHealed.clear();\n}\n\n/** A request param the seam transformed (name/value). Reserved for #4069 / a later max-tokens increment; empty today. */\nexport interface TransformedParam {\n readonly param: string;\n readonly from: unknown;\n readonly to: unknown;\n}\n\n/** The provider-NEUTRAL decision the adapters apply to their own wire shape. */\nexport interface OptionalParamPlan {\n /** Present iff temperature should be sent (the adapter sets it under its own field name — all 3 use `temperature`). Absent = drop it. */\n readonly temperature?: number;\n readonly dropped: readonly DroppedParam[];\n readonly transformed: readonly TransformedParam[];\n}\n\n/**\n * Centralizes the temperature drop-decision shared by the claude/openai/sdk adapters\n * (#4068, epic #4066 layer 2). Consults the layer-1 resolver; when the model rejects\n * temperature it is dropped (and `warnTemperatureDropped` fires, exactly as before) and\n * recorded in `dropped` for the layer-3 telemetry child (#4069). Behavior-preserving:\n * the adapters previously inlined this identically. Returns DECISION METADATA, not a\n * neutral params dict (each adapter still owns its wire names/nesting for stop/tools/etc).\n */\nexport function planOptionalParams(request: CompletionRequest, modelId: string): OptionalParamPlan {\n const dropped: DroppedParam[] = [];\n let temperature: number | undefined;\n if (request.temperature !== undefined) {\n if (modelSupportsParameter(modelId, 'temperature')) {\n temperature = request.temperature;\n } else {\n // ONE loud line per drop, deduped: warnTemperatureDropped is the consolidated\n // behavioral WARN (severity:'behavioral'), once per model then debug (#4066\n // layer 3). temperature is the only param dropped today and it is behavioral,\n // so there is no second emit — adding one would double-warn.\n warnTemperatureDropped(modelId);\n // Record the proactive drop: every time the reactive self-heal path (#4071)\n // would have fired on a temperature-rejecting 400.\n recordWouldHaveSelfHealed(modelId, 'temperature');\n dropped.push({\n param: 'temperature',\n reason: `model_rejects:${modelId}`,\n severity: parameterSeverity('temperature'),\n });\n }\n }\n return { ...(temperature !== undefined ? { temperature } : {}), dropped, transformed: [] };\n}\n","/**\n * nexus-agents/adapters - Base Adapter\n *\n * Abstract base class that all model adapters extend.\n * Provides common functionality for token counting, logging, error transformation,\n * and capability checking.\n */\n\nimport type {\n Result,\n IModelAdapter,\n CompletionRequest,\n CompletionResponse,\n StreamChunk,\n ILogger,\n ModelCapability,\n} from '../core/index.js';\nimport { getErrorMessage } from '../core/index.js';\nimport {\n isRateLimitLikeError,\n resolveRetryAfterMs,\n RETRY_AFTER_CONTEXT_KEY,\n} from './rate-limit-detector.js';\nimport { recordWouldHaveSelfHealed } from './optional-params.js';\n\nimport {\n ok,\n err,\n ConfigError,\n ModelError,\n ErrorCode,\n createLogger,\n getTokenEstimator,\n type NexusErrorOptions,\n} from '../core/index.js';\n\n/**\n * Configuration options for BaseAdapter.\n */\nexport interface BaseAdapterConfig {\n /** Provider identifier (e.g., 'anthropic', 'openai') */\n providerId: string;\n /** Model identifier (e.g., 'claude-sonnet-4', 'gpt-4o') */\n modelId: string;\n /** Capabilities this model supports */\n capabilities: readonly ModelCapability[];\n /** Optional custom logger */\n logger?: ILogger;\n /** API key for authentication (optional, may come from environment) */\n apiKey?: string;\n /** Base URL for the API (optional, uses provider default) */\n baseUrl?: string;\n /** Request timeout in milliseconds */\n timeout?: number;\n /** Maximum number of retries for failed requests */\n maxRetries?: number;\n}\n\n/**\n * Extended ModelError that supports specific error codes.\n *\n * While ModelError from core uses MODEL_ERROR by default, this subclass\n * allows adapters to specify more granular error codes like\n * MODEL_RATE_LIMITED, MODEL_TIMEOUT, etc.\n *\n * Extends ModelError so `instanceof ModelError` checks pass naturally\n * without requiring `as unknown as ModelError` casts.\n */\nexport class AdapterModelError extends ModelError {\n constructor(message: string, options: NexusErrorOptions) {\n super(message, options);\n this.name = 'ModelError';\n }\n}\n\n// ============================================================================\n// API Key Validation Helpers (#1446 — DRY extraction)\n// ============================================================================\n\n/**\n * Returns true if the given API key is missing or blank.\n */\nexport function isApiKeyMissing(apiKey: string | undefined): boolean {\n return apiKey === undefined || apiKey === '' || apiKey.trim() === '';\n}\n\n/**\n * Validates API key presence in constructor — throws ConfigError if missing.\n * Use in adapter constructors where throwing is appropriate.\n */\nexport function requireApiKey(\n apiKey: string | undefined,\n providerName: string,\n modelId: string\n): void {\n if (isApiKeyMissing(apiKey)) {\n throw new ConfigError(`${providerName} API key is required`, {\n context: { providerId: providerName.toLowerCase(), modelId },\n });\n }\n}\n\n/**\n * Validates API key presence — returns Result for validate-style methods.\n * Use in adapter validateConfig() methods that return Result.\n */\nexport function validateApiKeyPresence(\n apiKey: string | undefined,\n providerId: string,\n modelId: string\n): Result<void, ConfigError> {\n if (isApiKeyMissing(apiKey)) {\n return err(\n new ConfigError(`${providerId} API key is required`, {\n context: { providerId, modelId },\n })\n );\n }\n return ok(undefined);\n}\n\n/**\n * Abstract base class for model adapters.\n *\n * Provides default implementations for common adapter functionality while\n * leaving the core API interaction methods abstract for provider-specific\n * implementations.\n *\n * @example\n * ```typescript\n * class ClaudeAdapter extends BaseAdapter {\n * constructor(config: ClaudeAdapterConfig) {\n * super({\n * providerId: 'anthropic',\n * modelId: config.modelId,\n * capabilities: [ModelCapability.COMPLETION, ModelCapability.STREAMING],\n * apiKey: config.apiKey,\n * });\n * }\n *\n * async complete(request: CompletionRequest): Promise<Result<CompletionResponse, ModelError>> {\n * this.logRequest(request);\n * // Provider-specific implementation...\n * }\n *\n * async *stream(request: CompletionRequest): AsyncIterable<StreamChunk> {\n * this.logRequest(request);\n * // Provider-specific streaming implementation...\n * }\n * }\n * ```\n */\nexport abstract class BaseAdapter implements IModelAdapter {\n readonly providerId: string;\n readonly modelId: string;\n readonly capabilities: readonly ModelCapability[];\n\n /** Logger for request/response logging */\n protected readonly logger: ILogger;\n\n /** Configuration for the adapter */\n protected readonly config: BaseAdapterConfig;\n\n /**\n * Creates a new BaseAdapter instance.\n *\n * @param config - Adapter configuration\n */\n constructor(config: BaseAdapterConfig) {\n this.providerId = config.providerId;\n this.modelId = config.modelId;\n this.capabilities = config.capabilities;\n this.config = config;\n this.logger =\n config.logger ??\n createLogger({\n adapter: config.providerId,\n model: config.modelId,\n });\n }\n\n /**\n * Send a completion request to the model.\n * Must be implemented by concrete adapter classes.\n *\n * @param request - The completion request\n * @returns Result with response or ModelError\n */\n abstract complete(request: CompletionRequest): Promise<Result<CompletionResponse, ModelError>>;\n\n /**\n * Stream a completion request from the model.\n * Must be implemented by concrete adapter classes.\n *\n * @param request - The completion request\n * @yields StreamChunk objects as they arrive\n */\n abstract stream(request: CompletionRequest): AsyncIterable<StreamChunk>;\n\n /**\n * Count tokens in text using the unified TokenEstimator.\n *\n * This provides a reasonable estimate for most use cases.\n * Concrete adapters may override this with provider-specific tokenizers.\n *\n * @param text - Text to count tokens for\n * @returns Approximate token count\n */\n countTokens(text: string): Promise<number> {\n return Promise.resolve(getTokenEstimator().estimateText(text));\n }\n\n /**\n * Validate adapter configuration.\n *\n * Checks that required configuration fields are present and valid.\n * Concrete adapters may override to add provider-specific validation.\n *\n * @returns Ok if valid, ConfigError if invalid\n */\n validateConfig(): Result<void, ConfigError> {\n const errors: string[] = [];\n\n if (!this.providerId || this.providerId.trim() === '') {\n errors.push('Provider ID is required');\n }\n\n if (!this.modelId || this.modelId.trim() === '') {\n errors.push('Model ID is required');\n }\n\n if (this.config.timeout !== undefined && this.config.timeout <= 0) {\n errors.push('Timeout must be positive');\n }\n\n if (this.config.maxRetries !== undefined && this.config.maxRetries < 0) {\n errors.push('Max retries cannot be negative');\n }\n\n if (errors.length > 0) {\n return err(\n new ConfigError(`Invalid adapter configuration: ${errors.join('; ')}`, {\n context: {\n providerId: this.providerId,\n modelId: this.modelId,\n errors,\n },\n })\n );\n }\n\n return ok(undefined);\n }\n\n /**\n * Check if this adapter supports a specific capability.\n *\n * @param capability - The capability to check for\n * @returns True if the capability is supported\n */\n hasCapability(capability: ModelCapability): boolean {\n return this.capabilities.includes(capability);\n }\n\n /**\n * Log details about an outgoing request.\n * Sanitizes sensitive information before logging.\n *\n * @param request - The completion request to log\n */\n protected logRequest(request: CompletionRequest): void {\n const messageCount = request.messages.length;\n const hasTools = request.tools !== undefined && request.tools.length > 0;\n const toolCount = request.tools?.length ?? 0;\n\n this.logger.debug('Sending completion request', {\n messageCount,\n hasSystemPrompt: request.systemPrompt !== undefined,\n temperature: request.temperature,\n maxTokens: request.maxTokens,\n hasTools,\n toolCount,\n responseFormat: request.responseFormat?.type,\n stopSequences: request.stop?.length ?? 0,\n });\n }\n\n /**\n * Log details about a received response.\n *\n * @param response - The completion response to log\n */\n protected logResponse(response: CompletionResponse): void {\n this.logger.debug('Received completion response', {\n contentBlocks: response.content.length,\n stopReason: response.stopReason,\n inputTokens: response.usage?.inputTokens ?? 0,\n outputTokens: response.usage?.outputTokens ?? 0,\n totalTokens: response.usage?.totalTokens ?? 0,\n model: response.model,\n });\n }\n\n /**\n * Transform a provider-specific error into a standardized ModelError.\n *\n * Maps common error patterns to appropriate error codes:\n * - Rate limiting (429, quota exceeded)\n * - Timeouts (ETIMEDOUT, ESOCKETTIMEDOUT)\n * - Authentication (401, 403)\n * - Model unavailable (503, 502)\n *\n * @param error - The original error from the provider\n * @returns A standardized ModelError\n */\n protected transformError(error: unknown): ModelError {\n if (error instanceof ModelError) {\n return error;\n }\n\n const errorMessage = getErrorMessage(error);\n const errorCode = this.determineErrorCode(error);\n\n // #4069: a param-naming 400 carries the offending param name in context, and\n // counts as a would-have-self-healed event (the reactive #4071 path would catch\n // exactly this 400). Only set for MODEL_PARAMETER_UNSUPPORTED — all other codes\n // are unchanged.\n const param =\n errorCode === ErrorCode.MODEL_PARAMETER_UNSUPPORTED\n ? this.extractErrorParam(error)\n : undefined;\n if (param !== undefined) {\n recordWouldHaveSelfHealed(this.modelId, param);\n }\n\n // #4606: capture the provider's stated retry horizon HERE, while the\n // thrown SDK error — the last place the HTTP response is reachable — is\n // still in hand. Header first (RFC 9110 `Retry-After`), body prose second.\n // Only on a rate limit: a wait hint inside a 500 body is not a rate-limit\n // assertion, matching the subprocess path's `retryable ? parse : undefined`.\n // `resolveRetryAfterMs` returns a NUMBER; no header object travels inward.\n const retryAfterMs =\n errorCode === ErrorCode.MODEL_RATE_LIMITED\n ? resolveRetryAfterMs(error, errorMessage)\n : undefined;\n\n const modelError = this.createModelError(errorMessage, errorCode, error, param, retryAfterMs);\n\n this.logger.error('Model adapter error', modelError, {\n errorCode,\n providerId: this.providerId,\n modelId: this.modelId,\n });\n\n return modelError;\n }\n\n /**\n * Create a ModelError with appropriate error code.\n */\n private createModelError(\n message: string,\n errorCode: (typeof ErrorCode)[keyof typeof ErrorCode],\n originalError: unknown,\n param?: string,\n retryAfterMs?: number\n ): ModelError {\n const fullMessage = `${this.providerId}/${this.modelId}: ${message}`;\n\n // Build options object conditionally to satisfy exactOptionalPropertyTypes\n const context: Record<string, unknown> = {\n providerId: this.providerId,\n modelId: this.modelId,\n };\n // #4069: surface the offending param name for a param-naming 400 so callers\n // and the reactive self-heal path (#4071) can read which param to retry without.\n if (param !== undefined) {\n context.param = param;\n }\n // #4606: the provider-stated retry horizon, in ms. Set only when a horizon\n // was actually read — absent means \"the provider said nothing\", which is\n // what `CapacityTracker.recordProviderQuotaExhaustion` needs to see rather\n // than a substituted 0.\n if (retryAfterMs !== undefined) {\n context[RETRY_AFTER_CONTEXT_KEY] = retryAfterMs;\n }\n const options: NexusErrorOptions = {\n code: errorCode,\n context,\n };\n\n // Only set cause if originalError is an Error\n if (originalError instanceof Error) {\n options.cause = originalError;\n }\n\n // AdapterModelError extends ModelError — no cast needed\n return new AdapterModelError(fullMessage, options);\n }\n\n /**\n * Determine the appropriate error code based on error characteristics.\n */\n private determineErrorCode(error: unknown): (typeof ErrorCode)[keyof typeof ErrorCode] {\n if (!(error instanceof Error)) {\n return ErrorCode.MODEL_ERROR;\n }\n\n const message = error.message.toLowerCase();\n const errorObj = error as { status?: number; code?: string };\n\n // Check for rate limiting (canonical detection from rate-limit-detector)\n if (isRateLimitLikeError(error)) {\n return ErrorCode.MODEL_RATE_LIMITED;\n }\n\n // Check for timeout\n if (this.isTimeoutError(message, errorObj)) {\n return ErrorCode.MODEL_TIMEOUT;\n }\n\n // Check for model-not-found (#2540 PR 8) — distinct from transient\n // MODEL_UNAVAILABLE (502/503). 404 + vendor-specific phrases (\"model\n // not found\", \"deprecated\", \"no such model\") all mean: this id is\n // gone, retry won't help, route to a different one.\n if (this.isModelNotFoundError(message, errorObj)) {\n return ErrorCode.MODEL_NOT_FOUND;\n }\n\n // Check for model unavailable\n if (this.isUnavailableError(message, errorObj)) {\n return ErrorCode.MODEL_UNAVAILABLE;\n }\n\n // Check for a param-naming 400 (#4069): a 400 that identifies an unsupported\n // parameter by name. Distinct from generic MODEL_ERROR — non-retryable, and the\n // param name is threaded into context. Only changes 400s that NAME a param; a\n // 400 with no param, and every non-400, stay MODEL_ERROR.\n if (this.extractErrorParam(error) !== undefined) {\n return ErrorCode.MODEL_PARAMETER_UNSUPPORTED;\n }\n\n return ErrorCode.MODEL_ERROR;\n }\n\n /**\n * Extract the offending parameter name from a param-naming 400 (#4069).\n *\n * Returns the param only when the error is a 400 AND carries a non-empty `param`\n * field (the OpenAI SDK / OpenAI-compatible gateways set this on a rejected\n * parameter; the OpenAI adapter threads it onto the classification probe).\n * Returns undefined otherwise, so non-400s and param-less 400s are untouched.\n */\n private extractErrorParam(error: unknown): string | undefined {\n if (!(error instanceof Error)) {\n return undefined;\n }\n const errorObj = error as { status?: number; param?: unknown };\n if (errorObj.status !== 400) {\n return undefined;\n }\n return typeof errorObj.param === 'string' && errorObj.param !== '' ? errorObj.param : undefined;\n }\n\n /**\n * (#2540 PR 8) Detect model-retirement errors. Distinct from transient\n * 502/503: 404 + vendor messages indicating the model id is gone.\n */\n private isModelNotFoundError(\n message: string,\n errorObj: { status?: number; code?: string }\n ): boolean {\n if (errorObj.status === 404) return true;\n const patterns = [\n 'model not found',\n 'model_not_found',\n 'no such model',\n 'model is deprecated',\n 'model has been deprecated',\n 'model is no longer available',\n ];\n return patterns.some((p) => message.includes(p));\n }\n\n /**\n * Check if error indicates a timeout.\n */\n private isTimeoutError(message: string, errorObj: { status?: number; code?: string }): boolean {\n const timeoutPatterns = ['timeout', 'etimedout', 'esockettimedout'];\n return (\n errorObj.code === 'ETIMEDOUT' ||\n errorObj.code === 'ESOCKETTIMEDOUT' ||\n timeoutPatterns.some((pattern) => message.includes(pattern))\n );\n }\n\n /**\n * Check if error indicates model unavailability.\n */\n private isUnavailableError(\n message: string,\n errorObj: { status?: number; code?: string }\n ): boolean {\n const unavailablePatterns = ['unavailable', 'service unavailable', 'overloaded'];\n return (\n errorObj.status === 502 ||\n errorObj.status === 503 ||\n unavailablePatterns.some((pattern) => message.includes(pattern))\n );\n }\n}\n","/**\n * nexus-agents/adapters - Streaming Types and Core Utilities\n *\n * Shared types, errors, and core streaming primitives used by both\n * streaming.ts and stream-operators.ts to avoid circular dependencies.\n */\n\nimport { type Result, ok, err } from '../core/index.js';\nimport { NexusError, ErrorCode } from '../core/index.js';\n\n/**\n * Error thrown when a stream operation fails.\n */\nexport class StreamError extends NexusError {\n constructor(message: string, options?: { cause?: Error; context?: Record<string, unknown> }) {\n super(message, { code: ErrorCode.INTERNAL_ERROR, ...options });\n this.name = 'StreamError';\n }\n}\n\n/**\n * Error thrown when a stream is cancelled.\n */\nexport class StreamCancelledError extends NexusError {\n constructor(reason?: string) {\n super(reason ?? 'Stream was cancelled', { code: ErrorCode.INTERNAL_ERROR });\n this.name = 'StreamCancelledError';\n }\n}\n\n/**\n * State of a stream controller.\n */\nexport type StreamState = 'idle' | 'streaming' | 'paused' | 'cancelled' | 'completed' | 'error';\n\n/**\n * Options for creating a stream.\n */\nexport interface CreateStreamOptions {\n /** AbortSignal for cancellation support */\n signal?: AbortSignal;\n /** Maximum buffer size for backpressure (default: 100) */\n maxBufferSize?: number;\n}\n\n/**\n * Controller for managing stream lifecycle.\n * Provides push/complete/error methods and cancellation support.\n */\nexport class StreamController<T> {\n private readonly chunks: T[] = [];\n private readonly waiters: Array<{\n resolve: (result: IteratorResult<T, void>) => void;\n reject: (error: Error) => void;\n }> = [];\n\n private _state: StreamState = 'idle';\n private _error: Error | undefined;\n private readonly maxBufferSize: number;\n private readonly abortHandler: (() => void) | undefined;\n private readonly abortSignal: AbortSignal | undefined;\n\n /**\n * Creates a new StreamController.\n * @param options - Stream creation options\n */\n constructor(options: CreateStreamOptions = {}) {\n this.maxBufferSize = options.maxBufferSize ?? 100;\n\n if (options.signal) {\n this.abortSignal = options.signal;\n this.abortHandler = (): void => {\n this.cancel('AbortSignal triggered');\n };\n options.signal.addEventListener('abort', this.abortHandler);\n }\n }\n\n /**\n * Current state of the stream.\n */\n get state(): StreamState {\n return this._state;\n }\n\n /**\n * Whether the stream is still active (can receive chunks).\n */\n get isActive(): boolean {\n return this._state === 'idle' || this._state === 'streaming' || this._state === 'paused';\n }\n\n /**\n * Current buffer size.\n */\n get bufferSize(): number {\n return this.chunks.length;\n }\n\n /**\n * Push a chunk to the stream.\n * @param chunk - The chunk to push\n * @returns Result indicating success or backpressure\n */\n push(chunk: T): Result<void, StreamError> {\n if (!this.isActive) {\n return err(new StreamError(`Cannot push to stream in state: ${this._state}`));\n }\n\n if (this._state === 'idle') {\n this._state = 'streaming';\n }\n\n // If there's a waiting consumer, deliver directly\n const waiter = this.waiters.shift();\n if (waiter) {\n waiter.resolve({ done: false, value: chunk });\n return ok(undefined);\n }\n\n // Check backpressure\n if (this.chunks.length >= this.maxBufferSize) {\n this._state = 'paused';\n return err(\n new StreamError('Buffer full - backpressure applied', {\n context: { bufferSize: this.chunks.length, maxBufferSize: this.maxBufferSize },\n })\n );\n }\n\n this.chunks.push(chunk);\n return ok(undefined);\n }\n\n /**\n * Complete the stream successfully.\n */\n complete(): void {\n if (!this.isActive) {\n return;\n }\n\n this._state = 'completed';\n this.removeAbortListener();\n this.resolveAllWaiters();\n }\n\n /**\n * Complete the stream with an error.\n * @param error - The error that occurred\n */\n error(error: Error): void {\n if (!this.isActive) {\n return;\n }\n\n this._state = 'error';\n this._error = error;\n this.removeAbortListener();\n this.rejectAllWaiters(error);\n }\n\n /**\n * Cancel the stream.\n * @param reason - Optional reason for cancellation\n */\n cancel(reason?: string): void {\n if (!this.isActive) {\n return;\n }\n\n this._state = 'cancelled';\n this._error = new StreamCancelledError(reason);\n this.removeAbortListener();\n this.rejectAllWaiters(this._error);\n }\n\n /**\n * Get the AsyncIterable for consuming the stream.\n */\n getIterable(): AsyncIterable<T> {\n // Store reference to controller methods for closure\n const nextChunk = (): Promise<IteratorResult<T, void>> => this.nextChunk();\n const cancel = (reason: string): void => {\n this.cancel(reason);\n };\n\n return {\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return {\n async next(): Promise<IteratorResult<T, void>> {\n return nextChunk();\n },\n return(): Promise<IteratorResult<T, void>> {\n cancel('Iterator returned');\n return Promise.resolve({ done: true, value: undefined });\n },\n };\n },\n };\n }\n\n private async nextChunk(): Promise<IteratorResult<T, void>> {\n // If we have buffered chunks, return one\n const chunk = this.chunks.shift();\n if (chunk !== undefined) {\n // Resume if we were paused and buffer is now below threshold\n if (this._state === 'paused' && this.chunks.length < this.maxBufferSize / 2) {\n this._state = 'streaming';\n }\n return { done: false, value: chunk };\n }\n\n // Check terminal states\n if (this._state === 'completed') {\n return { done: true, value: undefined };\n }\n\n if (this._state === 'cancelled' || this._state === 'error') {\n throw this._error ?? new StreamCancelledError();\n }\n\n // Wait for next chunk\n return new Promise((resolve, reject) => {\n this.waiters.push({ resolve, reject });\n });\n }\n\n private removeAbortListener(): void {\n if (this.abortSignal && this.abortHandler) {\n this.abortSignal.removeEventListener('abort', this.abortHandler);\n }\n }\n\n private resolveAllWaiters(): void {\n for (const waiter of this.waiters) {\n waiter.resolve({ done: true, value: undefined });\n }\n this.waiters.length = 0;\n }\n\n private rejectAllWaiters(error: Error): void {\n for (const waiter of this.waiters) {\n waiter.reject(error);\n }\n this.waiters.length = 0;\n }\n}\n\n/**\n * Creates a controllable stream.\n * @param options - Stream creation options\n * @returns Tuple of [controller, iterable]\n */\nexport function createStream<T>(\n options: CreateStreamOptions = {}\n): [StreamController<T>, AsyncIterable<T>] {\n const controller = new StreamController<T>(options);\n return [controller, controller.getIterable()];\n}\n","/**\n * nexus-agents/adapters - Stream Operators Helpers\n *\n * Helper functions for stream operations extracted for maintainability.\n */\n\nimport { type Result, ok, err } from '../core/index.js';\nimport { StreamError, StreamCancelledError } from './streaming-types.js';\n\n/**\n * Takes the first N chunks from a stream.\n * @param stream - The source stream\n * @param count - Number of chunks to take\n * @param options - Options including optional AbortSignal\n * @returns Stream of first N chunks\n */\nexport async function* take<T>(\n stream: AsyncIterable<T>,\n count: number,\n options: { signal?: AbortSignal } = {}\n): AsyncIterable<T> {\n if (count <= 0) {\n return;\n }\n\n let taken = 0;\n\n for await (const chunk of stream) {\n if (options.signal?.aborted === true) {\n throw new StreamCancelledError('take aborted');\n }\n\n yield chunk;\n taken++;\n\n if (taken >= count) {\n return;\n }\n }\n}\n\n/**\n * Skips the first N chunks from a stream.\n * @param stream - The source stream\n * @param count - Number of chunks to skip\n * @param options - Options including optional AbortSignal\n * @returns Stream with first N chunks skipped\n */\nexport async function* skip<T>(\n stream: AsyncIterable<T>,\n count: number,\n options: { signal?: AbortSignal } = {}\n): AsyncIterable<T> {\n let skipped = 0;\n\n for await (const chunk of stream) {\n if (options.signal?.aborted === true) {\n throw new StreamCancelledError('skip aborted');\n }\n\n if (skipped < count) {\n skipped++;\n continue;\n }\n\n yield chunk;\n }\n}\n\n/**\n * Concatenates multiple streams sequentially.\n * @param streams - The streams to concatenate\n * @param options - Options including optional AbortSignal\n * @returns Concatenated stream\n */\nexport async function* concatStreams<T>(\n streams: AsyncIterable<T>[],\n options: { signal?: AbortSignal } = {}\n): AsyncIterable<T> {\n for (const stream of streams) {\n if (options.signal?.aborted === true) {\n throw new StreamCancelledError('concat aborted');\n }\n\n yield* stream;\n }\n}\n\n/**\n * Creates a stream from an array of values.\n * @param values - The values to stream\n * @param options - Options including optional delay between chunks\n * @returns Stream of values\n */\nexport async function* fromArray<T>(\n values: T[],\n options: { delayMs?: number; signal?: AbortSignal } = {}\n): AsyncIterable<T> {\n for (const value of values) {\n if (options.signal?.aborted === true) {\n throw new StreamCancelledError('fromArray aborted');\n }\n\n if (options.delayMs !== undefined && options.delayMs > 0) {\n await new Promise((resolve) => setTimeout(resolve, options.delayMs));\n }\n\n yield value;\n }\n}\n\n/**\n * Taps into a stream without modifying it (for side effects like logging).\n * @param stream - The source stream\n * @param fn - Side effect function called for each chunk\n * @param options - Options including optional AbortSignal\n * @returns Original stream unchanged\n */\nexport async function* tapStream<T>(\n stream: AsyncIterable<T>,\n fn: (chunk: T, index: number) => void | Promise<void>,\n options: { signal?: AbortSignal } = {}\n): AsyncIterable<T> {\n let index = 0;\n\n for await (const chunk of stream) {\n if (options.signal?.aborted === true) {\n throw new StreamCancelledError('tap aborted');\n }\n\n await fn(chunk, index);\n yield chunk;\n index++;\n }\n}\n\n/**\n * Reduces a stream to a single value.\n * @param stream - The source stream\n * @param reducer - Reducer function\n * @param initialValue - Initial accumulator value\n * @param options - Options including optional AbortSignal\n * @returns Result containing the final value or error\n */\nexport async function reduceStream<T, U>(\n stream: AsyncIterable<T>,\n reducer: (accumulator: U, chunk: T, index: number) => U | Promise<U>,\n initialValue: U,\n options: { signal?: AbortSignal } = {}\n): Promise<Result<U, StreamError>> {\n let accumulator = initialValue;\n let index = 0;\n\n try {\n for await (const chunk of stream) {\n if (options.signal?.aborted === true) {\n return err(new StreamError('Reduce aborted'));\n }\n\n accumulator = await reducer(accumulator, chunk, index);\n index++;\n }\n\n return ok(accumulator);\n } catch (error) {\n return err(\n new StreamError('Failed to reduce stream', {\n cause: error instanceof Error ? error : new Error(String(error)),\n })\n );\n }\n}\n","/**\n * nexus-agents/adapters - Stream Operators\n *\n * Stream transformation operators for AsyncIterables.\n * Provides filter, map, merge, concat, buffer, and other stream operations.\n */\n\nimport { TimeoutError } from '../core/index.js';\nimport {\n StreamError,\n StreamCancelledError,\n createStream,\n type CreateStreamOptions,\n} from './streaming-types.js';\n\n// Re-export helper functions for backward compatibility\nexport {\n take,\n skip,\n concatStreams,\n fromArray,\n tapStream,\n reduceStream,\n} from './stream-operators-helpers.js';\n\n/**\n * Transforms stream chunks using a mapping function.\n * @param stream - The source stream\n * @param fn - Transformation function\n * @param options - Options including optional AbortSignal\n * @returns Transformed stream\n */\nexport async function* transformStream<T, U>(\n stream: AsyncIterable<T>,\n fn: (chunk: T, index: number) => U | Promise<U>,\n options: { signal?: AbortSignal } = {}\n): AsyncIterable<U> {\n let index = 0;\n\n for await (const chunk of stream) {\n if (options.signal?.aborted === true) {\n throw new StreamCancelledError('Transform aborted');\n }\n\n yield await fn(chunk, index);\n index++;\n }\n}\n\n/**\n * Merges multiple streams into a single stream.\n * Chunks are yielded as they arrive from any source.\n * @param streams - The streams to merge\n * @param options - Options including optional AbortSignal\n * @returns Merged stream\n */\nexport async function* mergeStreams<T>(\n streams: AsyncIterable<T>[],\n options: { signal?: AbortSignal } = {}\n): AsyncIterable<T> {\n if (streams.length === 0) {\n return;\n }\n\n const streamOptions: CreateStreamOptions = {};\n if (options.signal) {\n streamOptions.signal = options.signal;\n }\n const [controller, merged] = createStream<T>(streamOptions);\n let activeCount = streams.length;\n\n // Start consuming all streams in parallel\n const consumers = streams.map(async (stream, streamIndex) => {\n try {\n for await (const chunk of stream) {\n if (options.signal?.aborted === true) {\n break;\n }\n controller.push(chunk);\n }\n } catch (error) {\n if (error instanceof StreamCancelledError) {\n // Propagate cancellation\n controller.cancel(`Stream ${String(streamIndex)} was cancelled`);\n return;\n }\n controller.error(error instanceof Error ? error : new Error(String(error)));\n return;\n } finally {\n activeCount--;\n if (activeCount === 0) {\n controller.complete();\n }\n }\n });\n\n // Start all consumers without blocking (Issue #541)\n // Each consumer has try-catch that forwards errors to controller.error(),\n // so Promise.all should always resolve. Add defensive catch for edge cases.\n Promise.all(consumers).catch((error: unknown) => {\n // This should not happen since each consumer catches its own errors,\n // but handle it defensively to prevent silent failures.\n controller.error(error instanceof Error ? error : new StreamError(String(error)));\n });\n\n yield* merged;\n}\n\n/**\n * Takes chunks from a stream until a predicate returns true.\n * @param stream - The source stream\n * @param predicate - Function that returns true to stop taking\n * @param options - Options including whether to include the matching chunk\n * @returns Stream of chunks up to (and optionally including) the match\n */\nexport async function* takeUntil<T>(\n stream: AsyncIterable<T>,\n predicate: (chunk: T, index: number) => boolean | Promise<boolean>,\n options: { signal?: AbortSignal; inclusive?: boolean } = {}\n): AsyncIterable<T> {\n let index = 0;\n\n for await (const chunk of stream) {\n if (options.signal?.aborted === true) {\n throw new StreamCancelledError('takeUntil aborted');\n }\n\n const shouldStop = await predicate(chunk, index);\n\n if (shouldStop) {\n if (options.inclusive === true) {\n yield chunk;\n }\n return;\n }\n\n yield chunk;\n index++;\n }\n}\n\n/**\n * Filters stream chunks based on a predicate.\n * @param stream - The source stream\n * @param predicate - Function that returns true to keep the chunk\n * @param options - Options including optional AbortSignal\n * @returns Filtered stream\n */\nexport async function* filterStream<T>(\n stream: AsyncIterable<T>,\n predicate: (chunk: T, index: number) => boolean | Promise<boolean>,\n options: { signal?: AbortSignal } = {}\n): AsyncIterable<T> {\n let index = 0;\n\n for await (const chunk of stream) {\n if (options.signal?.aborted === true) {\n throw new StreamCancelledError('filter aborted');\n }\n\n if (await predicate(chunk, index)) {\n yield chunk;\n }\n\n index++;\n }\n}\n\n/**\n * Adds a timeout to a stream. If no chunk is received within the timeout,\n * the stream throws a TimeoutError.\n * @param stream - The source stream\n * @param timeoutMs - Timeout in milliseconds\n * @param options - Options including optional AbortSignal\n * @returns Stream with timeout applied\n */\nexport async function* withTimeout<T>(\n stream: AsyncIterable<T>,\n timeoutMs: number,\n options: { signal?: AbortSignal } = {}\n): AsyncIterable<T> {\n const iterator = stream[Symbol.asyncIterator]();\n\n try {\n let running = true;\n while (running) {\n if (options.signal?.aborted === true) {\n throw new StreamCancelledError('withTimeout aborted');\n }\n\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n try {\n const result = await Promise.race([\n iterator.next().then((res) => {\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n return res;\n }),\n new Promise<never>((_, reject) => {\n timeoutId = setTimeout(() => {\n reject(\n new TimeoutError(`Stream timed out after ${String(timeoutMs)}ms`, {\n context: { timeoutMs },\n })\n );\n }, timeoutMs);\n }),\n ]);\n\n if (result.done === true) {\n running = false;\n } else {\n yield result.value;\n }\n } finally {\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n }\n }\n } finally {\n // Ensure the iterator is properly closed\n if (iterator.return !== undefined) {\n await iterator.return();\n }\n }\n}\n\n/**\n * Buffers stream chunks into groups of a specified size.\n * @param stream - The source stream\n * @param size - Buffer size\n * @param options - Options including optional AbortSignal\n * @returns Stream of chunk arrays\n */\nexport async function* bufferStream<T>(\n stream: AsyncIterable<T>,\n size: number,\n options: { signal?: AbortSignal } = {}\n): AsyncIterable<T[]> {\n if (size <= 0) {\n throw new StreamError('Buffer size must be positive');\n }\n\n let buffer: T[] = [];\n\n for await (const chunk of stream) {\n if (options.signal?.aborted === true) {\n throw new StreamCancelledError('buffer aborted');\n }\n\n buffer.push(chunk);\n\n if (buffer.length >= size) {\n yield buffer;\n buffer = [];\n }\n }\n\n // Yield remaining chunks\n if (buffer.length > 0) {\n yield buffer;\n }\n}\n","/**\n * nexus-agents/adapters - Streaming Utilities\n *\n * AsyncIterator-based streaming utilities for model responses.\n * Provides stream creation, backpressure handling, cancellation support,\n * and chunk collection helpers.\n *\n * For stream transformation operators (map, filter, merge, etc.),\n * see ./stream-operators.ts\n */\n\nimport { type Result, ok, err } from '../core/index.js';\n\n// Re-export core streaming types and utilities from shared module\nexport {\n StreamError,\n StreamCancelledError,\n StreamController,\n createStream,\n type StreamState,\n type CreateStreamOptions,\n} from './streaming-types.js';\n\n// Import for use in this file\nimport { StreamError, StreamCancelledError } from './streaming-types.js';\n\n/**\n * Default cap on collected chunks — prevents unbounded memory growth when\n * callers forget to pass `maxChunks`. Callers that genuinely need no cap\n * must opt in explicitly with `{ maxChunks: Infinity }`. (#1913 Class F)\n */\nexport const DEFAULT_COLLECT_STREAM_MAX_CHUNKS = 100_000;\n\n/**\n * Collects all chunks from a stream into an array.\n *\n * @param stream - The stream to collect\n * @param options - Options including optional AbortSignal.\n * `maxChunks` defaults to {@link DEFAULT_COLLECT_STREAM_MAX_CHUNKS} to\n * prevent unbounded memory growth on forgotten limits. Pass\n * `Infinity` explicitly for truly unbounded collection.\n * @returns Result containing collected chunks or error\n */\nexport async function collectStream<T>(\n stream: AsyncIterable<T>,\n options: { signal?: AbortSignal; maxChunks?: number } = {}\n): Promise<Result<T[], StreamError>> {\n const chunks: T[] = [];\n const maxChunks = options.maxChunks ?? DEFAULT_COLLECT_STREAM_MAX_CHUNKS;\n\n try {\n for await (const chunk of stream) {\n if (options.signal?.aborted === true) {\n return err(new StreamError('Collection aborted'));\n }\n\n chunks.push(chunk);\n\n if (chunks.length >= maxChunks) {\n break;\n }\n }\n\n return ok(chunks);\n } catch (error) {\n if (error instanceof StreamCancelledError) {\n return err(new StreamError('Stream was cancelled during collection', { cause: error }));\n }\n return err(\n new StreamError('Failed to collect stream', {\n cause: error instanceof Error ? error : new Error(String(error)),\n })\n );\n }\n}\n\n// Re-export all stream operators for convenience\nexport {\n transformStream,\n mergeStreams,\n takeUntil,\n take,\n skip,\n filterStream,\n withTimeout,\n bufferStream,\n concatStreams,\n fromArray,\n tapStream,\n reduceStream,\n} from './stream-operators.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;AAoDA,SAAS,sBAAsB,QAAyC;AACtE,QAAM,UAAU,OAAO,QAAQ,eAAe,EAAE;AAChD,QAAM,QAAQ,uBAAuB,KAAK,OAAO;AACjD,MAAI,UAAU,KAAM,QAAO;AAC3B,QAAM,QAAQ,OAAO,SAAS,MAAM,CAAC,GAAa,EAAE;AACpD,QAAM,QAAQ,MAAM,CAAC,MAAM,SAAY,OAAO,SAAS,MAAM,CAAC,GAAG,EAAE,IAAI;AACvE,MAAI,OAAO,MAAM,KAAK,KAAK,OAAO,MAAM,KAAK,EAAG,QAAO;AACvD,SAAO,EAAE,OAAO,MAAM;AACxB;AAGA,IAAM,gCAAgC;AAStC,SAAS,6BAA6B,MAAuB;AAC3D,QAAM,UAAU,sBAAsB,IAAI;AAC1C,MAAI,YAAY,MAAM;AAEpB,WAAO,QAAQ,QAAQ,KAAM,QAAQ,UAAU,KAAK,QAAQ,SAAS;AAAA,EACvE;AACA,MAAI,8BAA8B,KAAK,IAAI,EAAG,QAAO;AACrD,SAAO;AACT;AAcA,SAAS,gBAAgB,IAAqB;AAC5C,QAAM,UAAU,GAAG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AAYjD,eAAsB,cACpB,QACA,UAAwD,CAAC,GACtB;AACnC,QAAM,SAAc,CAAC;AACrB,QAAM,YAAY,QAAQ,aAAa;AAEvC,MAAI;AACF,qBAAiB,SAAS,QAAQ;AAChC,UAAI,QAAQ,QAAQ,YAAY,MAAM;AACpC,eAAO,IAAI,IAAI,YAAY,oBAAoB,CAAC;AAAA,MAClD;AAEA,aAAO,KAAK,KAAK;AAEjB,UAAI,OAAO,UAAU,WAAW;AAC9B;AAAA,MACF;AAAA,IACF;AAEA,WAAO,GAAG,MAAM;AAAA,EAClB,SAAS,OAAO;AACd,QAAI,iBAAiB,sBAAsB;AACzC,aAAO,IAAI,IAAI,YAAY,0CAA0C,EAAE,OAAO,MAAM,CAAC,CAAC;AAAA,IACxF;AACA,WAAO;AAAA,MACL,IAAI,YAAY,4BAA4B;AAAA,QAC1C,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;AAAA,MACjE,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":[]}
@@ -1,6 +1,6 @@
1
1
  // src/version.ts
2
2
  import semver from "semver";
3
- var VERSION = true ? "8.86.3" : "dev";
3
+ var VERSION = true ? "8.88.0" : "dev";
4
4
  var NODE_ENGINE_RANGE = ">=22.5.0";
5
5
  function isNodeVersionSupported(version) {
6
6
  return semver.satisfies(version, NODE_ENGINE_RANGE);
@@ -11,4 +11,4 @@ export {
11
11
  NODE_ENGINE_RANGE,
12
12
  isNodeVersionSupported
13
13
  };
14
- //# sourceMappingURL=chunk-SX77QPB2.js.map
14
+ //# sourceMappingURL=chunk-3HRKK3TB.js.map
@@ -1244,6 +1244,56 @@ var DEFAULT_MODEL_CAPABILITIES = {
1244
1244
  },
1245
1245
  // ----- OpenAI Codex -----
1246
1246
  {
1247
+ // #6516 (panel option A): the codex default since gpt-5.5 retires.
1248
+ // ~/.codex/models_cache.json (codex-cli 0.155.1, read 2026-09-23) puts
1249
+ // an `upgrade` record on the gpt-5.5 row: retirement_at
1250
+ // 2026-10-14T19:00:00Z, upgrade.model gpt-5.6-sol. The id equals the
1251
+ // served slug (the #5489 direction), so no alias layer is needed.
1252
+ // SOURCES:
1253
+ // - displayName, contextWindow, maxOutputTokens, pricing: models.dev
1254
+ // `gpt-5.6-sol` in the committed models-dev-snapshot.json (2026-09-21),
1255
+ // matching `openai/gpt-5.6-sol` in model-registry.generated.json
1256
+ // (2026-09-23): $4/$20 per 1M, 1.05M context, 128K output.
1257
+ // - inputModalities (text/image/pdf): the same models.dev entry.
1258
+ // - notes' description, reasoning levels and 272K default window: the
1259
+ // codex cache row (default_reasoning_level low; supported low, medium,
1260
+ // high, xhigh, max, ultra; context_window 272000).
1261
+ // - qualityScores: CARRIED OVER from gpt-5.5, NOT measured. It is the
1262
+ // successor at the same tier position; `cost` stays 4 although the
1263
+ // price fell ($4/$20 vs $5/$30), so a rescore is a separate decision.
1264
+ // - toolCapabilities, outputModalities, unsupportedParameters,
1265
+ // maxTokensParam: carried from gpt-5.5 (same family and CLI transport).
1266
+ // Listed BEFORE gpt-5.5 so a scoring tie between the two resolves to the
1267
+ // served successor, not the retiring slug.
1268
+ id: "gpt-5.6-sol",
1269
+ displayName: "GPT-5.6 Sol",
1270
+ provider: "openai",
1271
+ contextWindow: 105e4,
1272
+ outputModalities: ["text", "structured_json", "code"],
1273
+ inputModalities: ["text", "image", "pdf", "code"],
1274
+ toolCapabilities: [
1275
+ "function_calling",
1276
+ "code_execution_sandbox",
1277
+ "web_search",
1278
+ "file_operations",
1279
+ "structured_output",
1280
+ "apply_patch",
1281
+ "computer_use"
1282
+ ],
1283
+ specialFeatures: ["streaming"],
1284
+ notes: 'GPT-5.6 Sol (models.dev 2026-09-21; codex catalog: "older coding model for complex work"); codex default and gpt-5.5 successor per the codex cache; served by codex-cli 0.155.1; reasoning low..ultra; 1.05M context (codex cache default window 272K)',
1285
+ pricing: { inputPer1M: 4, outputPer1M: 20 },
1286
+ qualityScores: { reasoning: 10, codeGeneration: 10, speed: 7, cost: 4 },
1287
+ maxOutputTokens: 128e3,
1288
+ cliName: "codex",
1289
+ cliModelName: "gpt-5.6-sol",
1290
+ unsupportedParameters: ["temperature"],
1291
+ maxTokensParam: "max_completion_tokens"
1292
+ },
1293
+ {
1294
+ // Retires in codex 2026-10-14 (codex cache upgrade record); no longer the
1295
+ // codex default (#6516). Kept routable for configs that pin it; removal
1296
+ // is tracked in #6526.
1247
1297
  id: "gpt-5.5",
1248
1298
  displayName: "GPT-5.5",
1249
1299
  provider: "openai",
@@ -1482,10 +1532,12 @@ var DEFAULT_MODEL_CAPABILITIES = {
1482
1532
  ]
1483
1533
  };
1484
1534
  var DEFAULT_MODEL_PER_CLI = {
1485
- // #4176: fable/gpt-5.5 are strongest per CLI; gemini-3.5-flash is flash-tier, not default.
1535
+ // #4176: fable/gpt-5.5 were strongest per CLI; gemini-3.5-flash is flash-tier, not default.
1536
+ // #6516: codex moves to gpt-5.6-sol, the upgrade target the codex cache names
1537
+ // for gpt-5.5 (retiring 2026-10-14).
1486
1538
  claude: "claude-fable-5",
1487
1539
  gemini: "gemini-3-pro",
1488
- codex: "gpt-5.5",
1540
+ codex: "gpt-5.6-sol",
1489
1541
  opencode: "opencode-default"
1490
1542
  };
1491
1543
  var STATIC_CLI_COST_PER_1M = {
@@ -1989,6 +2041,7 @@ var MODEL_IDS = [
1989
2041
  "gemini-3.5-flash",
1990
2042
  "gemini-3-flash",
1991
2043
  "gemini-flash",
2044
+ "gpt-5.6-sol",
1992
2045
  "gpt-5.5",
1993
2046
  "codex-5.3",
1994
2047
  "codex-5.2",
@@ -2643,7 +2696,7 @@ function setDefaultRegistry(registry) {
2643
2696
  }
2644
2697
  async function reloadDefaultRegistry() {
2645
2698
  globalRegistry = buildDefaultRegistry();
2646
- const { resetGlobalRegistry } = await import("./unified-registry-Y327PN6R.js");
2699
+ const { resetGlobalRegistry } = await import("./unified-registry-V5N44N4X.js");
2647
2700
  resetGlobalRegistry();
2648
2701
  return globalRegistry;
2649
2702
  }
@@ -10239,11 +10292,14 @@ var OutcomeFailureCategorySchema = z14.enum([
10239
10292
  ]);
10240
10293
  var OutcomeCliSchema = z14.union([CliNameSchema, ApiArmIdSchema, z14.literal("unknown")]);
10241
10294
  var OutcomeCliSourceSchema = z14.enum(["executed", "category-default"]);
10295
+ var OutcomeRoutedBySchema = z14.enum(["composite-router"]);
10242
10296
  var TaskOutcomeSchema = z14.object({
10243
10297
  id: z14.string().min(1),
10244
10298
  cli: OutcomeCliSchema,
10245
10299
  /** How the CLI attribution was obtained. Absent on legacy, unmeasured records. */
10246
10300
  cliSource: OutcomeCliSourceSchema.optional(),
10301
+ /** Set only when `CompositeRouter` selected the CLI for this task (#6521). */
10302
+ routedBy: OutcomeRoutedBySchema.optional(),
10247
10303
  category: TaskCategorySchema,
10248
10304
  model: z14.string().min(1),
10249
10305
  success: z14.boolean(),
@@ -10495,8 +10551,8 @@ function categorizeOutcomeErrorMessage(msg) {
10495
10551
  // src/learning/distiller-eligibility.ts
10496
10552
  var ROUTABLE_CLIS = new Set(CLI_NAMES);
10497
10553
  function isDistillerEligible(outcome) {
10498
- if (outcome.source !== "delegate") return false;
10499
- if (outcome.cliSource !== "executed") return false;
10554
+ if (outcome.routedBy !== "composite-router") return false;
10555
+ if (outcome.source === "consensus") return false;
10500
10556
  if (!(outcome.durationMs > 0)) return false;
10501
10557
  return ROUTABLE_CLIS.has(outcome.cli);
10502
10558
  }
@@ -10509,33 +10565,49 @@ function countEligibleSince(outcomes, sinceMs) {
10509
10565
  }
10510
10566
  return count;
10511
10567
  }
10512
- var eligibilityFieldsSchema;
10513
- function getEligibilityFieldsSchema() {
10514
- eligibilityFieldsSchema ??= TaskOutcomeSchema.pick({
10568
+ var fileFieldsSchema;
10569
+ function getFileFieldsSchema() {
10570
+ fileFieldsSchema ??= TaskOutcomeSchema.pick({
10515
10571
  source: true,
10516
10572
  cli: true,
10517
- cliSource: true,
10518
- durationMs: true
10573
+ routedBy: true,
10574
+ durationMs: true,
10575
+ timestamp: true
10519
10576
  });
10520
- return eligibilityFieldsSchema;
10577
+ return fileFieldsSchema;
10521
10578
  }
10522
10579
  function parseLine(line) {
10523
10580
  try {
10524
- const parsed = getEligibilityFieldsSchema().safeParse(JSON.parse(line));
10581
+ const parsed = getFileFieldsSchema().safeParse(JSON.parse(line));
10525
10582
  return parsed.success ? parsed.data : void 0;
10526
10583
  } catch {
10527
10584
  return void 0;
10528
10585
  }
10529
10586
  }
10530
- function countEligibleOutcomesInFile(filePath) {
10531
- if (!existsSync6(filePath)) return 0;
10532
- let count = 0;
10587
+ function readOutcomeFields(filePath) {
10588
+ if (!existsSync6(filePath)) return [];
10589
+ const records = [];
10533
10590
  for (const line of readFileSync6(filePath, "utf-8").split("\n")) {
10534
10591
  if (line.trim().length === 0) continue;
10535
10592
  const fields = parseLine(line);
10536
- if (fields !== void 0 && isDistillerEligible(fields)) count++;
10593
+ if (fields !== void 0) records.push(fields);
10537
10594
  }
10538
- return count;
10595
+ return records;
10596
+ }
10597
+ function countEligibleOutcomesInFile(filePath) {
10598
+ return readOutcomeFields(filePath).filter(isDistillerEligible).length;
10599
+ }
10600
+ var WEEK_MS = 7 * 24 * 60 * 60 * 1e3;
10601
+ function countRoutedOutcomesInFile(filePath, nowMs) {
10602
+ let total = 0;
10603
+ let last7Days = 0;
10604
+ for (const record of readOutcomeFields(filePath)) {
10605
+ if (record.routedBy !== "composite-router") continue;
10606
+ total++;
10607
+ const at = Date.parse(record.timestamp);
10608
+ if (at > nowMs - WEEK_MS && at <= nowMs) last7Days++;
10609
+ }
10610
+ return { total, last7Days };
10539
10611
  }
10540
10612
 
10541
10613
  // src/learning/strategy-distiller.ts
@@ -16014,7 +16086,7 @@ var CompositeRouter = class _CompositeRouter {
16014
16086
  */
16015
16087
  async consultUnifiedContext(task) {
16016
16088
  try {
16017
- const { getContextForTask, inferTaskCategory } = await import("./context-retriever-NZOSGG6S.js");
16089
+ const { getContextForTask, inferTaskCategory } = await import("./context-retriever-7T56LVZN.js");
16018
16090
  const ctx = await getContextForTask({
16019
16091
  task: task.content,
16020
16092
  category: inferTaskCategory(task.content),
@@ -16055,11 +16127,18 @@ var CompositeRouter = class _CompositeRouter {
16055
16127
  logger: this.logger
16056
16128
  });
16057
16129
  this.recordToOrchestrationObserver(decision, task);
16130
+ const armStart = getTimeProvider().now();
16058
16131
  const executeResult = await decision.adapter.execute(task);
16132
+ const armDurationMs = getTimeProvider().now() - armStart;
16059
16133
  const durationMs = getTimeProvider().now() - startTime;
16060
16134
  const success = executeResult.ok;
16061
16135
  this.autoRecordFeedback(decision, task, success, durationMs);
16062
- return executeResult;
16136
+ const routed = {
16137
+ routedCli: routingArmDisplaySlot(decision.cliName),
16138
+ routedDurationMs: armDurationMs
16139
+ };
16140
+ if (!executeResult.ok) return err({ ...executeResult.error, ...routed });
16141
+ return ok({ ...executeResult.value, ...routed });
16063
16142
  }
16064
16143
  autoRecordFeedback(decision, task, success, durationMs) {
16065
16144
  const arm = decision.cliName;
@@ -17598,6 +17677,7 @@ export {
17598
17677
  createRoutingMemory,
17599
17678
  DEFAULT_DISTILLER_CONFIG,
17600
17679
  countEligibleOutcomesInFile,
17680
+ countRoutedOutcomesInFile,
17601
17681
  sigmoidConfidence,
17602
17682
  effectFor,
17603
17683
  detectFailurePatterns,
@@ -17650,4 +17730,4 @@ export {
17650
17730
  AgentCapability,
17651
17731
  OrchestratorError
17652
17732
  };
17653
- //# sourceMappingURL=chunk-64IJKT4I.js.map
17733
+ //# sourceMappingURL=chunk-56SU2GM2.js.map