@theokit/sdk 5.14.0 → 5.15.1

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 (214) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/dist/{agent-T34LCGQM.js → agent-66U5QCPF.js} +18 -17
  3. package/dist/{agent-T34LCGQM.js.map → agent-66U5QCPF.js.map} +1 -1
  4. package/dist/{agent-DExqjqYy.d.cts → agent-BL4kxgwq.d.cts} +30 -214
  5. package/dist/{agent-Dfw3VsIX.d.ts → agent-ByDx7K30.d.ts} +30 -214
  6. package/dist/{agent-TL4K7BTG.cjs → agent-CB27KF6O.cjs} +19 -18
  7. package/dist/{agent-TL4K7BTG.cjs.map → agent-CB27KF6O.cjs.map} +1 -1
  8. package/dist/agent.d.ts +2 -3
  9. package/dist/{batch-EP3FCL6D.js → batch-N2XDYZED.js} +4 -4
  10. package/dist/{batch-EP3FCL6D.js.map → batch-N2XDYZED.js.map} +1 -1
  11. package/dist/{batch-IZ5EDKJ5.cjs → batch-VFR2MAUE.cjs} +7 -7
  12. package/dist/{batch-IZ5EDKJ5.cjs.map → batch-VFR2MAUE.cjs.map} +1 -1
  13. package/dist/{chunk-ZOL3L4EH.js → chunk-26GI3OYA.js} +118 -21
  14. package/dist/chunk-26GI3OYA.js.map +1 -0
  15. package/dist/{chunk-2WY2OFSC.cjs → chunk-26UQG242.cjs} +616 -318
  16. package/dist/chunk-26UQG242.cjs.map +1 -0
  17. package/dist/{chunk-2C24NSNV.js → chunk-3BBTHFGJ.js} +3 -3
  18. package/dist/{chunk-2C24NSNV.js.map → chunk-3BBTHFGJ.js.map} +1 -1
  19. package/dist/{chunk-SNVYOX46.cjs → chunk-3E3VSMB6.cjs} +160 -63
  20. package/dist/chunk-3E3VSMB6.cjs.map +1 -0
  21. package/dist/{chunk-NP362THY.cjs → chunk-3F53FLQ7.cjs} +5 -7
  22. package/dist/chunk-3F53FLQ7.cjs.map +1 -0
  23. package/dist/{chunk-SXH37C7X.cjs → chunk-55LLQFHW.cjs} +6 -6
  24. package/dist/{chunk-SXH37C7X.cjs.map → chunk-55LLQFHW.cjs.map} +1 -1
  25. package/dist/{chunk-ZJAYFSVI.js → chunk-7ACS6P5Z.js} +5 -7
  26. package/dist/chunk-7ACS6P5Z.js.map +1 -0
  27. package/dist/{chunk-WDVG5R2Q.cjs → chunk-AUH2EVWY.cjs} +4 -3
  28. package/dist/chunk-AUH2EVWY.cjs.map +1 -0
  29. package/dist/chunk-BNEUB52I.cjs +55 -0
  30. package/dist/chunk-BNEUB52I.cjs.map +1 -0
  31. package/dist/chunk-BPL5CVZ5.js +53 -0
  32. package/dist/chunk-BPL5CVZ5.js.map +1 -0
  33. package/dist/{chunk-NVQSBRG6.js → chunk-CBBT42VX.js} +3 -3
  34. package/dist/{chunk-NVQSBRG6.js.map → chunk-CBBT42VX.js.map} +1 -1
  35. package/dist/chunk-CHKV2L2Y.cjs +416 -0
  36. package/dist/chunk-CHKV2L2Y.cjs.map +1 -0
  37. package/dist/{chunk-LXG6VL6R.cjs → chunk-FBIDOOJM.cjs} +3 -3
  38. package/dist/{chunk-LXG6VL6R.cjs.map → chunk-FBIDOOJM.cjs.map} +1 -1
  39. package/dist/{chunk-354F3OF5.js → chunk-FGGVSHDW.js} +3 -3
  40. package/dist/{chunk-354F3OF5.js.map → chunk-FGGVSHDW.js.map} +1 -1
  41. package/dist/{chunk-6OCJWGVD.cjs → chunk-FTXY4D44.cjs} +4 -4
  42. package/dist/{chunk-6OCJWGVD.cjs.map → chunk-FTXY4D44.cjs.map} +1 -1
  43. package/dist/chunk-INVEGVGO.js +405 -0
  44. package/dist/chunk-INVEGVGO.js.map +1 -0
  45. package/dist/{chunk-DF77RBF4.js → chunk-LCCT5ZXJ.js} +6 -6
  46. package/dist/{chunk-DF77RBF4.js.map → chunk-LCCT5ZXJ.js.map} +1 -1
  47. package/dist/{chunk-G7XBVM3T.cjs → chunk-MHUOVS5I.cjs} +5 -5
  48. package/dist/{chunk-G7XBVM3T.cjs.map → chunk-MHUOVS5I.cjs.map} +1 -1
  49. package/dist/{chunk-CWQPQTUZ.cjs → chunk-NEH3BPFD.cjs} +15 -15
  50. package/dist/{chunk-CWQPQTUZ.cjs.map → chunk-NEH3BPFD.cjs.map} +1 -1
  51. package/dist/{chunk-5AR6O7GW.js → chunk-NK5EOTDY.js} +3 -3
  52. package/dist/{chunk-5AR6O7GW.js.map → chunk-NK5EOTDY.js.map} +1 -1
  53. package/dist/{chunk-NAVUTK6X.js → chunk-O2RCS3SJ.js} +3 -3
  54. package/dist/{chunk-NAVUTK6X.js.map → chunk-O2RCS3SJ.js.map} +1 -1
  55. package/dist/{chunk-4TEGFMSP.cjs → chunk-P7QYG4RZ.cjs} +23 -15
  56. package/dist/chunk-P7QYG4RZ.cjs.map +1 -0
  57. package/dist/chunk-PPU2D4FZ.js +19 -0
  58. package/dist/chunk-PPU2D4FZ.js.map +1 -0
  59. package/dist/{chunk-AB4OPJLD.js → chunk-RGVMJU57.js} +3 -3
  60. package/dist/{chunk-AB4OPJLD.js.map → chunk-RGVMJU57.js.map} +1 -1
  61. package/dist/{chunk-4KBI37F3.cjs → chunk-RTDVSHJR.cjs} +5 -5
  62. package/dist/{chunk-4KBI37F3.cjs.map → chunk-RTDVSHJR.cjs.map} +1 -1
  63. package/dist/{chunk-CJN5CEI3.js → chunk-RZL2W4C3.js} +23 -15
  64. package/dist/chunk-RZL2W4C3.js.map +1 -0
  65. package/dist/chunk-SPEN7RJU.cjs +18 -0
  66. package/dist/{chunk-R5UQL2R5.cjs.map → chunk-SPEN7RJU.cjs.map} +1 -1
  67. package/dist/{chunk-BZK5QL3N.cjs → chunk-TRPRTZEH.cjs} +4 -4
  68. package/dist/{chunk-BZK5QL3N.cjs.map → chunk-TRPRTZEH.cjs.map} +1 -1
  69. package/dist/{chunk-ZF2LDKQQ.cjs → chunk-U3DW3WDE.cjs} +9 -8
  70. package/dist/chunk-U3DW3WDE.cjs.map +1 -0
  71. package/dist/{chunk-H7G65PNI.js → chunk-VCQ37TC5.js} +3 -3
  72. package/dist/{chunk-H7G65PNI.js.map → chunk-VCQ37TC5.js.map} +1 -1
  73. package/dist/{chunk-3ONIVO2I.js → chunk-VNRNZ3WI.js} +3 -3
  74. package/dist/{chunk-3ONIVO2I.js.map → chunk-VNRNZ3WI.js.map} +1 -1
  75. package/dist/{chunk-SDZ4XDWS.cjs → chunk-VWYFGE27.cjs} +9 -9
  76. package/dist/{chunk-SDZ4XDWS.cjs.map → chunk-VWYFGE27.cjs.map} +1 -1
  77. package/dist/{chunk-RN3XDZGS.js → chunk-WM646HEN.js} +4 -3
  78. package/dist/chunk-WM646HEN.js.map +1 -0
  79. package/dist/chunk-X7CE7Y5W.js +305 -0
  80. package/dist/chunk-X7CE7Y5W.js.map +1 -0
  81. package/dist/{chunk-CGH4BCIY.cjs → chunk-XE3CAY6Z.cjs} +5 -5
  82. package/dist/{chunk-CGH4BCIY.cjs.map → chunk-XE3CAY6Z.cjs.map} +1 -1
  83. package/dist/chunk-XOU3CL7S.cjs +312 -0
  84. package/dist/chunk-XOU3CL7S.cjs.map +1 -0
  85. package/dist/{chunk-ULEK4OM4.js → chunk-YKNBTHMD.js} +3 -3
  86. package/dist/{chunk-ULEK4OM4.js.map → chunk-YKNBTHMD.js.map} +1 -1
  87. package/dist/{chunk-GARVAUCU.js → chunk-ZQWRUJHE.js} +534 -236
  88. package/dist/chunk-ZQWRUJHE.js.map +1 -0
  89. package/dist/{compact-session-D2MQDB6G.cjs → compact-session-CHBJOYWP.cjs} +16 -16
  90. package/dist/{compact-session-D2MQDB6G.cjs.map → compact-session-CHBJOYWP.cjs.map} +1 -1
  91. package/dist/{compact-session-N2PPHQO6.js → compact-session-F3J3FMEU.js} +7 -7
  92. package/dist/{compact-session-N2PPHQO6.js.map → compact-session-F3J3FMEU.js.map} +1 -1
  93. package/dist/{cron-CK2v0VWA.d.cts → cron-B7KH9sHW.d.cts} +2 -2
  94. package/dist/{cron-BubDpFJG.d.ts → cron-FEO7UAQF.d.ts} +2 -2
  95. package/dist/cron.cjs +18 -17
  96. package/dist/cron.d.cts +4 -3
  97. package/dist/cron.d.ts +4 -3
  98. package/dist/cron.js +17 -16
  99. package/dist/eval.cjs +17 -16
  100. package/dist/eval.cjs.map +1 -1
  101. package/dist/eval.js +16 -15
  102. package/dist/eval.js.map +1 -1
  103. package/dist/fs-session-store-CYNTEPJZ.cjs +20 -0
  104. package/dist/{fs-session-store-S2AXVJIX.cjs.map → fs-session-store-CYNTEPJZ.cjs.map} +1 -1
  105. package/dist/fs-session-store-MYQEVUFL.js +11 -0
  106. package/dist/{fs-session-store-6ZCCJX3K.js.map → fs-session-store-MYQEVUFL.js.map} +1 -1
  107. package/dist/{index-manager-HO456AVW.cjs → index-manager-2KH75BRW.cjs} +7 -7
  108. package/dist/{index-manager-HO456AVW.cjs.map → index-manager-2KH75BRW.cjs.map} +1 -1
  109. package/dist/{index-manager-QDH56FER.js → index-manager-NF2WRLOU.js} +6 -6
  110. package/dist/{index-manager-QDH56FER.js.map → index-manager-NF2WRLOU.js.map} +1 -1
  111. package/dist/index.cjs +66 -262
  112. package/dist/index.cjs.map +1 -1
  113. package/dist/index.d.cts +10 -46
  114. package/dist/index.d.ts +10 -46
  115. package/dist/index.js +27 -227
  116. package/dist/index.js.map +1 -1
  117. package/dist/{inject-session-J26SHHIO.js → inject-session-LC2TROHM.js} +3 -3
  118. package/dist/{inject-session-J26SHHIO.js.map → inject-session-LC2TROHM.js.map} +1 -1
  119. package/dist/{inject-session-3ICZIJ2N.cjs → inject-session-T4RXANG3.cjs} +4 -4
  120. package/dist/{inject-session-3ICZIJ2N.cjs.map → inject-session-T4RXANG3.cjs.map} +1 -1
  121. package/dist/internal/agent-loop/doom-loop-tracker.d.ts +3 -0
  122. package/dist/internal/agent-loop/types.d.ts +6 -0
  123. package/dist/internal/error-mappers/anthropic.d.ts +3 -0
  124. package/dist/internal/error-mappers/openai-compatible.d.ts +2 -3
  125. package/dist/internal/llm/hermes-tool-extract.d.ts +2 -0
  126. package/dist/internal/local-agent/local-agent-dispatch.d.ts +3 -1
  127. package/dist/internal/local-agent/send-queue.d.ts +31 -0
  128. package/dist/internal/mcp/client.d.ts +2 -0
  129. package/dist/internal/mcp/oauth-bearer.d.ts +2 -0
  130. package/dist/internal/memory/adapters/index.cjs +3 -3
  131. package/dist/internal/memory/adapters/index.js +2 -2
  132. package/dist/internal/memory/dreaming/phases.d.ts +15 -0
  133. package/dist/internal/memory/dreaming/run.d.ts +29 -0
  134. package/dist/internal/memory/sdk-memory-peer-loader.d.ts +2 -0
  135. package/dist/internal/memory/storage/index.cjs +51 -35
  136. package/dist/internal/memory/storage/index.d.cts +2 -0
  137. package/dist/internal/memory/storage/index.d.ts +2 -0
  138. package/dist/internal/memory/storage/index.js +4 -4
  139. package/dist/internal/persistence/cwd-mutex.d.cts +4 -2
  140. package/dist/internal/persistence/cwd-mutex.d.ts +4 -2
  141. package/dist/internal/persistence/index.cjs +4 -4
  142. package/dist/internal/persistence/index.js +2 -2
  143. package/dist/internal/persistence/sqlite-session-store.d.cts +25 -0
  144. package/dist/internal/persistence/sqlite-session-store.d.ts +25 -0
  145. package/dist/internal/providers/registry.d.ts +5 -1
  146. package/dist/mcp-auth.cjs +25 -307
  147. package/dist/mcp-auth.cjs.map +1 -1
  148. package/dist/mcp-auth.js +5 -305
  149. package/dist/mcp-auth.js.map +1 -1
  150. package/dist/models.cjs +9 -9
  151. package/dist/models.js +2 -2
  152. package/dist/persistence.cjs +9 -4
  153. package/dist/persistence.cjs.map +1 -1
  154. package/dist/persistence.d.cts +744 -40
  155. package/dist/persistence.d.ts +744 -40
  156. package/dist/persistence.js +3 -2
  157. package/dist/persistence.js.map +1 -1
  158. package/dist/providers.cjs +4 -4
  159. package/dist/providers.js +2 -2
  160. package/dist/sandbox/docker-sandbox.d.cts +58 -0
  161. package/dist/sandbox/docker-sandbox.d.ts +58 -0
  162. package/dist/sandbox/index.cjs +129 -1
  163. package/dist/sandbox/index.cjs.map +1 -1
  164. package/dist/sandbox/index.d.cts +1 -0
  165. package/dist/sandbox/index.d.ts +1 -0
  166. package/dist/sandbox/index.js +132 -5
  167. package/dist/sandbox/index.js.map +1 -1
  168. package/dist/{sdk-agent-DwzHcuxy.d.cts → sdk-agent-BA_6_wtc.d.cts} +30 -2
  169. package/dist/{sdk-agent-a3fW1xUK.d.ts → sdk-agent-CnwPODYH.d.ts} +30 -2
  170. package/dist/session-store-Dh07jr9N.d.cts +209 -0
  171. package/dist/session-store-Dh07jr9N.d.ts +209 -0
  172. package/dist/sqlite-session-store-BbcpKY1L.d.ts +64 -0
  173. package/dist/sqlite-session-store-TKXtT4ON.d.cts +64 -0
  174. package/dist/subagents-loader-KLWF4QPD.cjs +16 -0
  175. package/dist/{subagents-loader-TXOA5EJJ.cjs.map → subagents-loader-KLWF4QPD.cjs.map} +1 -1
  176. package/dist/subagents-loader-SXETS2F2.js +7 -0
  177. package/dist/{subagents-loader-Z744TAKD.js.map → subagents-loader-SXETS2F2.js.map} +1 -1
  178. package/dist/subagents-loader.cjs +2 -2
  179. package/dist/subagents-loader.d.cts +3 -2
  180. package/dist/subagents-loader.d.ts +3 -2
  181. package/dist/subagents-loader.js +1 -1
  182. package/dist/types/agent.d.ts +14 -1
  183. package/dist/types/budget-tracker.d.ts +6 -2
  184. package/dist/types/hooks.d.ts +7 -1
  185. package/dist/types/mcp.d.ts +14 -0
  186. package/dist/types/run.d.ts +15 -1
  187. package/dist/workflow.d.cts +1 -1
  188. package/dist/workflow.d.ts +1 -1
  189. package/docs/adr/mutation-testing-scope.md +12 -2
  190. package/docs/error-codes.md +41 -40
  191. package/docs/harness-capability-map.md +32 -6
  192. package/package.json +1 -1
  193. package/dist/chunk-2WY2OFSC.cjs.map +0 -1
  194. package/dist/chunk-4TEGFMSP.cjs.map +0 -1
  195. package/dist/chunk-6CXRYPG7.cjs +0 -211
  196. package/dist/chunk-6CXRYPG7.cjs.map +0 -1
  197. package/dist/chunk-CJN5CEI3.js.map +0 -1
  198. package/dist/chunk-GARVAUCU.js.map +0 -1
  199. package/dist/chunk-MSEL5E5P.js +0 -204
  200. package/dist/chunk-MSEL5E5P.js.map +0 -1
  201. package/dist/chunk-NP362THY.cjs.map +0 -1
  202. package/dist/chunk-Q5EWJPRY.js +0 -18
  203. package/dist/chunk-Q5EWJPRY.js.map +0 -1
  204. package/dist/chunk-R5UQL2R5.cjs +0 -18
  205. package/dist/chunk-RN3XDZGS.js.map +0 -1
  206. package/dist/chunk-SNVYOX46.cjs.map +0 -1
  207. package/dist/chunk-WDVG5R2Q.cjs.map +0 -1
  208. package/dist/chunk-ZF2LDKQQ.cjs.map +0 -1
  209. package/dist/chunk-ZJAYFSVI.js.map +0 -1
  210. package/dist/chunk-ZOL3L4EH.js.map +0 -1
  211. package/dist/fs-session-store-6ZCCJX3K.js +0 -11
  212. package/dist/fs-session-store-S2AXVJIX.cjs +0 -20
  213. package/dist/subagents-loader-TXOA5EJJ.cjs +0 -16
  214. package/dist/subagents-loader-Z744TAKD.js +0 -7
@@ -64,7 +64,7 @@ var PROVIDER_DETAIL_MAX_CHARS = 512;
64
64
  function mapOpenAICompatibleError(args) {
65
65
  const { providerId, status, body, headers, endpoint } = args;
66
66
  const code = mapOpenAiStatusToCode(status, body);
67
- const message = formatMessage(providerId, status, code);
67
+ const message = formatMessage(providerId, status, code, boundedProviderDetail(body));
68
68
  const metadata = buildErrorMetadata({
69
69
  provider: providerId,
70
70
  endpoint,
@@ -80,15 +80,13 @@ function mapOpenAICompatibleError(args) {
80
80
  return new chunkCEGU5AVD_cjs.RateLimitError(message, { code: `${providerId}_rate_limit`, metadata });
81
81
  }
82
82
  if (status === 404 && code === "model_unavailable") {
83
- const detailed = formatMessage(providerId, status, code, boundedProviderDetail(body));
84
- return new chunkCEGU5AVD_cjs.ConfigurationError(detailed, {
83
+ return new chunkCEGU5AVD_cjs.ConfigurationError(message, {
85
84
  code: `${providerId}_model_unavailable`,
86
85
  metadata
87
86
  });
88
87
  }
89
88
  if (status === 400) {
90
- const detailed = formatMessage(providerId, status, code, boundedProviderDetail(body));
91
- return new chunkCEGU5AVD_cjs.ConfigurationError(detailed, { code: `${providerId}_${code}`, metadata });
89
+ return new chunkCEGU5AVD_cjs.ConfigurationError(message, { code: `${providerId}_${code}`, metadata });
92
90
  }
93
91
  if (status === 408) {
94
92
  return new chunkCEGU5AVD_cjs.NetworkError(message, { code: `${providerId}_timeout`, metadata });
@@ -160,5 +158,5 @@ exports.httpStatusToErrorCode = httpStatusToErrorCode;
160
158
  exports.mapOpenAICompatibleError = mapOpenAICompatibleError;
161
159
  exports.parseErrorBody = parseErrorBody;
162
160
  exports.parseRetryAfter = parseRetryAfter;
163
- //# sourceMappingURL=chunk-NP362THY.cjs.map
164
- //# sourceMappingURL=chunk-NP362THY.cjs.map
161
+ //# sourceMappingURL=chunk-3F53FLQ7.cjs.map
162
+ //# sourceMappingURL=chunk-3F53FLQ7.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/error-mappers/shared.ts","../src/internal/error-mappers/openai-compatible.ts"],"names":["redactSecrets","AuthenticationError","RateLimitError","ConfigurationError","NetworkError","UnknownAgentError"],"mappings":";;;;;;AAeA,IAAM,aAAA,GAAgB,IAAA;AAUf,SAAS,gBAAgB,OAAA,EAAkD;AAChF,EAAA,IAAI,OAAA,KAAY,QAAW,OAAO,MAAA;AAClC,EAAA,MAAM,GAAA,GAAM,OAAA,CAAQ,GAAA,CAAI,aAAa,CAAA;AACrC,EAAA,IAAI,GAAA,KAAQ,MAAM,OAAO,MAAA;AACzB,EAAA,MAAM,CAAA,GAAI,OAAO,GAAG,CAAA;AACpB,EAAA,IAAI,MAAA,CAAO,SAAS,CAAC,CAAA,IAAK,KAAK,CAAA,EAAG,OAAO,IAAA,CAAK,IAAA,CAAK,CAAC,CAAA;AAEpD,EAAA,MAAM,MAAA,GAAS,IAAA,CAAK,KAAA,CAAM,GAAG,CAAA;AAC7B,EAAA,IAAI,MAAA,CAAO,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AO,IAAA,EAAM,IAAA;AACf;AAEA,SAAS,aAAA,CACP,UAAA,EACA,MAAA,EACA,IAAA,EACA,MAAA,EACQ;AACR,EAAA,MAAM,OAAO,CAAA,EAAG,UAAU,CAAA,YAAA,EAAe,IAAI,UAAU,MAAM,CAAA,CAAA,CAAA;AAC7D,EAAA,OAAO,MAAA,KAAW,UAAa,MAAA,KAAW,EAAA,GAAK,OAAO,CAAA,EAAG,IAAI,KAAK,MAAM,CAAA,CAAA;AAC1E","file":"chunk-3F53FLQ7.cjs","sourcesContent":["/**\nimport type { ErrorCode } from \"../../errors.js\";\n * Helpers shared between provider HTTP error mappers (ADR D67).\n *\n * Extracted to dedupe identical logic in `anthropic.ts` and\n * `openai-compatible.ts` — retry-after parsing, raw-body truncation,\n * and metadata assembly are dialect-agnostic.\n *\n * @internal\n */\n\nimport type { ErrorCode, ErrorMetadata } from \"../../errors.js\";\nimport { redactSecrets } from \"../security/index.js\";\n\n/** Longest `ErrorMetadata.raw`, in UTF-16 code units, before the `…` suffix. */\nconst RAW_MAX_CHARS = 2048;\n\n/**\n * Parse the `Retry-After` header (RFC 7231) into seconds. Both forms are\n * supported: numeric-seconds (`Retry-After: 30`) and HTTP-date\n * (`Retry-After: Wed, 21 Oct 2025 07:28:00 GMT` → seconds until that instant,\n * clamped at 0 for a past date). Garbage / missing header → `undefined`.\n *\n * @internal\n */\nexport function parseRetryAfter(headers: Headers | undefined): number | undefined {\n if (headers === undefined) return undefined;\n const raw = headers.get(\"retry-after\");\n if (raw === null) return undefined;\n const n = Number(raw);\n if (Number.isFinite(n) && n >= 0) return Math.ceil(n);\n // HTTP-date form — seconds until the given instant (0 if already elapsed).\n const dateMs = Date.parse(raw);\n if (Number.isFinite(dateMs)) return Math.max(0, Math.ceil((dateMs - Date.now()) / 1000));\n return undefined;\n}\n\n/**\n * Redact known credential patterns in the raw response body, then\n * cut the redacted text to 2048 characters (UTF-16 code units), so it can ride inside\n * `ErrorMetadata.raw` without ballooning logs OR leaking tokens.\n * Returns `undefined` for null/undefined input.\n *\n * Redaction runs first: a pattern can only mask a credential it sees\n * whole, and cutting first left a key straddling the cut too short for\n * its pattern, so its leading fragment reached `raw` in clear (B-540).\n * The `…` suffix is added exactly when text was dropped.\n *\n * Redaction sees the whole body, however long. Any bound on what it reads\n * brings the edge back: a credential cut by the bound matches nothing, and\n * redaction of the text before it can pull the clear fragment inside the\n * cut, and no fixed margin is enough because JWTs and PEM blocks have no\n * length bound (plan D1, review round 2). The builtin patterns were timed\n * on hostile input and the two that were not linear were fixed (B-544,\n * B-554), so the cost grows with the body's length; a pattern\n * registered with `Security.addPattern` sees the whole body too and\n * should stay linear in its input. The cut never splits a surrogate pair.\n *\n * Post T1.1 (secret-redaction-discipline, ADR D68): every error metadata\n * goes through `redactSecrets` before exposure. Note the shape change —\n * pre-T1.1 the function preserved the original `body` shape when ≤2KB;\n * now it always returns a (possibly redacted) string, because redaction\n * coerces non-strings to JSON. Consumers who used to do `err.metadata.raw.foo`\n * must now `JSON.parse(err.metadata.raw)` first — but a workspace-wide\n * grep at T1.1 land time confirmed zero such callers.\n *\n * @internal\n */\nexport function truncateRaw(body: unknown): unknown {\n if (body === null || body === undefined) return undefined;\n const s = typeof body === \"string\" ? body : JSON.stringify(body);\n const redacted = redactSecrets(s);\n return redacted.length <= RAW_MAX_CHARS ? redacted : `${cutAt(redacted, RAW_MAX_CHARS)}…`;\n}\n\n/** The first `end` code units of `text`, one fewer when that would split a surrogate pair. */\nfunction cutAt(text: string, end: number): string {\n if (end >= text.length) return text;\n const last = text.charCodeAt(end - 1);\n return text.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end);\n}\n\n/**\n * Build an `ErrorMetadata` object with all optional fields included\n * conditionally (no `undefined` keys in the output). Caller passes\n * dialect-specific fields (`provider`, `endpoint`, `code`); shared\n * fields (`statusCode`, `retryAfter`, `raw`) are derived here.\n *\n * @internal\n */\nexport function buildErrorMetadata(args: {\n provider: string;\n endpoint: string;\n code: ErrorCode;\n status: number;\n headers: Headers | undefined;\n body: unknown;\n}): ErrorMetadata {\n const retryAfter = parseRetryAfter(args.headers);\n const raw = truncateRaw(args.body);\n return {\n provider: args.provider,\n endpoint: args.endpoint,\n code: args.code,\n statusCode: args.status,\n ...(retryAfter !== undefined ? { retryAfter } : {}),\n ...(raw !== undefined ? { raw } : {}),\n };\n}\n\n/**\n * D314: extract the provider's request id (`x-request-id` is OpenAI/most;\n * `request-id` is Anthropic). Returns `undefined` when neither is present.\n *\n * @internal\n */\nexport function parseRequestId(headers: Headers | undefined): string | undefined {\n if (headers === undefined) return undefined;\n return headers.get(\"x-request-id\") ?? headers.get(\"request-id\") ?? undefined;\n}\n\n/**\n * The HTTP status ladder — ONE definition, shared by every provider mapper.\n *\n * This is RFC 9110 semantics, not a vendor contract: a 429 means the same thing\n * whether Anthropic, OpenAI, Bedrock or Vertex sent it. It lived in four copies\n * until 2026-09-01 and the copies had already drifted in two measurable ways,\n * which is what moved it here beside the other dialect-agnostic helpers ADR D67\n * extracted:\n *\n * 1. **402 reached one mapper of four.** T3.7 added `quota_exceeded` and wired\n * it into `openai-compatible.ts` only. A Bedrock, Vertex or Anthropic\n * endpoint answering 402 fell through every arm and came back `unknown` —\n * the canonical bucket existed and three of four mappers could not reach it.\n * 2. **The 5xx arm had two different upper bounds.** `anthropic` and\n * `openai-compatible` guarded `>= 500 && < 600`; `bedrock` and `vertex`\n * guarded `>= 500` with no ceiling, so a malformed or proxy-injected 6xx was\n * `server_error` in two mappers and `unknown` in the other two.\n *\n * Neither was a vendor difference. Both were copy-drift, and that is the DRY\n * test in its textbook form: one piece of knowledge, four places to change it.\n *\n * The ladder is deliberately the FALLBACK, never the whole classifier. Each\n * mapper keeps its own body-dialect rules — Anthropic's `context_too_long`,\n * Bedrock's AWS `__type` strings, Vertex's `google.rpc` status enum — because\n * those ARE per-vendor contracts. The shape is\n * `classifyVendorBody(body) ?? httpStatusToErrorCode(status)`.\n *\n * 404 is deliberately NOT mapped here. Three mappers treat it as `unknown` and\n * Bedrock treats it as `invalid_request` via its own `__type` rules; folding it\n * in would silently change three mappers to close a divergence nobody measured.\n *\n * @internal\n */\nexport type HttpStatusErrorCode = Extract<\n ErrorCode,\n | \"auth_failed\"\n | \"quota_exceeded\"\n | \"timeout\"\n | \"rate_limit\"\n | \"invalid_request\"\n | \"server_error\"\n | \"unknown\"\n>;\n\nexport function httpStatusToErrorCode(status: number): HttpStatusErrorCode {\n if (status === 401 || status === 403) return \"auth_failed\";\n if (status === 402) return \"quota_exceeded\";\n if (status === 408) return \"timeout\";\n if (status === 429) return \"rate_limit\";\n if (status === 400) return \"invalid_request\";\n if (status >= 500 && status < 600) return \"server_error\";\n return \"unknown\";\n}\n\n/**\n * Reads an error body that may arrive already parsed, as a JSON string, or as neither.\n *\n * This is TRANSPORT knowledge, not vendor knowledge: it describes how `fetch` surfaces a body, which\n * is the same whichever provider sent it. It lived twice, character-for-character, in bedrock.ts and\n * vertex.ts — identical once the return type name was substituted. They had not drifted, so the cost\n * was only latent: a fix to one would have missed the other silently.\n *\n * Unparseable input yields `{}` rather than throwing, because a mapper's job is to classify a\n * failure that already happened; failing to read the body is not a second failure to report.\n */\nexport function parseErrorBody<T>(body: unknown): T {\n if (body !== null && typeof body === \"object\") return body as T;\n if (typeof body === \"string\") {\n try {\n return JSON.parse(body) as T;\n } catch {\n return {} as T;\n }\n }\n return {} as T;\n}\n","/**\n * OpenAI-compatible HTTP error mapper (ADR D67).\n *\n * Translates OpenAI-shaped API error responses (covers OpenAI, OpenRouter,\n * DeepSeek, Together, Mistral, Voyage, DeepInfra, etc.) into typed\n * `TheokitAgentError` subclasses with full `ErrorMetadata`.\n *\n * Body inspection: looks at `body.error.code` / `body.error.type` to detect\n * `context_too_long`, `content_filtered`, `model_unavailable` semantics, and at\n * `body.error.message` for a 404 that says no endpoint serves the model\n * (OpenRouter's numeric-code body for a retired model id). Every message\n * ends with the provider's text, redacted and capped at 512 characters.\n * Falls back to status-based mapping when body doesn't expose `.error`\n * (e.g., HTML server error page, DeepInfra's `{message: \"...\"}` shape).\n *\n * Never throws — caller is already in an error path.\n *\n * @internal\n */\n\nimport {\n AuthenticationError,\n ConfigurationError,\n type ErrorCode,\n NetworkError,\n RateLimitError,\n type TheokitAgentError,\n UnknownAgentError,\n} from \"../../errors.js\";\nimport { redactSecrets } from \"../security/index.js\";\nimport { buildErrorMetadata, httpStatusToErrorCode } from \"./shared.js\";\n\n// A provider's text joins a message consumers log and show, so it is bounded first. 512 keeps every\n// measured text whole (OpenRouter's 400s run 40 to 60 characters, OpenAI's context-length text\n// about 250); `metadata.raw` keeps up to 2048 bytes of the body for the rest.\nconst PROVIDER_DETAIL_MAX_CHARS = 512;\n\ninterface MapOpenAiErrorArgs {\n providerId: string;\n status: number;\n body: unknown;\n headers: Headers | undefined;\n endpoint: string;\n}\n\nexport function mapOpenAICompatibleError(args: MapOpenAiErrorArgs): TheokitAgentError {\n const { providerId, status, body, headers, endpoint } = args;\n const code = mapOpenAiStatusToCode(status, body);\n // Every status carries the provider's text: it is the only place that says what went wrong.\n const message = formatMessage(providerId, status, code, boundedProviderDetail(body));\n const metadata = buildErrorMetadata({\n provider: providerId,\n endpoint,\n code,\n status,\n headers,\n body,\n });\n\n if (status === 401 || status === 403) {\n return new AuthenticationError(message, { code: `${providerId}_auth_failed`, metadata });\n }\n if (status === 429) {\n return new RateLimitError(message, { code: `${providerId}_rate_limit`, metadata });\n }\n if (status === 404 && code === \"model_unavailable\") {\n return new ConfigurationError(message, {\n code: `${providerId}_model_unavailable`,\n metadata,\n });\n }\n if (status === 400) {\n return new ConfigurationError(message, { code: `${providerId}_${code}`, metadata });\n }\n if (status === 408) {\n return new NetworkError(message, { code: `${providerId}_timeout`, metadata });\n }\n if (status >= 500 && status < 600) {\n return new NetworkError(message, { code: `${providerId}_server_error`, metadata });\n }\n return new UnknownAgentError(message, { code: `${providerId}_unknown`, metadata });\n}\n\nfunction extractOpenAiErrorCode(body: unknown): string | undefined {\n if (body === null || typeof body !== \"object\") return undefined;\n const err = (body as { error?: { code?: unknown; type?: unknown } }).error;\n if (err === undefined || err === null) return undefined;\n if (typeof err.code === \"string\") return err.code;\n if (typeof err.type === \"string\") return err.type;\n return undefined;\n}\n\nfunction extractOpenAiErrorMessage(body: unknown): string | undefined {\n if (body === null || typeof body !== \"object\") return undefined;\n const err = (body as { error?: { message?: unknown } }).error;\n if (err === undefined || err === null) return undefined;\n return typeof err.message === \"string\" ? err.message : undefined;\n}\n\n// Redaction runs before the cut: a key cut first could keep too few characters to match a\n// credential pattern, and its prefix would reach the message unmasked.\nfunction boundedProviderDetail(body: unknown): string | undefined {\n const raw = extractOpenAiErrorMessage(body);\n if (raw === undefined || raw.trim() === \"\") return undefined;\n const redacted = redactSecrets(raw);\n return redacted.length <= PROVIDER_DETAIL_MAX_CHARS\n ? redacted\n : `${redacted.slice(0, PROVIDER_DETAIL_MAX_CHARS)}…`;\n}\n\n// OpenRouter answers a model it does not serve with HTTP 404 and a numeric `error.code`,\n// so only the message tells it apart from a 404 for a wrong path (measured 2026-10-20).\nconst MISSING_MODEL_MESSAGE = /no endpoints found/i;\n\nfunction mapOpenAiStatusToCode(status: number, body: unknown): ErrorCode {\n const fromBodyCode = classifyOpenAiBodyCode(extractOpenAiErrorCode(body)?.toLowerCase() ?? \"\");\n if (fromBodyCode !== undefined) return fromBodyCode;\n if (isMissingModel404(status, body)) return \"model_unavailable\";\n\n // Everything below the body dialect is RFC 9110 and lives once, in shared.ts.\n return httpStatusToErrorCode(status);\n}\n\nfunction isMissingModel404(status: number, body: unknown): boolean {\n return status === 404 && MISSING_MODEL_MESSAGE.test(extractOpenAiErrorMessage(body) ?? \"\");\n}\n\n// The body dialect, in precedence order: the first rule whose fragment appears in the\n// lowercased body code wins.\nconst BODY_CODE_RULES: ReadonlyArray<{ fragments: readonly string[]; code: ErrorCode }> = [\n {\n fragments: [\"context_length\", \"context_window\", \"too_many_tokens\", \"max_tokens\"],\n code: \"context_too_long\",\n },\n { fragments: [\"content_filter\", \"content_policy\", \"safety\"], code: \"content_filtered\" },\n {\n fragments: [\"model_not_found\", \"model_unavailable\", \"invalid_model\"],\n code: \"model_unavailable\",\n },\n // T3.7 — OpenRouter \"Insufficient credits\" / `insufficient_quota` in the BODY.\n // The status-402 half of this rule moved to the shared ladder, where it now\n // reaches all four mappers instead of this one; what stays here is the part\n // that is genuinely a body dialect.\n { fragments: [\"insufficient_quota\", \"quota_exceeded\"], code: \"quota_exceeded\" },\n];\n\nfunction classifyOpenAiBodyCode(rawCode: string): ErrorCode | undefined {\n const rule = BODY_CODE_RULES.find(({ fragments }) =>\n fragments.some((fragment) => rawCode.includes(fragment)),\n );\n return rule?.code;\n}\n\nfunction formatMessage(\n providerId: string,\n status: number,\n code: ErrorCode,\n detail?: string,\n): string {\n const base = `${providerId} API error: ${code} (HTTP ${status})`;\n return detail === undefined || detail === \"\" ? base : `${base}: ${detail}`;\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  var chunkQOGNZMHD_cjs = require('./chunk-QOGNZMHD.cjs');
4
- var chunkZF2LDKQQ_cjs = require('./chunk-ZF2LDKQQ.cjs');
4
+ var chunkU3DW3WDE_cjs = require('./chunk-U3DW3WDE.cjs');
5
5
  var chunkCEGU5AVD_cjs = require('./chunk-CEGU5AVD.cjs');
6
6
  var async_hooks = require('async_hooks');
7
7
 
@@ -149,7 +149,7 @@ var CredentialPool = class _CredentialPool {
149
149
  * @internal
150
150
  */
151
151
  async select() {
152
- return chunkZF2LDKQQ_cjs.withCwdMutex(`credential-pool:${this.provider}`, async () => this.selectLocked());
152
+ return chunkU3DW3WDE_cjs.withCwdMutex(`credential-pool:${this.provider}`, async () => this.selectLocked());
153
153
  }
154
154
  /**
155
155
  * Mark the entry whose id matches `entryId` as exhausted with the
@@ -160,7 +160,7 @@ var CredentialPool = class _CredentialPool {
160
160
  * @internal
161
161
  */
162
162
  async markExhaustedAndRotate(args) {
163
- return chunkZF2LDKQQ_cjs.withCwdMutex(`credential-pool:${this.provider}`, async () => {
163
+ return chunkU3DW3WDE_cjs.withCwdMutex(`credential-pool:${this.provider}`, async () => {
164
164
  const entry = this.entries.find((e) => e.id === args.entryId);
165
165
  if (entry !== void 0) {
166
166
  const now = Date.now();
@@ -175,7 +175,7 @@ var CredentialPool = class _CredentialPool {
175
175
  }
176
176
  /** Admin escape hatch: clear all cooldowns. */
177
177
  async resetAll() {
178
- await chunkZF2LDKQQ_cjs.withCwdMutex(`credential-pool:${this.provider}`, async () => {
178
+ await chunkU3DW3WDE_cjs.withCwdMutex(`credential-pool:${this.provider}`, async () => {
179
179
  for (const e of this.entries) {
180
180
  e.lastStatus = "ok";
181
181
  e.lastStatusAt = void 0;
@@ -276,5 +276,5 @@ exports.CredentialPool = CredentialPool;
276
276
  exports.currentCredentialPool = currentCredentialPool;
277
277
  exports.newPooledCredential = newPooledCredential;
278
278
  exports.withCredentialPool = withCredentialPool;
279
- //# sourceMappingURL=chunk-SXH37C7X.cjs.map
280
- //# sourceMappingURL=chunk-SXH37C7X.cjs.map
279
+ //# sourceMappingURL=chunk-55LLQFHW.cjs.map
280
+ //# sourceMappingURL=chunk-55LLQFHW.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/llm/credential-pool-types.ts","../src/internal/llm/credential-pool.ts","../src/internal/llm/credential-pool-context.ts"],"names":["ConfigurationError","sleepWithAbort","withCwdMutex","picked","AsyncLocalStorage"],"mappings":";;;;;;;;AAyFO,IAAM,WAAA,GAAgD;AAAA,EAC3D,GAAA,EAAK,IAAI,EAAA,GAAK,GAAA;AAAA;AAAA,EACd,GAAA,EAAK,KAAK,EAAA,GAAK,GAAA;AAAA;AAAA,EACf,GAAA,EAAK,KAAK,EAAA,GAAK;AAAA;AACjB,CAAA;AAGO,IAAM,mBAAA,GAAsB,KAAK,EAAA,GAAK,GAAA;;;AC9DtC,SAAS,oBAAoB,IAAA,EAMf;AACnB,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,UAAA,CAAW,MA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123-D133).\n *\n * Pool a developer's multiple API keys for the SAME provider so the SDK\n * can rotate transparently on HTTP 429/402/401 instead of jumping\n * straight to a different provider via `FallbackLlmClient`.\n *\n * @internal\n */\n\n/**\n * Rotation strategy when picking the next credential from a pool.\n *\n * - `fill_first` (default): use entries[0] until exhausted, then [1]…\n * - `round_robin`: rotate after each `select()`\n * - `least_used`: pick the entry with the lowest `requestCount`\n * - `random`: random pick among healthy entries\n *\n * Closed enum per ADR D124 — adding a strategy is an explicit semver\n * minor that updates `selectByStrategy` exhaustively.\n *\n * @internal\n */\nexport type CredentialPoolStrategy = \"fill_first\" | \"round_robin\" | \"least_used\" | \"random\";\n\n/** Health flag tracked per credential. */\nexport type CredentialStatus = \"ok\" | \"exhausted\";\n\n/**\n * Provenance of a credential — where it came from when seeded.\n * Free-form string; conventional prefixes:\n *\n * - `env:<VAR_NAME>` — auto-discovered from environment variable\n * - `manual` — added via explicit `apiKeys` config\n * - `explicit-apikey` — wrapped from `AgentOptions.apiKey` single-key path (D132)\n */\nexport type CredentialSource = string;\n\n/**\n * Single credential entry inside a {@link CredentialPool}.\n *\n * `accessToken` is the sensitive field — must never be logged unredacted.\n * The lint gate `tests/lint/no-unredacted-pool-token.test.ts` enforces this.\n *\n * @internal\n */\nexport interface PooledCredential {\n /** Stable identifier (uuid v4) for log lines + telemetry. */\n id: string;\n /** Human-readable label for `Theokit.credentialPool.list()`. */\n label: string;\n /** Provider name (matches `ProviderProfile.name`). */\n provider: string;\n /** Sort key; lower = earlier in fill_first. Unique within a pool. */\n priority: number;\n /** Provenance string. */\n source: CredentialSource;\n /** Sensitive API key. NEVER LOG UNREDACTED. */\n accessToken: string;\n /** Current health. */\n lastStatus: CredentialStatus;\n /** Epoch ms of the last status change. */\n lastStatusAt: number | undefined;\n /** HTTP code that caused exhaustion (401/402/429). */\n lastErrorCode: number | undefined;\n /** Provider-supplied \"retry after this epoch ms\" hint. Overrides cooldown defaults. */\n lastErrorResetAt: number | undefined;\n /** Bumped per successful `select()` for `least_used` strategy. Lazy-persisted. */\n requestCount: number;\n}\n\n/**\n * Serializable snapshot of a single provider's pool. Used by the\n * persistence layer (T2.1) to read/write `~/.theokit/credential-pool.json`.\n *\n * @internal\n */\nexport interface CredentialPoolSnapshot {\n provider: string;\n strategy: CredentialPoolStrategy;\n entries: PooledCredential[];\n}\n\n/**\n * Cooldown ladder by HTTP error code (ADR D125). Provider-supplied\n * `lastErrorResetAt` overrides these defaults when present.\n *\n * @internal\n */\nexport const COOLDOWN_MS: Readonly<Record<number, number>> = {\n 401: 5 * 60 * 1000, // 5 minutes — OAuth refresh can recover quickly\n 402: 60 * 60 * 1000, // 1 hour — billing quota typically hourly+\n 429: 60 * 60 * 1000, // 1 hour — daily-rate-limit windows\n};\n\n/** Default cooldown when no specific code matches. */\nexport const DEFAULT_COOLDOWN_MS = 60 * 60 * 1000;\n","/**\n * In-memory credential pool with strategy-based rotation (ADRs D123-D133).\n *\n * Pure logic. No I/O — persistence lives in `internal/persistence/\n * credential-pool-store.ts`. The pool is the single source of truth for\n * rotation state within a process; if it diverges from disk (e.g.,\n * process killed mid-rotation per EC-I), the next save heals the\n * inconsistency — at the cost of one extra HTTP 429 per crash.\n *\n * Thread safety: the pool uses an in-process async-aware mutex\n * (`cwd-mutex` D9 keyed by `credential-pool:${provider}`). Cross-process\n * safety happens at the persistence layer via `withFileLock` (D61).\n * Two Node processes sharing the same file may double-pick momentarily\n * (worst case = 1 extra 429 per race) — acceptable per ADR D128.\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { withCwdMutex } from \"../persistence/cwd-mutex.js\";\nimport {\n COOLDOWN_MS,\n type CredentialPoolSnapshot,\n type CredentialPoolStrategy,\n DEFAULT_COOLDOWN_MS,\n type PooledCredential,\n} from \"./credential-pool-types.js\";\nimport { sleepWithAbort } from \"./retry.js\";\n\n/**\n * Construct a `PooledCredential` with sane defaults.\n *\n * @internal\n */\nexport function newPooledCredential(args: {\n provider: string;\n accessToken: string;\n priority: number;\n source: string;\n label?: string;\n}): PooledCredential {\n return {\n id: globalThis.crypto.randomUUID(),\n label: args.label ?? labelFromSource(args.source, args.accessToken),\n provider: args.provider,\n priority: args.priority,\n source: args.source,\n accessToken: args.accessToken,\n lastStatus: \"ok\",\n lastStatusAt: undefined,\n lastErrorCode: undefined,\n lastErrorResetAt: undefined,\n requestCount: 0,\n };\n}\n\n/**\n * Build a human-readable label from the credential source. Used for\n * `Theokit.credentialPool.list()` UX. NEVER includes the raw token.\n *\n * @internal\n */\nfunction labelFromSource(source: string, accessToken: string): string {\n if (source.startsWith(\"env:\")) return source.slice(4);\n const masked =\n accessToken.length > 8 ? `${accessToken.slice(0, 4)}…${accessToken.slice(-4)}` : \"***\";\n return `${source}:${masked}`;\n}\n\n/**\n * Per-provider credential pool. Construct with one or more entries\n * sorted by priority. Throws `ConfigurationError` on empty input.\n *\n * EC-C: identical `accessToken`s are deduplicated during construction\n * (3 copies of \"k1\" → 1 entry). Otherwise an exhaustion event would\n * mark \"k1\" exhausted 3× wastefully.\n *\n * @internal\n */\nexport class CredentialPool {\n readonly provider: string;\n private readonly strategy: CredentialPoolStrategy;\n private entries: PooledCredential[];\n\n constructor(\n provider: string,\n entries: PooledCredential[],\n strategy: CredentialPoolStrategy = \"fill_first\",\n ) {\n if (entries.length === 0) {\n throw new ConfigurationError(\n `credential-pool: cannot construct empty pool for provider \"${provider}\"`,\n { code: \"credential_pool_empty\" },\n );\n }\n this.provider = provider;\n this.strategy = strategy;\n // EC-C: dedupe by accessToken before sort.\n this.entries = dedupeByToken(entries).sort((a, b) => a.priority - b.priority);\n }\n\n /** True if the pool was seeded with at least one entry. */\n hasCredentials(): boolean {\n return this.entries.length > 0;\n }\n\n /** True iff at least one entry is healthy (auto-healed if cooldown expired). */\n hasAvailable(): boolean {\n return this.availableEntries().length > 0;\n }\n\n /**\n * Earliest `lastErrorResetAt` across all entries, or `undefined` if no\n * entry is in cooldown. Used by `waitForAvailable` to compute the\n * upper bound of each jittered sleep window.\n *\n * @internal\n */\n earliestResetAt(): number | undefined {\n let earliest: number | undefined;\n for (const entry of this.entries) {\n if (entry.lastStatus === \"ok\") continue;\n if (entry.lastErrorResetAt === undefined) continue;\n if (earliest === undefined || entry.lastErrorResetAt < earliest) {\n earliest = entry.lastErrorResetAt;\n }\n }\n return earliest;\n }\n\n /**\n * Wait until at least one entry becomes healthy OR `maxWaitMs` elapses\n * OR `signal` aborts. Returns `true` if a healthy entry is available\n * when the call returns, `false` otherwise.\n *\n * T3.9 — Reconnect storm prevention. Concurrent callers each sleep a\n * random fraction of the window to the earliest cooldown reset (full\n * jitter — AWS Brooker 2015) so they do not all wake at the exact\n * instant cooldown expires and hammer the upstream simultaneously.\n *\n * The `sleeper` parameter is a dependency-injection seam for tests:\n * callers in production omit it and the default `setTimeout`-based\n * sleeper is used. The seam avoids the `vi.useFakeTimers()` mismatch\n * that blocked T3.4's wiring.\n *\n * @internal\n */\n async waitForAvailable(\n signal: AbortSignal,\n opts: {\n maxWaitMs: number;\n sleeper?: (ms: number, signal: AbortSignal) => Promise<void>;\n /**\n * Clock seam, the companion to `sleeper`. Production omits it and gets `Date.now`.\n *\n * `sleeper` alone was not enough to make this loop testable: a test could replace the SLEEP\n * but the deadline check still read real wall-clock, so the one case that exercises timeout\n * had to set `maxWaitMs: 5` and race the scheduler — with a comment in the committed file\n * saying so (\"we can't easily ... spec is wall-clock based\"). A sleeper that also advances a\n * virtual clock closes the loop deterministically, which is what `rules/testing.md` § 6 asks\n * for when it says to inject the clock rather than sleep.\n */\n now?: () => number;\n },\n ): Promise<boolean> {\n if (signal.aborted) return false;\n if (this.hasAvailable()) return true;\n const now = opts.now ?? Date.now;\n return await this.pollUntilAvailable(\n signal,\n now() + opts.maxWaitMs,\n opts.sleeper ?? sleepWithAbort,\n now,\n );\n }\n\n /**\n * The polling half of `waitForAvailable`, with both seams already resolved.\n *\n * Its own method because resolving two optional seams and running the loop in one body put the\n * function over the cognitive-complexity gate. The split is also the honest one: everything above\n * is a guard, everything here is the wait.\n */\n private async pollUntilAvailable(\n signal: AbortSignal,\n deadline: number,\n sleeper: (ms: number, signal: AbortSignal) => Promise<void>,\n now: () => number,\n ): Promise<boolean> {\n while (now() < deadline) {\n if (signal.aborted) return false;\n await sleeper(this.computeJitteredSleepMs(deadline, now), signal);\n if (signal.aborted) return false;\n if (this.hasAvailable()) return true;\n }\n return this.hasAvailable();\n }\n\n /**\n * Compute the next jittered sleep window (ms) for `waitForAvailable`.\n * Full-jitter cap: at most (a) time until the earliest reset (plus a\n * 50 ms grace so the entry actually heals before re-probe), or (b) the\n * remaining wait window, whichever is smaller. When no entry has a\n * known reset (rare — only if `markExhaustedAndRotate` was called\n * without `resetAtMs`), fall back to a 250 ms ceiling so we stay\n * responsive without hot-looping.\n */\n private computeJitteredSleepMs(deadline: number, now: () => number = Date.now): number {\n const resetAt = this.earliestResetAt();\n const remaining = deadline - now();\n const ceiling =\n resetAt === undefined\n ? Math.min(remaining, 250)\n : Math.min(remaining, Math.max(0, resetAt - now()) + 50);\n return Math.max(0, Math.floor(Math.random() * ceiling));\n }\n\n /** Live (frozen) view of all entries. */\n list(): readonly PooledCredential[] {\n return this.entries;\n }\n\n /**\n * Pick a healthy entry according to the configured strategy.\n * Mutates `requestCount` and (for round_robin) entry order.\n * Returns null if every entry is in cooldown.\n *\n * @internal\n */\n async select(): Promise<PooledCredential | null> {\n return withCwdMutex(`credential-pool:${this.provider}`, async () => this.selectLocked());\n }\n\n /**\n * Mark the entry whose id matches `entryId` as exhausted with the\n * appropriate cooldown, then return the next healthy entry (or null).\n * If `entryId` is undefined, marks all currently-active entries (rare —\n * only used by admin reset scenarios).\n *\n * @internal\n */\n async markExhaustedAndRotate(args: {\n entryId: string;\n statusCode: number;\n resetAtMs?: number;\n }): Promise<PooledCredential | null> {\n return withCwdMutex(`credential-pool:${this.provider}`, async () => {\n const entry = this.entries.find((e) => e.id === args.entryId);\n if (entry !== undefined) {\n const now = Date.now();\n const cooldown = COOLDOWN_MS[args.statusCode] ?? DEFAULT_COOLDOWN_MS;\n entry.lastStatus = \"exhausted\";\n entry.lastStatusAt = now;\n entry.lastErrorCode = args.statusCode;\n // EC-5: negative or stale resetAt → ignore, fall through to default.\n entry.lastErrorResetAt =\n args.resetAtMs !== undefined && args.resetAtMs > now ? args.resetAtMs : now + cooldown;\n }\n return this.selectLocked();\n });\n }\n\n /** Admin escape hatch: clear all cooldowns. */\n async resetAll(): Promise<void> {\n await withCwdMutex(`credential-pool:${this.provider}`, async () => {\n for (const e of this.entries) {\n e.lastStatus = \"ok\";\n e.lastStatusAt = undefined;\n e.lastErrorCode = undefined;\n e.lastErrorResetAt = undefined;\n }\n });\n }\n\n /** Materialize for persistence. */\n toSnapshot(): CredentialPoolSnapshot {\n return {\n provider: this.provider,\n strategy: this.strategy,\n entries: this.entries.map((e) => ({ ...e })),\n };\n }\n\n /** Hydrate from a previously-saved snapshot. */\n static fromSnapshot(snapshot: CredentialPoolSnapshot): CredentialPool {\n return new CredentialPool(snapshot.provider, snapshot.entries, snapshot.strategy);\n }\n\n // ─── Internal helpers (always called inside the mutex) ───\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: strategy dispatch must branch on 4 enum values (random/least_used/round_robin/fill_first) with 1-entry short-circuits per strategy. Each branch is 5-10 lines of focused logic; extracting per-strategy methods fragments the linear narrative.\n private selectLocked(): PooledCredential | null {\n const available = this.availableEntries();\n if (available.length === 0) return null;\n\n if (this.strategy === \"random\") {\n const idx = Math.floor(Math.random() * available.length);\n const picked = available[idx];\n if (picked === undefined) return null; // unreachable; satisfies strict\n picked.requestCount += 1;\n return picked;\n }\n\n if (this.strategy === \"least_used\" && available.length > 1) {\n // EC-3: tie-break by priority ascending (first wins).\n const picked = [...available].sort(\n (a, b) => a.requestCount - b.requestCount || a.priority - b.priority,\n )[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n return picked;\n }\n\n if (this.strategy === \"round_robin\" && available.length > 1) {\n // Pick head; move it to the end of `entries` so next call picks the next.\n const picked = available[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n const rest = this.entries.filter((e) => e.id !== picked.id);\n // Re-assign priorities: rotated entry gets the highest priority value\n // so it sorts last after `fromSnapshot` rehydration. This makes EC-F\n // (round-robin state survives save/load) work without a separate field.\n const maxPriority = this.entries.length - 1;\n rest.forEach((e, i) => {\n e.priority = i;\n });\n picked.priority = maxPriority;\n this.entries = [...rest, picked];\n return picked;\n }\n\n // fill_first (default) and 1-entry edge case for round_robin/least_used\n const picked = available[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n return picked;\n }\n\n private availableEntries(): PooledCredential[] {\n const now = Date.now();\n const out: PooledCredential[] = [];\n for (const entry of this.entries) {\n if (entry.lastStatus === \"ok\") {\n out.push(entry);\n continue;\n }\n // EC-1: auto-heal expired cooldowns inline.\n const resetAt = entry.lastErrorResetAt;\n if (resetAt !== undefined && now >= resetAt) {\n entry.lastStatus = \"ok\";\n entry.lastStatusAt = undefined;\n entry.lastErrorCode = undefined;\n entry.lastErrorResetAt = undefined;\n out.push(entry);\n }\n }\n return out;\n }\n}\n\n/**\n * Drop duplicates by `accessToken`. Keeps the first occurrence (lowest\n * priority wins after sort). EC-C from the edge-case review.\n */\nfunction dedupeByToken(entries: PooledCredential[]): PooledCredential[] {\n const seen = new Set<string>();\n const out: PooledCredential[] = [];\n for (const e of entries) {\n if (seen.has(e.accessToken)) continue;\n seen.add(e.accessToken);\n out.push(e);\n }\n return out;\n}\n","/**\n * Per-fork credential-pool inheritance via `AsyncLocalStorage` (ADR D131).\n *\n * Mirrors the whitelist context pattern from D111\n * (`runtime/async-local-storage.ts`). Forked sub-agents inherit the\n * parent's pool *by reference* so concurrent rotations all observe\n * the same cooldown state — the desired behavior per Hermes parity.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport type { CredentialPool } from \"./credential-pool.js\";\n\n/** ALS slot — keyed by provider name → pool. */\nconst credentialPoolStore = new AsyncLocalStorage<Map<string, CredentialPool>>();\n\n/**\n * Run `fn` with `pools` as the active credential-pool registry for the\n * current async context. Nested calls shadow the outer map (parent\n * pools are not visible to children when the child sets its own).\n *\n * @internal\n */\nexport async function withCredentialPool<T>(\n pools: Map<string, CredentialPool>,\n fn: () => Promise<T>,\n): Promise<T> {\n return credentialPoolStore.run(pools, fn);\n}\n\n/**\n * Pool registered for `provider` in the current async context, or\n * `undefined` when no `withCredentialPool(...)` scope is active.\n *\n * @internal\n */\nexport function currentCredentialPool(provider: string): CredentialPool | undefined {\n return credentialPoolStore.getStore()?.get(provider);\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/llm/credential-pool-types.ts","../src/internal/llm/credential-pool.ts","../src/internal/llm/credential-pool-context.ts"],"names":["ConfigurationError","sleepWithAbort","withCwdMutex","picked","AsyncLocalStorage"],"mappings":";;;;;;;;AAyFO,IAAM,WAAA,GAAgD;AAAA,EAC3D,GAAA,EAAK,IAAI,EAAA,GAAK,GAAA;AAAA;AAAA,EACd,GAAA,EAAK,KAAK,EAAA,GAAK,GAAA;AAAA;AAAA,EACf,GAAA,EAAK,KAAK,EAAA,GAAK;AAAA;AACjB,CAAA;AAGO,IAAM,mBAAA,GAAsB,KAAK,EAAA,GAAK,GAAA;;;AC9DtC,SAAS,oBAAoB,IAAA,EAMf;AACnB,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,UAAA,CAAW,MAAA,CAAO,UAAA,EAAW;AAAA,IACjC,OAAO,IAAA,CAAK,KAAA,IAAS,gBAAgB,IAAA,CAAK,MAAA,EAAQ,KAAK,WAAW,CAAA;AAAA,IAClE,UAAU,IAAA,CAAK,QAAA;AAAA,IACf,UAAU,IAAA,CAAK,QAAA;AAAA,IACf,QAAQ,IAAA,CAAK,MAAA;AAAA,IACb,aAAa,IAAA,CAAK,WAAA;AAAA,IAClB,UAAA,EAAY,IAAA;AAAA,IACZ,YAAA,EAAc,MAAA;AAAA,IACd,aAAA,EAAe,MAAA;AAAA,IACf,gBAAA,EAAk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AAgB,MAAA;AACtB,QAAA,KAAA,CAAM,gBAAA,GAAmB,MAAA;AACzB,QAAA,GAAA,CAAI,KAAK,KAAK,CAAA;AAAA,MAChB;AAAA,IACF;AACA,IAAA,OAAO,GAAA;AAAA,EACT;AACF;AAMA,SAAS,cAAc,OAAA,EAAiD;AACtE,EAAA,MAAM,IAAA,uBAAW,GAAA,EAAY;AAC7B,EAAA,MAAM,MAA0B,EAAC;AACjC,EAAA,KAAA,MAAW,KAAK,OAAA,EAAS;AACvB,IAAA,IAAI,IAAA,CAAK,GAAA,CAAI,CAAA,CAAE,WAAW,CAAA,EAAG;AAC7B,IAAA,IAAA,CAAK,GAAA,CAAI,EAAE,WAAW,CAAA;AACtB,IAAA,GAAA,CAAI,KAAK,CAAC,CAAA;AAAA,EACZ;AACA,EAAA,OAAO,GAAA;AACT;ACrWA,IAAM,mBAAA,GAAsB,IAAIC,6BAAA,EAA+C;AAS/E,eAAsB,kBAAA,CACpB,OACA,EAAA,EACY;AACZ,EAAA,OAAO,mBAAA,CAAoB,GAAA,CAAI,KAAA,EAAO,EAAE,CAAA;AAC1C;AAQO,SAAS,sBAAsB,QAAA,EAA8C;AAClF,EAAA,OAAO,mBAAA,CAAoB,QAAA,EAAS,EAAG,GAAA,CAAI,QAAQ,CAAA;AACrD","file":"chunk-55LLQFHW.cjs","sourcesContent":["/**\n * Types for the credential pool subsystem (ADRs D123-D133).\n *\n * Pool a developer's multiple API keys for the SAME provider so the SDK\n * can rotate transparently on HTTP 429/402/401 instead of jumping\n * straight to a different provider via `FallbackLlmClient`.\n *\n * @internal\n */\n\n/**\n * Rotation strategy when picking the next credential from a pool.\n *\n * - `fill_first` (default): use entries[0] until exhausted, then [1]…\n * - `round_robin`: rotate after each `select()`\n * - `least_used`: pick the entry with the lowest `requestCount`\n * - `random`: random pick among healthy entries\n *\n * Closed enum per ADR D124 — adding a strategy is an explicit semver\n * minor that updates `selectByStrategy` exhaustively.\n *\n * @internal\n */\nexport type CredentialPoolStrategy = \"fill_first\" | \"round_robin\" | \"least_used\" | \"random\";\n\n/** Health flag tracked per credential. */\nexport type CredentialStatus = \"ok\" | \"exhausted\";\n\n/**\n * Provenance of a credential — where it came from when seeded.\n * Free-form string; conventional prefixes:\n *\n * - `env:<VAR_NAME>` — auto-discovered from environment variable\n * - `manual` — added via explicit `apiKeys` config\n * - `explicit-apikey` — wrapped from `AgentOptions.apiKey` single-key path (D132)\n */\nexport type CredentialSource = string;\n\n/**\n * Single credential entry inside a {@link CredentialPool}.\n *\n * `accessToken` is the sensitive field — must never be logged unredacted.\n * The lint gate `tests/lint/no-unredacted-pool-token.test.ts` enforces this.\n *\n * @internal\n */\nexport interface PooledCredential {\n /** Stable identifier (uuid v4) for log lines + telemetry. */\n id: string;\n /** Human-readable label for `Theokit.credentialPool.list()`. */\n label: string;\n /** Provider name (matches `ProviderProfile.name`). */\n provider: string;\n /** Sort key; lower = earlier in fill_first. Unique within a pool. */\n priority: number;\n /** Provenance string. */\n source: CredentialSource;\n /** Sensitive API key. NEVER LOG UNREDACTED. */\n accessToken: string;\n /** Current health. */\n lastStatus: CredentialStatus;\n /** Epoch ms of the last status change. */\n lastStatusAt: number | undefined;\n /** HTTP code that caused exhaustion (401/402/429). */\n lastErrorCode: number | undefined;\n /** Provider-supplied \"retry after this epoch ms\" hint. Overrides cooldown defaults. */\n lastErrorResetAt: number | undefined;\n /** Bumped per successful `select()` for `least_used` strategy. Lazy-persisted. */\n requestCount: number;\n}\n\n/**\n * Serializable snapshot of a single provider's pool. Used by the\n * persistence layer (T2.1) to read/write `~/.theokit/credential-pool.json`.\n *\n * @internal\n */\nexport interface CredentialPoolSnapshot {\n provider: string;\n strategy: CredentialPoolStrategy;\n entries: PooledCredential[];\n}\n\n/**\n * Cooldown ladder by HTTP error code (ADR D125). Provider-supplied\n * `lastErrorResetAt` overrides these defaults when present.\n *\n * @internal\n */\nexport const COOLDOWN_MS: Readonly<Record<number, number>> = {\n 401: 5 * 60 * 1000, // 5 minutes — OAuth refresh can recover quickly\n 402: 60 * 60 * 1000, // 1 hour — billing quota typically hourly+\n 429: 60 * 60 * 1000, // 1 hour — daily-rate-limit windows\n};\n\n/** Default cooldown when no specific code matches. */\nexport const DEFAULT_COOLDOWN_MS = 60 * 60 * 1000;\n","/**\n * In-memory credential pool with strategy-based rotation (ADRs D123-D133).\n *\n * Pure logic. No I/O — persistence lives in `internal/persistence/\n * credential-pool-store.ts`. The pool is the single source of truth for\n * rotation state within a process; if it diverges from disk (e.g.,\n * process killed mid-rotation per EC-I), the next save heals the\n * inconsistency — at the cost of one extra HTTP 429 per crash.\n *\n * Thread safety: the pool uses an in-process async-aware mutex\n * (`cwd-mutex` D9 keyed by `credential-pool:${provider}`). Cross-process\n * safety happens at the persistence layer via `withFileLock` (D61).\n * Two Node processes sharing the same file may double-pick momentarily\n * (worst case = 1 extra 429 per race) — acceptable per ADR D128.\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { withCwdMutex } from \"../persistence/cwd-mutex.js\";\nimport {\n COOLDOWN_MS,\n type CredentialPoolSnapshot,\n type CredentialPoolStrategy,\n DEFAULT_COOLDOWN_MS,\n type PooledCredential,\n} from \"./credential-pool-types.js\";\nimport { sleepWithAbort } from \"./retry.js\";\n\n/**\n * Construct a `PooledCredential` with sane defaults.\n *\n * @internal\n */\nexport function newPooledCredential(args: {\n provider: string;\n accessToken: string;\n priority: number;\n source: string;\n label?: string;\n}): PooledCredential {\n return {\n id: globalThis.crypto.randomUUID(),\n label: args.label ?? labelFromSource(args.source, args.accessToken),\n provider: args.provider,\n priority: args.priority,\n source: args.source,\n accessToken: args.accessToken,\n lastStatus: \"ok\",\n lastStatusAt: undefined,\n lastErrorCode: undefined,\n lastErrorResetAt: undefined,\n requestCount: 0,\n };\n}\n\n/**\n * Build a human-readable label from the credential source. Used for\n * `Theokit.credentialPool.list()` UX. NEVER includes the raw token.\n *\n * @internal\n */\nfunction labelFromSource(source: string, accessToken: string): string {\n if (source.startsWith(\"env:\")) return source.slice(4);\n const masked =\n accessToken.length > 8 ? `${accessToken.slice(0, 4)}…${accessToken.slice(-4)}` : \"***\";\n return `${source}:${masked}`;\n}\n\n/**\n * Per-provider credential pool. Construct with one or more entries\n * sorted by priority. Throws `ConfigurationError` on empty input.\n *\n * EC-C: identical `accessToken`s are deduplicated during construction\n * (3 copies of \"k1\" → 1 entry). Otherwise an exhaustion event would\n * mark \"k1\" exhausted 3× wastefully.\n *\n * @internal\n */\nexport class CredentialPool {\n readonly provider: string;\n private readonly strategy: CredentialPoolStrategy;\n private entries: PooledCredential[];\n\n constructor(\n provider: string,\n entries: PooledCredential[],\n strategy: CredentialPoolStrategy = \"fill_first\",\n ) {\n if (entries.length === 0) {\n throw new ConfigurationError(\n `credential-pool: cannot construct empty pool for provider \"${provider}\"`,\n { code: \"credential_pool_empty\" },\n );\n }\n this.provider = provider;\n this.strategy = strategy;\n // EC-C: dedupe by accessToken before sort.\n this.entries = dedupeByToken(entries).sort((a, b) => a.priority - b.priority);\n }\n\n /** True if the pool was seeded with at least one entry. */\n hasCredentials(): boolean {\n return this.entries.length > 0;\n }\n\n /** True iff at least one entry is healthy (auto-healed if cooldown expired). */\n hasAvailable(): boolean {\n return this.availableEntries().length > 0;\n }\n\n /**\n * Earliest `lastErrorResetAt` across all entries, or `undefined` if no\n * entry is in cooldown. Used by `waitForAvailable` to compute the\n * upper bound of each jittered sleep window.\n *\n * @internal\n */\n earliestResetAt(): number | undefined {\n let earliest: number | undefined;\n for (const entry of this.entries) {\n if (entry.lastStatus === \"ok\") continue;\n if (entry.lastErrorResetAt === undefined) continue;\n if (earliest === undefined || entry.lastErrorResetAt < earliest) {\n earliest = entry.lastErrorResetAt;\n }\n }\n return earliest;\n }\n\n /**\n * Wait until at least one entry becomes healthy OR `maxWaitMs` elapses\n * OR `signal` aborts. Returns `true` if a healthy entry is available\n * when the call returns, `false` otherwise.\n *\n * T3.9 — Reconnect storm prevention. Concurrent callers each sleep a\n * random fraction of the window to the earliest cooldown reset (full\n * jitter — AWS Brooker 2015) so they do not all wake at the exact\n * instant cooldown expires and hammer the upstream simultaneously.\n *\n * The `sleeper` parameter is a dependency-injection seam for tests:\n * callers in production omit it and the default `setTimeout`-based\n * sleeper is used. The seam avoids the `vi.useFakeTimers()` mismatch\n * that blocked T3.4's wiring.\n *\n * @internal\n */\n async waitForAvailable(\n signal: AbortSignal,\n opts: {\n maxWaitMs: number;\n sleeper?: (ms: number, signal: AbortSignal) => Promise<void>;\n /**\n * Clock seam, the companion to `sleeper`. Production omits it and gets `Date.now`.\n *\n * `sleeper` alone was not enough to make this loop testable: a test could replace the SLEEP\n * but the deadline check still read real wall-clock, so the one case that exercises timeout\n * had to set `maxWaitMs: 5` and race the scheduler — with a comment in the committed file\n * saying so (\"we can't easily ... spec is wall-clock based\"). A sleeper that also advances a\n * virtual clock closes the loop deterministically, which is what `rules/testing.md` § 6 asks\n * for when it says to inject the clock rather than sleep.\n */\n now?: () => number;\n },\n ): Promise<boolean> {\n if (signal.aborted) return false;\n if (this.hasAvailable()) return true;\n const now = opts.now ?? Date.now;\n return await this.pollUntilAvailable(\n signal,\n now() + opts.maxWaitMs,\n opts.sleeper ?? sleepWithAbort,\n now,\n );\n }\n\n /**\n * The polling half of `waitForAvailable`, with both seams already resolved.\n *\n * Its own method because resolving two optional seams and running the loop in one body put the\n * function over the cognitive-complexity gate. The split is also the honest one: everything above\n * is a guard, everything here is the wait.\n */\n private async pollUntilAvailable(\n signal: AbortSignal,\n deadline: number,\n sleeper: (ms: number, signal: AbortSignal) => Promise<void>,\n now: () => number,\n ): Promise<boolean> {\n while (now() < deadline) {\n if (signal.aborted) return false;\n await sleeper(this.computeJitteredSleepMs(deadline, now), signal);\n if (signal.aborted) return false;\n if (this.hasAvailable()) return true;\n }\n return this.hasAvailable();\n }\n\n /**\n * Compute the next jittered sleep window (ms) for `waitForAvailable`.\n * Full-jitter cap: at most (a) time until the earliest reset (plus a\n * 50 ms grace so the entry actually heals before re-probe), or (b) the\n * remaining wait window, whichever is smaller. When no entry has a\n * known reset (rare — only if `markExhaustedAndRotate` was called\n * without `resetAtMs`), fall back to a 250 ms ceiling so we stay\n * responsive without hot-looping.\n */\n private computeJitteredSleepMs(deadline: number, now: () => number = Date.now): number {\n const resetAt = this.earliestResetAt();\n const remaining = deadline - now();\n const ceiling =\n resetAt === undefined\n ? Math.min(remaining, 250)\n : Math.min(remaining, Math.max(0, resetAt - now()) + 50);\n return Math.max(0, Math.floor(Math.random() * ceiling));\n }\n\n /** Live (frozen) view of all entries. */\n list(): readonly PooledCredential[] {\n return this.entries;\n }\n\n /**\n * Pick a healthy entry according to the configured strategy.\n * Mutates `requestCount` and (for round_robin) entry order.\n * Returns null if every entry is in cooldown.\n *\n * @internal\n */\n async select(): Promise<PooledCredential | null> {\n return withCwdMutex(`credential-pool:${this.provider}`, async () => this.selectLocked());\n }\n\n /**\n * Mark the entry whose id matches `entryId` as exhausted with the\n * appropriate cooldown, then return the next healthy entry (or null).\n * If `entryId` is undefined, marks all currently-active entries (rare —\n * only used by admin reset scenarios).\n *\n * @internal\n */\n async markExhaustedAndRotate(args: {\n entryId: string;\n statusCode: number;\n resetAtMs?: number;\n }): Promise<PooledCredential | null> {\n return withCwdMutex(`credential-pool:${this.provider}`, async () => {\n const entry = this.entries.find((e) => e.id === args.entryId);\n if (entry !== undefined) {\n const now = Date.now();\n const cooldown = COOLDOWN_MS[args.statusCode] ?? DEFAULT_COOLDOWN_MS;\n entry.lastStatus = \"exhausted\";\n entry.lastStatusAt = now;\n entry.lastErrorCode = args.statusCode;\n // EC-5: negative or stale resetAt → ignore, fall through to default.\n entry.lastErrorResetAt =\n args.resetAtMs !== undefined && args.resetAtMs > now ? args.resetAtMs : now + cooldown;\n }\n return this.selectLocked();\n });\n }\n\n /** Admin escape hatch: clear all cooldowns. */\n async resetAll(): Promise<void> {\n await withCwdMutex(`credential-pool:${this.provider}`, async () => {\n for (const e of this.entries) {\n e.lastStatus = \"ok\";\n e.lastStatusAt = undefined;\n e.lastErrorCode = undefined;\n e.lastErrorResetAt = undefined;\n }\n });\n }\n\n /** Materialize for persistence. */\n toSnapshot(): CredentialPoolSnapshot {\n return {\n provider: this.provider,\n strategy: this.strategy,\n entries: this.entries.map((e) => ({ ...e })),\n };\n }\n\n /** Hydrate from a previously-saved snapshot. */\n static fromSnapshot(snapshot: CredentialPoolSnapshot): CredentialPool {\n return new CredentialPool(snapshot.provider, snapshot.entries, snapshot.strategy);\n }\n\n // ─── Internal helpers (always called inside the mutex) ───\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: strategy dispatch must branch on 4 enum values (random/least_used/round_robin/fill_first) with 1-entry short-circuits per strategy. Each branch is 5-10 lines of focused logic; extracting per-strategy methods fragments the linear narrative.\n private selectLocked(): PooledCredential | null {\n const available = this.availableEntries();\n if (available.length === 0) return null;\n\n if (this.strategy === \"random\") {\n const idx = Math.floor(Math.random() * available.length);\n const picked = available[idx];\n if (picked === undefined) return null; // unreachable; satisfies strict\n picked.requestCount += 1;\n return picked;\n }\n\n if (this.strategy === \"least_used\" && available.length > 1) {\n // EC-3: tie-break by priority ascending (first wins).\n const picked = [...available].sort(\n (a, b) => a.requestCount - b.requestCount || a.priority - b.priority,\n )[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n return picked;\n }\n\n if (this.strategy === \"round_robin\" && available.length > 1) {\n // Pick head; move it to the end of `entries` so next call picks the next.\n const picked = available[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n const rest = this.entries.filter((e) => e.id !== picked.id);\n // Re-assign priorities: rotated entry gets the highest priority value\n // so it sorts last after `fromSnapshot` rehydration. This makes EC-F\n // (round-robin state survives save/load) work without a separate field.\n const maxPriority = this.entries.length - 1;\n rest.forEach((e, i) => {\n e.priority = i;\n });\n picked.priority = maxPriority;\n this.entries = [...rest, picked];\n return picked;\n }\n\n // fill_first (default) and 1-entry edge case for round_robin/least_used\n const picked = available[0];\n if (picked === undefined) return null;\n picked.requestCount += 1;\n return picked;\n }\n\n private availableEntries(): PooledCredential[] {\n const now = Date.now();\n const out: PooledCredential[] = [];\n for (const entry of this.entries) {\n if (entry.lastStatus === \"ok\") {\n out.push(entry);\n continue;\n }\n // EC-1: auto-heal expired cooldowns inline.\n const resetAt = entry.lastErrorResetAt;\n if (resetAt !== undefined && now >= resetAt) {\n entry.lastStatus = \"ok\";\n entry.lastStatusAt = undefined;\n entry.lastErrorCode = undefined;\n entry.lastErrorResetAt = undefined;\n out.push(entry);\n }\n }\n return out;\n }\n}\n\n/**\n * Drop duplicates by `accessToken`. Keeps the first occurrence (lowest\n * priority wins after sort). EC-C from the edge-case review.\n */\nfunction dedupeByToken(entries: PooledCredential[]): PooledCredential[] {\n const seen = new Set<string>();\n const out: PooledCredential[] = [];\n for (const e of entries) {\n if (seen.has(e.accessToken)) continue;\n seen.add(e.accessToken);\n out.push(e);\n }\n return out;\n}\n","/**\n * Per-fork credential-pool inheritance via `AsyncLocalStorage` (ADR D131).\n *\n * Mirrors the whitelist context pattern from D111\n * (`runtime/async-local-storage.ts`). Forked sub-agents inherit the\n * parent's pool *by reference* so concurrent rotations all observe\n * the same cooldown state — the desired behavior per Hermes parity.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport type { CredentialPool } from \"./credential-pool.js\";\n\n/** ALS slot — keyed by provider name → pool. */\nconst credentialPoolStore = new AsyncLocalStorage<Map<string, CredentialPool>>();\n\n/**\n * Run `fn` with `pools` as the active credential-pool registry for the\n * current async context. Nested calls shadow the outer map (parent\n * pools are not visible to children when the child sets its own).\n *\n * @internal\n */\nexport async function withCredentialPool<T>(\n pools: Map<string, CredentialPool>,\n fn: () => Promise<T>,\n): Promise<T> {\n return credentialPoolStore.run(pools, fn);\n}\n\n/**\n * Pool registered for `provider` in the current async context, or\n * `undefined` when no `withCredentialPool(...)` scope is active.\n *\n * @internal\n */\nexport function currentCredentialPool(provider: string): CredentialPool | undefined {\n return credentialPoolStore.getStore()?.get(provider);\n}\n"]}
@@ -62,7 +62,7 @@ var PROVIDER_DETAIL_MAX_CHARS = 512;
62
62
  function mapOpenAICompatibleError(args) {
63
63
  const { providerId, status, body, headers, endpoint } = args;
64
64
  const code = mapOpenAiStatusToCode(status, body);
65
- const message = formatMessage(providerId, status, code);
65
+ const message = formatMessage(providerId, status, code, boundedProviderDetail(body));
66
66
  const metadata = buildErrorMetadata({
67
67
  provider: providerId,
68
68
  endpoint,
@@ -78,15 +78,13 @@ function mapOpenAICompatibleError(args) {
78
78
  return new RateLimitError(message, { code: `${providerId}_rate_limit`, metadata });
79
79
  }
80
80
  if (status === 404 && code === "model_unavailable") {
81
- const detailed = formatMessage(providerId, status, code, boundedProviderDetail(body));
82
- return new ConfigurationError(detailed, {
81
+ return new ConfigurationError(message, {
83
82
  code: `${providerId}_model_unavailable`,
84
83
  metadata
85
84
  });
86
85
  }
87
86
  if (status === 400) {
88
- const detailed = formatMessage(providerId, status, code, boundedProviderDetail(body));
89
- return new ConfigurationError(detailed, { code: `${providerId}_${code}`, metadata });
87
+ return new ConfigurationError(message, { code: `${providerId}_${code}`, metadata });
90
88
  }
91
89
  if (status === 408) {
92
90
  return new NetworkError(message, { code: `${providerId}_timeout`, metadata });
@@ -154,5 +152,5 @@ function formatMessage(providerId, status, code, detail) {
154
152
  }
155
153
 
156
154
  export { buildErrorMetadata, httpStatusToErrorCode, mapOpenAICompatibleError, parseErrorBody, parseRetryAfter };
157
- //# sourceMappingURL=chunk-ZJAYFSVI.js.map
158
- //# sourceMappingURL=chunk-ZJAYFSVI.js.map
155
+ //# sourceMappingURL=chunk-7ACS6P5Z.js.map
156
+ //# sourceMappingURL=chunk-7ACS6P5Z.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/error-mappers/shared.ts","../src/internal/error-mappers/openai-compatible.ts"],"names":[],"mappings":";;;;AAeA,IAAM,aAAA,GAAgB,IAAA;AAUf,SAAS,gBAAgB,OAAA,EAAkD;AAChF,EAAA,IAAI,OAAA,KAAY,QAA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AAA,IACnE,IAAA,EAAM;AAAA,GACR;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA,EAAE,SAAA,EAAW,CAAC,sBAAsB,gBAAgB,CAAA,EAAG,MAAM,gBAAA;AAC/D,CAAA;AAEA,SAAS,uBAAuB,OAAA,EAAwC;AACtE,EAAA,MAAM,OAAO,eAAA,CAAgB,IAAA;AAAA,IAAK,CAAC,EAAE,SAAA,EAAU,KAC7C,SAAA,CAAU,IAAA,CAAK,CAAC,QAAA,KAAa,OAAA,CAAQ,QAAA,CAAS,QAAQ,CAAC;AAAA,GACzD;AACA,EAAA,OAAO,IAAA,EAAM,IAAA;AACf;AAEA,SAAS,aAAA,CACP,UAAA,EACA,MAAA,EACA,IAAA,EACA,MAAA,EACQ;AACR,EAAA,MAAM,OAAO,CAAA,EAAG,UAAU,CAAA,YAAA,EAAe,IAAI,UAAU,MAAM,CAAA,CAAA,CAAA;AAC7D,EAAA,OAAO,MAAA,KAAW,UAAa,MAAA,KAAW,EAAA,GAAK,OAAO,CAAA,EAAG,IAAI,KAAK,MAAM,CAAA,CAAA;AAC1E","file":"chunk-7ACS6P5Z.js","sourcesContent":["/**\nimport type { ErrorCode } from \"../../errors.js\";\n * Helpers shared between provider HTTP error mappers (ADR D67).\n *\n * Extracted to dedupe identical logic in `anthropic.ts` and\n * `openai-compatible.ts` — retry-after parsing, raw-body truncation,\n * and metadata assembly are dialect-agnostic.\n *\n * @internal\n */\n\nimport type { ErrorCode, ErrorMetadata } from \"../../errors.js\";\nimport { redactSecrets } from \"../security/index.js\";\n\n/** Longest `ErrorMetadata.raw`, in UTF-16 code units, before the `…` suffix. */\nconst RAW_MAX_CHARS = 2048;\n\n/**\n * Parse the `Retry-After` header (RFC 7231) into seconds. Both forms are\n * supported: numeric-seconds (`Retry-After: 30`) and HTTP-date\n * (`Retry-After: Wed, 21 Oct 2025 07:28:00 GMT` → seconds until that instant,\n * clamped at 0 for a past date). Garbage / missing header → `undefined`.\n *\n * @internal\n */\nexport function parseRetryAfter(headers: Headers | undefined): number | undefined {\n if (headers === undefined) return undefined;\n const raw = headers.get(\"retry-after\");\n if (raw === null) return undefined;\n const n = Number(raw);\n if (Number.isFinite(n) && n >= 0) return Math.ceil(n);\n // HTTP-date form — seconds until the given instant (0 if already elapsed).\n const dateMs = Date.parse(raw);\n if (Number.isFinite(dateMs)) return Math.max(0, Math.ceil((dateMs - Date.now()) / 1000));\n return undefined;\n}\n\n/**\n * Redact known credential patterns in the raw response body, then\n * cut the redacted text to 2048 characters (UTF-16 code units), so it can ride inside\n * `ErrorMetadata.raw` without ballooning logs OR leaking tokens.\n * Returns `undefined` for null/undefined input.\n *\n * Redaction runs first: a pattern can only mask a credential it sees\n * whole, and cutting first left a key straddling the cut too short for\n * its pattern, so its leading fragment reached `raw` in clear (B-540).\n * The `…` suffix is added exactly when text was dropped.\n *\n * Redaction sees the whole body, however long. Any bound on what it reads\n * brings the edge back: a credential cut by the bound matches nothing, and\n * redaction of the text before it can pull the clear fragment inside the\n * cut, and no fixed margin is enough because JWTs and PEM blocks have no\n * length bound (plan D1, review round 2). The builtin patterns were timed\n * on hostile input and the two that were not linear were fixed (B-544,\n * B-554), so the cost grows with the body's length; a pattern\n * registered with `Security.addPattern` sees the whole body too and\n * should stay linear in its input. The cut never splits a surrogate pair.\n *\n * Post T1.1 (secret-redaction-discipline, ADR D68): every error metadata\n * goes through `redactSecrets` before exposure. Note the shape change —\n * pre-T1.1 the function preserved the original `body` shape when ≤2KB;\n * now it always returns a (possibly redacted) string, because redaction\n * coerces non-strings to JSON. Consumers who used to do `err.metadata.raw.foo`\n * must now `JSON.parse(err.metadata.raw)` first — but a workspace-wide\n * grep at T1.1 land time confirmed zero such callers.\n *\n * @internal\n */\nexport function truncateRaw(body: unknown): unknown {\n if (body === null || body === undefined) return undefined;\n const s = typeof body === \"string\" ? body : JSON.stringify(body);\n const redacted = redactSecrets(s);\n return redacted.length <= RAW_MAX_CHARS ? redacted : `${cutAt(redacted, RAW_MAX_CHARS)}…`;\n}\n\n/** The first `end` code units of `text`, one fewer when that would split a surrogate pair. */\nfunction cutAt(text: string, end: number): string {\n if (end >= text.length) return text;\n const last = text.charCodeAt(end - 1);\n return text.slice(0, last >= 0xd800 && last <= 0xdbff ? end - 1 : end);\n}\n\n/**\n * Build an `ErrorMetadata` object with all optional fields included\n * conditionally (no `undefined` keys in the output). Caller passes\n * dialect-specific fields (`provider`, `endpoint`, `code`); shared\n * fields (`statusCode`, `retryAfter`, `raw`) are derived here.\n *\n * @internal\n */\nexport function buildErrorMetadata(args: {\n provider: string;\n endpoint: string;\n code: ErrorCode;\n status: number;\n headers: Headers | undefined;\n body: unknown;\n}): ErrorMetadata {\n const retryAfter = parseRetryAfter(args.headers);\n const raw = truncateRaw(args.body);\n return {\n provider: args.provider,\n endpoint: args.endpoint,\n code: args.code,\n statusCode: args.status,\n ...(retryAfter !== undefined ? { retryAfter } : {}),\n ...(raw !== undefined ? { raw } : {}),\n };\n}\n\n/**\n * D314: extract the provider's request id (`x-request-id` is OpenAI/most;\n * `request-id` is Anthropic). Returns `undefined` when neither is present.\n *\n * @internal\n */\nexport function parseRequestId(headers: Headers | undefined): string | undefined {\n if (headers === undefined) return undefined;\n return headers.get(\"x-request-id\") ?? headers.get(\"request-id\") ?? undefined;\n}\n\n/**\n * The HTTP status ladder — ONE definition, shared by every provider mapper.\n *\n * This is RFC 9110 semantics, not a vendor contract: a 429 means the same thing\n * whether Anthropic, OpenAI, Bedrock or Vertex sent it. It lived in four copies\n * until 2026-09-01 and the copies had already drifted in two measurable ways,\n * which is what moved it here beside the other dialect-agnostic helpers ADR D67\n * extracted:\n *\n * 1. **402 reached one mapper of four.** T3.7 added `quota_exceeded` and wired\n * it into `openai-compatible.ts` only. A Bedrock, Vertex or Anthropic\n * endpoint answering 402 fell through every arm and came back `unknown` —\n * the canonical bucket existed and three of four mappers could not reach it.\n * 2. **The 5xx arm had two different upper bounds.** `anthropic` and\n * `openai-compatible` guarded `>= 500 && < 600`; `bedrock` and `vertex`\n * guarded `>= 500` with no ceiling, so a malformed or proxy-injected 6xx was\n * `server_error` in two mappers and `unknown` in the other two.\n *\n * Neither was a vendor difference. Both were copy-drift, and that is the DRY\n * test in its textbook form: one piece of knowledge, four places to change it.\n *\n * The ladder is deliberately the FALLBACK, never the whole classifier. Each\n * mapper keeps its own body-dialect rules — Anthropic's `context_too_long`,\n * Bedrock's AWS `__type` strings, Vertex's `google.rpc` status enum — because\n * those ARE per-vendor contracts. The shape is\n * `classifyVendorBody(body) ?? httpStatusToErrorCode(status)`.\n *\n * 404 is deliberately NOT mapped here. Three mappers treat it as `unknown` and\n * Bedrock treats it as `invalid_request` via its own `__type` rules; folding it\n * in would silently change three mappers to close a divergence nobody measured.\n *\n * @internal\n */\nexport type HttpStatusErrorCode = Extract<\n ErrorCode,\n | \"auth_failed\"\n | \"quota_exceeded\"\n | \"timeout\"\n | \"rate_limit\"\n | \"invalid_request\"\n | \"server_error\"\n | \"unknown\"\n>;\n\nexport function httpStatusToErrorCode(status: number): HttpStatusErrorCode {\n if (status === 401 || status === 403) return \"auth_failed\";\n if (status === 402) return \"quota_exceeded\";\n if (status === 408) return \"timeout\";\n if (status === 429) return \"rate_limit\";\n if (status === 400) return \"invalid_request\";\n if (status >= 500 && status < 600) return \"server_error\";\n return \"unknown\";\n}\n\n/**\n * Reads an error body that may arrive already parsed, as a JSON string, or as neither.\n *\n * This is TRANSPORT knowledge, not vendor knowledge: it describes how `fetch` surfaces a body, which\n * is the same whichever provider sent it. It lived twice, character-for-character, in bedrock.ts and\n * vertex.ts — identical once the return type name was substituted. They had not drifted, so the cost\n * was only latent: a fix to one would have missed the other silently.\n *\n * Unparseable input yields `{}` rather than throwing, because a mapper's job is to classify a\n * failure that already happened; failing to read the body is not a second failure to report.\n */\nexport function parseErrorBody<T>(body: unknown): T {\n if (body !== null && typeof body === \"object\") return body as T;\n if (typeof body === \"string\") {\n try {\n return JSON.parse(body) as T;\n } catch {\n return {} as T;\n }\n }\n return {} as T;\n}\n","/**\n * OpenAI-compatible HTTP error mapper (ADR D67).\n *\n * Translates OpenAI-shaped API error responses (covers OpenAI, OpenRouter,\n * DeepSeek, Together, Mistral, Voyage, DeepInfra, etc.) into typed\n * `TheokitAgentError` subclasses with full `ErrorMetadata`.\n *\n * Body inspection: looks at `body.error.code` / `body.error.type` to detect\n * `context_too_long`, `content_filtered`, `model_unavailable` semantics, and at\n * `body.error.message` for a 404 that says no endpoint serves the model\n * (OpenRouter's numeric-code body for a retired model id). Every message\n * ends with the provider's text, redacted and capped at 512 characters.\n * Falls back to status-based mapping when body doesn't expose `.error`\n * (e.g., HTML server error page, DeepInfra's `{message: \"...\"}` shape).\n *\n * Never throws — caller is already in an error path.\n *\n * @internal\n */\n\nimport {\n AuthenticationError,\n ConfigurationError,\n type ErrorCode,\n NetworkError,\n RateLimitError,\n type TheokitAgentError,\n UnknownAgentError,\n} from \"../../errors.js\";\nimport { redactSecrets } from \"../security/index.js\";\nimport { buildErrorMetadata, httpStatusToErrorCode } from \"./shared.js\";\n\n// A provider's text joins a message consumers log and show, so it is bounded first. 512 keeps every\n// measured text whole (OpenRouter's 400s run 40 to 60 characters, OpenAI's context-length text\n// about 250); `metadata.raw` keeps up to 2048 bytes of the body for the rest.\nconst PROVIDER_DETAIL_MAX_CHARS = 512;\n\ninterface MapOpenAiErrorArgs {\n providerId: string;\n status: number;\n body: unknown;\n headers: Headers | undefined;\n endpoint: string;\n}\n\nexport function mapOpenAICompatibleError(args: MapOpenAiErrorArgs): TheokitAgentError {\n const { providerId, status, body, headers, endpoint } = args;\n const code = mapOpenAiStatusToCode(status, body);\n // Every status carries the provider's text: it is the only place that says what went wrong.\n const message = formatMessage(providerId, status, code, boundedProviderDetail(body));\n const metadata = buildErrorMetadata({\n provider: providerId,\n endpoint,\n code,\n status,\n headers,\n body,\n });\n\n if (status === 401 || status === 403) {\n return new AuthenticationError(message, { code: `${providerId}_auth_failed`, metadata });\n }\n if (status === 429) {\n return new RateLimitError(message, { code: `${providerId}_rate_limit`, metadata });\n }\n if (status === 404 && code === \"model_unavailable\") {\n return new ConfigurationError(message, {\n code: `${providerId}_model_unavailable`,\n metadata,\n });\n }\n if (status === 400) {\n return new ConfigurationError(message, { code: `${providerId}_${code}`, metadata });\n }\n if (status === 408) {\n return new NetworkError(message, { code: `${providerId}_timeout`, metadata });\n }\n if (status >= 500 && status < 600) {\n return new NetworkError(message, { code: `${providerId}_server_error`, metadata });\n }\n return new UnknownAgentError(message, { code: `${providerId}_unknown`, metadata });\n}\n\nfunction extractOpenAiErrorCode(body: unknown): string | undefined {\n if (body === null || typeof body !== \"object\") return undefined;\n const err = (body as { error?: { code?: unknown; type?: unknown } }).error;\n if (err === undefined || err === null) return undefined;\n if (typeof err.code === \"string\") return err.code;\n if (typeof err.type === \"string\") return err.type;\n return undefined;\n}\n\nfunction extractOpenAiErrorMessage(body: unknown): string | undefined {\n if (body === null || typeof body !== \"object\") return undefined;\n const err = (body as { error?: { message?: unknown } }).error;\n if (err === undefined || err === null) return undefined;\n return typeof err.message === \"string\" ? err.message : undefined;\n}\n\n// Redaction runs before the cut: a key cut first could keep too few characters to match a\n// credential pattern, and its prefix would reach the message unmasked.\nfunction boundedProviderDetail(body: unknown): string | undefined {\n const raw = extractOpenAiErrorMessage(body);\n if (raw === undefined || raw.trim() === \"\") return undefined;\n const redacted = redactSecrets(raw);\n return redacted.length <= PROVIDER_DETAIL_MAX_CHARS\n ? redacted\n : `${redacted.slice(0, PROVIDER_DETAIL_MAX_CHARS)}…`;\n}\n\n// OpenRouter answers a model it does not serve with HTTP 404 and a numeric `error.code`,\n// so only the message tells it apart from a 404 for a wrong path (measured 2026-10-20).\nconst MISSING_MODEL_MESSAGE = /no endpoints found/i;\n\nfunction mapOpenAiStatusToCode(status: number, body: unknown): ErrorCode {\n const fromBodyCode = classifyOpenAiBodyCode(extractOpenAiErrorCode(body)?.toLowerCase() ?? \"\");\n if (fromBodyCode !== undefined) return fromBodyCode;\n if (isMissingModel404(status, body)) return \"model_unavailable\";\n\n // Everything below the body dialect is RFC 9110 and lives once, in shared.ts.\n return httpStatusToErrorCode(status);\n}\n\nfunction isMissingModel404(status: number, body: unknown): boolean {\n return status === 404 && MISSING_MODEL_MESSAGE.test(extractOpenAiErrorMessage(body) ?? \"\");\n}\n\n// The body dialect, in precedence order: the first rule whose fragment appears in the\n// lowercased body code wins.\nconst BODY_CODE_RULES: ReadonlyArray<{ fragments: readonly string[]; code: ErrorCode }> = [\n {\n fragments: [\"context_length\", \"context_window\", \"too_many_tokens\", \"max_tokens\"],\n code: \"context_too_long\",\n },\n { fragments: [\"content_filter\", \"content_policy\", \"safety\"], code: \"content_filtered\" },\n {\n fragments: [\"model_not_found\", \"model_unavailable\", \"invalid_model\"],\n code: \"model_unavailable\",\n },\n // T3.7 — OpenRouter \"Insufficient credits\" / `insufficient_quota` in the BODY.\n // The status-402 half of this rule moved to the shared ladder, where it now\n // reaches all four mappers instead of this one; what stays here is the part\n // that is genuinely a body dialect.\n { fragments: [\"insufficient_quota\", \"quota_exceeded\"], code: \"quota_exceeded\" },\n];\n\nfunction classifyOpenAiBodyCode(rawCode: string): ErrorCode | undefined {\n const rule = BODY_CODE_RULES.find(({ fragments }) =>\n fragments.some((fragment) => rawCode.includes(fragment)),\n );\n return rule?.code;\n}\n\nfunction formatMessage(\n providerId: string,\n status: number,\n code: ErrorCode,\n detail?: string,\n): string {\n const base = `${providerId} API error: ${code} (HTTP ${status})`;\n return detail === undefined || detail === \"\" ? base : `${base}: ${detail}`;\n}\n"]}
@@ -154,7 +154,8 @@ function rejectMcp(fields, filename) {
154
154
  }
155
155
  function resolveModel(fields, filename) {
156
156
  const modelId = asString(fields.model);
157
- const effort = asString(fields.reasoning_effort);
157
+ const rawEffort = asString(fields.reasoning_effort)?.trim();
158
+ const effort = rawEffort === "" ? void 0 : rawEffort;
158
159
  if (effort !== void 0 && (modelId === void 0 || modelId === "inherit")) {
159
160
  throw new chunkCEGU5AVD_cjs.ConfigurationError(
160
161
  `Subagent ${filename}: reasoning_effort requires a concrete model (effort is a model parameter; an absent model or "inherit" cannot carry it)`,
@@ -205,5 +206,5 @@ function parseFrontmatterFields(frontmatter) {
205
206
 
206
207
  exports.loadSubagents = loadSubagents;
207
208
  exports.pluginBundleDirs = pluginBundleDirs;
208
- //# sourceMappingURL=chunk-WDVG5R2Q.cjs.map
209
- //# sourceMappingURL=chunk-WDVG5R2Q.cjs.map
209
+ //# sourceMappingURL=chunk-AUH2EVWY.cjs.map
210
+ //# sourceMappingURL=chunk-AUH2EVWY.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/runtime/plugin-loader/plugin-bundles.ts","../src/internal/runtime/skills/subagents-loader.ts"],"names":["pluginBundleRoots","readdir","join","projectConfigRoots","ConfigurationError","diag","readWorkspaceDir","path","readFile","parseSimpleYaml"],"mappings":";;;;;;;;;AAyBA,eAAsB,gBAAA,CACpB,GAAA,EAEA,aAAA,GAAoD,EAAC,EAClC;AACnB,EAAA,MAAM,OAAiB,EAAC;AACxB,EAAA,KAAA,MAAW,IAAA,IAAQA,mCAAA,CAAkB,GAAA,EAAK,aAAa,CAAA,EAAG;AACxD,IAAA,IAAI,OAAA;AACJ,IAAA,IAAI;AACF,MAAA,OAAA,GAAU,MAAMC,gBAAA,CAAQ,IAAA,EAAM,EAAE,aAAA,EAAe,MAAM,CAAA;AAAA,IACvD,CAAA,CAAA,MAAQ;AACN,MAAA;AAAA,IACF;AACA,IAAA,KAAA,MAAW,SAAS,OAAA,EAAS;AAC3B,MAAA,IAAI,KAAA,CAAM,aAAY,EAAG,IAAA,CAAK,KAAKC,SAAA,CAAK,IAAA,EAAM,KAAA,CAAM,IAAI,CAAC,CAAA;AAAA,IAC3D;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT;;;ACrBA,eAAsB,cACpB,GAAA,EACA,4BAAA,EACA,MAAA,EAEA,aAAA,GAAoD,EAAC,EACX;AAC1C,EAAA,MAAM,SAA0C,EAAC;AACjD,EAAA,IAAI,4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A0C,IAAA,CAAK,GAAG,CAAA;AAChE,EAAA,IAAI,UAAU,IAAA,EAAM;AAClB,IAAA,MAAM,IAAIA,oCAAA,CAAmB,CAAA,SAAA,EAAY,QAAQ,CAAA,uBAAA,CAAA,EAA2B;AAAA,MAC1E,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,EACH;AACA,EAAA,OAAO,EAAE,WAAA,EAAa,KAAA,CAAM,CAAC,CAAA,IAAK,EAAA,EAAI,IAAA,EAAA,CAAO,KAAA,CAAM,CAAC,CAAA,IAAK,EAAA,EAAI,IAAA,EAAK,EAAE;AACtE;AAEA,SAAS,uBAAuB,WAAA,EAAmE;AAIjG,EAAA,OAAOK,kCAAgB,WAAW,CAAA;AACpC","file":"chunk-AUH2EVWY.cjs","sourcesContent":["/**\n * Locating the plugin bundles a project carries.\n *\n * Shared by the skills and subagents loaders, which both need the same answer to \"which folders in\n * this project are plugins\" and would otherwise each grow their own copy of the directory walk.\n *\n * @internal\n */\n\nimport type { Dirent } from \"node:fs\";\nimport { readdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { pluginBundleRoots } from \"../../persistence/paths.js\";\nimport type { CompatSourceDeclaration } from \"../compat/foreign-config-sources.js\";\n\n/**\n * Every plugin folder under the project's plugin roots.\n *\n * Returns the FOLDERS, not their contents — what a bundle contributes (`skills/`, `agents/`) is the\n * caller's business, and a loader that also knew the layout would have to change whenever the other\n * one did.\n *\n * A missing root is not an error: most projects carry no plugins, and treating their absence as a\n * failure would make \"none installed\" indistinguishable from \"the directory could not be read\".\n */\nexport async function pluginBundleDirs(\n cwd: string,\n /** Declared foreign dialects (#524). Empty reads `.theokit/plugins` only. */\n compatSources: readonly CompatSourceDeclaration[] = [],\n): Promise<string[]> {\n const dirs: string[] = [];\n for (const root of pluginBundleRoots(cwd, compatSources)) {\n let entries: Dirent[];\n try {\n entries = await readdir(root, { withFileTypes: true });\n } catch {\n continue;\n }\n for (const entry of entries) {\n if (entry.isDirectory()) dirs.push(join(root, entry.name));\n }\n }\n return dirs;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { ConfigurationError } from \"../../../errors.js\";\nimport type { AgentDefinition } from \"../../../types/agent.js\";\nimport type { ModelSelection } from \"../../../types/agent-prims.js\";\nimport { diag } from \"../../diagnostics.js\";\nimport { projectConfigRoots } from \"../../persistence/paths.js\";\nimport type { CompatSourceDeclaration } from \"../compat/foreign-config-sources.js\";\nimport { readWorkspaceDir } from \"../config/workspace-dir.js\";\nimport { type FrontmatterValue, parseSimpleYaml } from \"../context/yaml-frontmatter.js\";\nimport { pluginBundleDirs } from \"../plugin-loader/plugin-bundles.js\";\n\n/**\n * Load file-based subagents from `.theokit/agents/*.md` and merge with\n * inline definitions. Inline overrides file-based on name conflict.\n *\n * Each markdown file has YAML frontmatter (description + optional model)\n * and a body that becomes the subagent prompt.\n *\n * @internal\n */\nexport async function loadSubagents(\n cwd: string,\n settingSourcesIncludeProject: boolean,\n inline: Record<string, AgentDefinition> | undefined,\n /** Declared foreign dialects (#524). Empty reads `.theokit/` only. */\n compatSources: readonly CompatSourceDeclaration[] = [],\n): Promise<Record<string, AgentDefinition>> {\n const result: Record<string, AgentDefinition> = {};\n if (settingSourcesIncludeProject) {\n const projectAgents = await readProjectSubagents(cwd, compatSources);\n for (const [name, definition] of Object.entries(projectAgents)) {\n result[name] = definition;\n }\n }\n if (inline !== undefined) {\n for (const [name, definition] of Object.entries(inline)) {\n result[name] = definition;\n }\n }\n return result;\n}\n\n/**\n * Read agent declarations from every project config root (`.theokit`, then `.claude`).\n *\n * FIRST occurrence of a name wins, which is what makes `projectConfigRoots`' order a contract rather\n * than a detail: a project declaring the same agent in both means the explicit namespace.\n */\nasync function readProjectSubagents(\n cwd: string,\n compatSources: readonly CompatSourceDeclaration[],\n): Promise<Record<string, AgentDefinition>> {\n const subagents: Record<string, AgentDefinition> = {};\n for (const configRoot of projectConfigRoots(cwd, compatSources, \"subagents\")) {\n await readSubagentsFrom(join(configRoot, \"agents\"), subagents);\n }\n // A Claude Code plugin is a BUNDLE, and its `agents/` is what it exists to contribute. Read after\n // the project's own, so a project can shadow an agent a plugin ships without editing the plugin.\n for (const bundle of await pluginBundleDirs(cwd, compatSources)) {\n await readSubagentsFrom(join(bundle, \"agents\"), subagents);\n }\n return subagents;\n}\n\n/**\n * Parse an agent file, or return null when it was written for another runtime.\n *\n * ## What this changed, and what it deliberately did not\n *\n * The failure used to take the whole directory, and that was a decision rather than an oversight:\n * \"a file that HAS frontmatter and gets it wrong is a broken agent and still fails loudly, which is\n * what keeps a typo'd `sandbox` from returning as a silent gate through this door. Isolating the\n * failure per file would hand that risk back.\"\n *\n * The risk named there is real and is NOT handed back, because the isolation is narrower than the\n * one that argument refuses. Only `KNOWN_CLAUDE_CODE_FIELDS` takes this door — the set that already\n * encodes \"this key belongs to another runtime and carries no behaviour here\". A misspelling of one\n * of OUR keys carries `subagent_unknown_field` and still propagates, so `sandboxx` remains fatal\n * and cannot return as a silent gate. `a-claude-code-field-names-itself.test.ts` pins both halves.\n *\n * What moved the decision was the cost, measured in a live TUI on 2026-09-15: one ported\n * `.claude/agents/*.md` carrying `memory:` stopped every sibling agent from loading and the turn\n * produced no answer at all — on an agent the task never used. Beside it, on the same prompt and\n * the same project, another runtime answered normally. The diagnosis fix this file shipped tells a\n * user which key is foreign; it does not give them back the turn.\n *\n * The loader already draws exactly this line for a file with no frontmatter, and for the same\n * stated reason: one of them must not stop every agent in the directory from loading.\n */\nfunction parseOrSkipForeignRuntime(\n raw: string,\n filename: string,\n): { name: string; definition: AgentDefinition } | null {\n try {\n return parseSubagentMarkdown(raw, filename);\n } catch (error) {\n if (error instanceof ConfigurationError && error.code === \"subagent_foreign_runtime_field\") {\n diag(`[theokit-sdk] ${filename}: ${error.message} — skipping this agent`);\n return null;\n }\n throw error;\n }\n}\n\nasync function readSubagentsFrom(\n root: string,\n subagents: Record<string, AgentDefinition>,\n): Promise<void> {\n const entries = await readWorkspaceDir(root, \"subagents_read_error\", \"subagents directory\");\n for (const entry of entries) {\n if (!entry.isFile() || !entry.name.endsWith(\".md\")) continue;\n const path = join(root, entry.name);\n const raw = await readFile(path, \"utf8\");\n // A markdown file with NO frontmatter is not an agent declaration — a directory of agents\n // written for the Claude Code CLI conventionally carries documentation beside them, and\n // `.claude/agents/README.md` exists in this repository. Throwing on it made ONE such file stop\n // every agent in the directory from loading.\n //\n // Skipped with a warn rather than in silence, and ONLY for the no-frontmatter case: a file that\n // HAS frontmatter and gets it wrong is a broken agent and still fails loudly, which is what\n // keeps a typo'd `sandbox` from returning as a silent gate through this door.\n if (!hasFrontmatter(raw)) {\n diag(`[theokit-sdk] ${entry.name} has no frontmatter — not an agent declaration, skipping`);\n continue;\n }\n const definition = parseOrSkipForeignRuntime(raw, entry.name);\n if (definition === null) continue;\n if (subagents[definition.name] === undefined) {\n // `path` is computed above to read the file and was then dropped. Keeping it is the whole\n // visibility fix (#524): without it a listing cannot say which root an agent came from.\n subagents[definition.name] = { ...definition.definition, source: path };\n }\n }\n}\n\n// The frontmatter keys a disk subagent may declare. Any other key is a typed load\n// error rather than a silent drop — a dropped `sandbox` an operator wrote believing\n// it confines the child is exactly the silent-gate failure class this guards against.\nconst ACCEPTED_FIELDS = new Set([\n \"name\",\n \"description\",\n \"model\",\n \"tools\",\n \"reasoning_effort\",\n \"mcp\",\n \"sandbox\",\n \"memory\",\n]);\n\n// Fields the Claude Code CLI writes that carry NO behaviour for this runtime. Accepted and ignored,\n// so an agent authored for the CLI loads here unchanged — measured 2026-08-26 across the 59 agent\n// files on one machine, where `color` appeared in 38 of them and made every one of those a\n// `subagent_unknown_field` load error.\n//\n// Named explicitly instead of loosening the check above, because that check's reason is sound: a\n// dropped `sandbox` an operator wrote believing it confines the child is a silent gate. A field that\n// COULD change behaviour must still fail loudly. This set is the difference between \"we know this\n// one and it does nothing\" and \"we have never heard of this\" — two facts a bare allow-everything\n// would collapse into one.\n//\n// Anything added here needs the same justification: inert for THIS runtime, not merely unfamiliar.\nconst INERT_CLAUDE_CODE_FIELDS = new Set([\n /** The CLI's label colour for the agent. Presentation only. */\n \"color\",\n]);\n\nfunction parseSubagentMarkdown(\n raw: string,\n filename: string,\n): { name: string; definition: AgentDefinition } {\n const { frontmatter, body } = splitFrontmatter(raw, filename);\n const fields = parseFrontmatterFields(frontmatter);\n rejectUnknownFields(fields, filename);\n rejectMcp(fields, filename);\n\n const definition: AgentDefinition = {\n description: asString(fields.description) ?? \"\",\n prompt: body,\n };\n const model = resolveModel(fields, filename);\n if (model !== undefined) definition.model = model;\n const tools = toStringList(fields.tools);\n if (tools.length > 0) definition.tools = tools;\n const sandbox = resolveSandbox(fields, filename);\n if (sandbox !== undefined) definition.sandbox = sandbox;\n // Carried unjudged — see `AgentDefinition.memory`. Which root a scope names, and whether the\n // name is one at all, is `@theokit/agents`' decision and refusing it twice means two lists.\n const memory = asString(fields.memory);\n if (memory !== undefined) definition.memory = memory;\n\n const name = asString(fields.name) ?? filename.replace(/\\.md$/, \"\");\n return { name, definition };\n}\n\n/**\n * Frontmatter keys that Claude Code documents for a subagent and this runtime does not accept.\n *\n * Not an allow-list — every one of these still fails the load. It exists so the FAILURE can say\n * which kind of unknown it met. A user migrating a `.claude/agents/` tree used to learn one key per\n * round trip: fix `memory`, meet `permissionMode`, fix that, meet `maxTurns` — with nothing saying\n * the set was finite or that the tree was simply written for another runtime.\n *\n * The distinction this file already draws for `INERT_CLAUDE_CODE_FIELDS` is the same one: \"the\n * difference between 'we know this one and it does nothing' and 'we have never heard of this' — two\n * facts a bare allow-everything would collapse into one.\" This is the third fact beside them —\n * \"another runtime's field\" — and it changes only the message, never the verdict.\n */\nconst KNOWN_CLAUDE_CODE_FIELDS = new Set([\n \"disallowedTools\",\n \"permissionMode\",\n \"maxTurns\",\n \"skills\",\n \"background\",\n \"effort\",\n \"isolation\",\n \"initialPrompt\",\n \"hooks\",\n \"experimental\",\n \"mcpServers\",\n]);\n\n/**\n * The typed error for a key we do not accept. Built here rather than inline so `rejectUnknownFields`\n * stays a plain loop: the message has two shapes and the code has two values, and computing all four\n * at the throw site is what pushed that function past the cognitive-complexity gate.\n */\nfunction unknownFieldError(key: string, filename: string): ConfigurationError {\n const foreign = KNOWN_CLAUDE_CODE_FIELDS.has(key);\n const siblings = [...KNOWN_CLAUDE_CODE_FIELDS].filter((f) => f !== key);\n const origin = foreign\n ? ` — \"${key}\" is a Claude Code subagent field that this runtime does not support. ` +\n `The same applies to: ${siblings.join(\", \")}. Removing them one at a time will meet each ` +\n `in turn; the tree is written for another runtime`\n : \"\";\n // The two codes are written as LITERALS, one per branch, rather than as a ternary inside the\n // options object. `tools/generate-error-codes.mjs` walks the source for the literal assigned to\n // `code:`, so a ternary there is not a literal and it extracted NEITHER — measured 2026-09-15,\n // when `quality:docs-errors` went red and the regenerated reference had lost\n // `subagent_unknown_field` without ever gaining `subagent_foreign_runtime_field`. Two real,\n // throwable codes were absent from the published error reference, which is the one place a\n // consumer looks to find out what they can catch.\n if (foreign)\n return new ConfigurationError(\n `Subagent ${filename}: unknown frontmatter field \"${key}\" (accepted: ${[...ACCEPTED_FIELDS].join(\", \")})${origin}`,\n { code: \"subagent_foreign_runtime_field\" },\n );\n return new ConfigurationError(\n `Subagent ${filename}: unknown frontmatter field \"${key}\" (accepted: ${[...ACCEPTED_FIELDS].join(\", \")})${origin}`,\n { code: \"subagent_unknown_field\" },\n );\n}\n\nfunction rejectUnknownFields(\n fields: Record<string, FrontmatterValue | undefined>,\n filename: string,\n): void {\n for (const key of Object.keys(fields)) {\n if (INERT_CLAUDE_CODE_FIELDS.has(key)) continue;\n if (!ACCEPTED_FIELDS.has(key)) throw unknownFieldError(key, filename);\n }\n}\n\n// mcp: a known field, but not yet honored on the LOCAL delegation path. The frontmatter YAML can only\n// express server NAMES (parseSimpleYaml has no nested-object support), while a child's `Agent.create`\n// needs `mcpServers` as a Record<name, config>; resolving names→config per-subagent in local delegation\n// is its own follow-up. Rather than silently drop it (the M26/M32 silent-gate class), it is a typed load\n// error that names the field and points at the alternative.\nfunction rejectMcp(fields: Record<string, FrontmatterValue | undefined>, filename: string): void {\n if (fields.mcp !== undefined) {\n throw new ConfigurationError(\n `Subagent ${filename}: per-subagent \"mcp\" is not yet supported on the local delegation path; declare MCP servers in .theokit/mcp.json (or the parent) instead`,\n { code: \"subagent_mcp_unsupported_local\" },\n );\n }\n}\n\n// model + reasoning_effort — effort rides inside `model.params[thinking]`, so it requires a concrete\n// model id to attach to (a child inheriting the parent's model cannot carry the parent's provider-\n// specific effort param safely).\nfunction resolveModel(\n fields: Record<string, FrontmatterValue | undefined>,\n filename: string,\n): ModelSelection | \"inherit\" | undefined {\n const modelId = asString(fields.model);\n // An empty/blank effort (`reasoning_effort: \"\"`) names nothing: treated as absent, never as a\n // `{ id: \"thinking\", value: \"\" }` param the provider would drop or reject.\n const rawEffort = asString(fields.reasoning_effort)?.trim();\n const effort = rawEffort === \"\" ? undefined : rawEffort;\n // reasoning_effort rides in model.params[thinking], so it needs a CONCRETE model id to attach to.\n // Neither an absent model NOR `model: inherit` can carry it (the inherited id is unknown at load), so\n // both are typed errors rather than a silently-dropped effort — the silent-gate class this guards.\n if (effort !== undefined && (modelId === undefined || modelId === \"inherit\")) {\n throw new ConfigurationError(\n `Subagent ${filename}: reasoning_effort requires a concrete model (effort is a model parameter; an absent model or \"inherit\" cannot carry it)`,\n { code: \"subagent_reasoning_effort_without_model\" },\n );\n }\n if (modelId === undefined) return undefined;\n if (modelId === \"inherit\") return \"inherit\";\n return effort !== undefined\n ? { id: modelId, params: [{ id: \"thinking\", value: effort }] }\n : { id: modelId };\n}\n\n// sandbox: boolean only. A granular mode string (read-only/…) is unsupported by the SDK runtime and is\n// a typed error rather than a silent coercion to a boolean.\nfunction resolveSandbox(\n fields: Record<string, FrontmatterValue | undefined>,\n filename: string,\n): boolean | undefined {\n if (fields.sandbox === undefined) return undefined;\n if (typeof fields.sandbox !== \"boolean\") {\n throw new ConfigurationError(\n `Subagent ${filename}: sandbox must be a boolean (got \"${String(fields.sandbox)}\"); granular sandbox modes are not supported by the runtime`,\n { code: \"subagent_sandbox_not_boolean\" },\n );\n }\n return fields.sandbox;\n}\n\nfunction asString(v: FrontmatterValue | undefined): string | undefined {\n if (typeof v !== \"string\") return undefined;\n // parseSimpleYaml does not strip quotes (documented), and `model`/`reasoning_effort` are fields users\n // habitually quote (`model: \"openai/gpt-4o\"`). Strip a single matching surrounding quote pair so a\n // quoted id/effort does not slip past validation and fail only at the provider.\n const m = /^([\"'])(.*)\\1$/.exec(v);\n return m ? m[2] : v;\n}\n\n/** Accept a YAML list (`string[]`) or a comma/space-separated scalar; trim + drop empties. */\nfunction toStringList(v: FrontmatterValue | undefined): string[] {\n if (Array.isArray(v)) return v.map((t) => t.trim()).filter((t) => t.length > 0);\n if (typeof v === \"string\") {\n return v\n .split(/[\\s,]+/)\n .map((t) => t.trim())\n .filter((t) => t.length > 0);\n }\n return [];\n}\n\n/** Does this file open with a frontmatter block at all? Its ABSENCE means \"not an agent\". */\nfunction hasFrontmatter(raw: string): boolean {\n return /^---\\s*\\n/.test(raw);\n}\n\nfunction splitFrontmatter(raw: string, filename: string): { frontmatter: string; body: string } {\n const match = /^---\\s*\\n([\\s\\S]*?)\\n---\\s*\\n([\\s\\S]*)$/.exec(raw);\n if (match === null) {\n throw new ConfigurationError(`Subagent ${filename} is missing frontmatter`, {\n code: \"subagent_missing_frontmatter\",\n });\n }\n return { frontmatter: match[1] ?? \"\", body: (match[2] ?? \"\").trim() };\n}\n\nfunction parseFrontmatterFields(frontmatter: string): Record<string, FrontmatterValue | undefined> {\n // Preserve the rich YAML value types (boolean/number/string[]): `sandbox: true` and\n // `mcp: [a, b]` are meaningful here, so narrowing everything to string (as the\n // pre-M33 loader did) would drop them. Per-field validation happens in parseSubagentMarkdown.\n return parseSimpleYaml(frontmatter);\n}\n"]}
@@ -0,0 +1,55 @@
1
+ 'use strict';
2
+
3
+ var chunkAT2PESXB_cjs = require('./chunk-AT2PESXB.cjs');
4
+
5
+ // src/internal/persistence/sqlite-session-store.ts
6
+ var SqliteSessionStore = class {
7
+ filePath;
8
+ dbPromise;
9
+ constructor(options) {
10
+ this.filePath = options.filePath;
11
+ }
12
+ db() {
13
+ this.dbPromise ??= chunkAT2PESXB_cjs.openSqliteResilient({
14
+ filePath: this.filePath,
15
+ label: "session-store",
16
+ recoverCorrupt: false,
17
+ onOpen: (db) => {
18
+ db.exec(
19
+ "CREATE TABLE IF NOT EXISTS session_records (seq INTEGER PRIMARY KEY AUTOINCREMENT, agent_id TEXT NOT NULL, record TEXT NOT NULL);CREATE INDEX IF NOT EXISTS session_records_agent ON session_records (agent_id, seq);"
20
+ );
21
+ }
22
+ });
23
+ this.dbPromise.catch(() => {
24
+ this.dbPromise = void 0;
25
+ });
26
+ return this.dbPromise;
27
+ }
28
+ async readRecords(agentId) {
29
+ const db = await this.db();
30
+ const rows = db.prepare("SELECT record FROM session_records WHERE agent_id = ? ORDER BY seq").all(agentId);
31
+ return rows.map((r) => JSON.parse(r.record));
32
+ }
33
+ async appendRecords(agentId, records) {
34
+ if (records.length === 0) return;
35
+ const db = await this.db();
36
+ const insert = db.prepare("INSERT INTO session_records (agent_id, record) VALUES (?, ?)");
37
+ db.exec("BEGIN IMMEDIATE");
38
+ try {
39
+ for (const rec of records) insert.run(agentId, JSON.stringify(rec));
40
+ db.exec("COMMIT");
41
+ } catch (err) {
42
+ db.exec("ROLLBACK");
43
+ throw err;
44
+ }
45
+ }
46
+ async dispose() {
47
+ const p = this.dbPromise;
48
+ this.dbPromise = void 0;
49
+ if (p) (await p).close();
50
+ }
51
+ };
52
+
53
+ exports.SqliteSessionStore = SqliteSessionStore;
54
+ //# sourceMappingURL=chunk-BNEUB52I.cjs.map
55
+ //# sourceMappingURL=chunk-BNEUB52I.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/persistence/sqlite-session-store.ts"],"names":["openSqliteResilient"],"mappings":";;;;;AA2BO,IAAM,qBAAN,MAAiD;AAAA,EACrC,QAAA;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IAAA,CAAK,SAAA,CAAU,GAAG,CAAC,CAAA;AAClE,MAAA,EAAA,CAAG,KAAK,QAAQ,CAAA;AAAA,IAClB,SAAS,GAAA,EAAK;AACZ,MAAA,EAAA,CAAG,KAAK,UAAU,CAAA;AAClB,MAAA,MAAM,GAAA;AAAA,IACR;AAAA,EACF;AAAA,EAEA,MAAM,OAAA,GAAyB;AAC7B,IAAA,MAAM,IAAI,IAAA,CAAK,SAAA;AACf,IAAA,IAAA,CAAK,SAAA,GAAY,MAAA;AACjB,IAAA,IAAI,CAAA,EAAG,CAAC,MAAM,CAAA,EAAG,KAAA,EAAM;AAAA,EACzB;AACF","file":"chunk-BNEUB52I.cjs","sourcesContent":["import type { SessionRecord, SessionStore } from \"../../types/session-store.js\";\nimport { openSqliteResilient, type ResilientSqliteDb } from \"./sqlite-open.js\";\n\n/** Options for {@link SqliteSessionStore}. */\nexport interface SqliteSessionStoreOptions {\n /** Absolute path of the SQLite file. Parent directories are created. */\n filePath: string;\n}\n\ninterface Stmt {\n run(...args: unknown[]): unknown;\n all(...args: unknown[]): unknown[];\n}\ninterface Db extends ResilientSqliteDb {\n prepare(sql: string): Stmt;\n}\n\n/**\n * A {@link SessionStore} that keeps the native session records in one SQLite file instead of\n * per-agent JSONL transcripts. Pass it as `local.sessionStore`.\n *\n * Uses `better-sqlite3` when installed, else the built-in `node:sqlite` (Node 22.5+).\n * Appends are one transaction, so a batch lands whole or not at all; order is the\n * autoincrement `seq`. Corruption is NOT silently rebuilt: opening a corrupt file throws.\n *\n * @public\n */\nexport class SqliteSessionStore implements SessionStore {\n private readonly filePath: string;\n private dbPromise: Promise<Db> | undefined;\n\n constructor(options: SqliteSessionStoreOptions) {\n this.filePath = options.filePath;\n }\n\n private db(): Promise<Db> {\n this.dbPromise ??= openSqliteResilient<Db>({\n filePath: this.filePath,\n label: \"session-store\",\n recoverCorrupt: false,\n onOpen: (db) => {\n db.exec(\n \"CREATE TABLE IF NOT EXISTS session_records (seq INTEGER PRIMARY KEY AUTOINCREMENT, agent_id TEXT NOT NULL, record TEXT NOT NULL);\" +\n \"CREATE INDEX IF NOT EXISTS session_records_agent ON session_records (agent_id, seq);\",\n );\n },\n });\n this.dbPromise.catch(() => {\n this.dbPromise = undefined; // allow retry after a failed open\n });\n return this.dbPromise;\n }\n\n async readRecords(agentId: string): Promise<SessionRecord[]> {\n const db = await this.db();\n const rows = db\n .prepare(\"SELECT record FROM session_records WHERE agent_id = ? ORDER BY seq\")\n .all(agentId) as { record: string }[];\n return rows.map((r) => JSON.parse(r.record) as SessionRecord);\n }\n\n async appendRecords(agentId: string, records: readonly SessionRecord[]): Promise<void> {\n if (records.length === 0) return;\n const db = await this.db();\n const insert = db.prepare(\"INSERT INTO session_records (agent_id, record) VALUES (?, ?)\");\n db.exec(\"BEGIN IMMEDIATE\");\n try {\n for (const rec of records) insert.run(agentId, JSON.stringify(rec));\n db.exec(\"COMMIT\");\n } catch (err) {\n db.exec(\"ROLLBACK\");\n throw err;\n }\n }\n\n async dispose(): Promise<void> {\n const p = this.dbPromise;\n this.dbPromise = undefined;\n if (p) (await p).close();\n }\n}\n"]}
@@ -0,0 +1,53 @@
1
+ import { openSqliteResilient } from './chunk-MLJDW2YK.js';
2
+
3
+ // src/internal/persistence/sqlite-session-store.ts
4
+ var SqliteSessionStore = class {
5
+ filePath;
6
+ dbPromise;
7
+ constructor(options) {
8
+ this.filePath = options.filePath;
9
+ }
10
+ db() {
11
+ this.dbPromise ??= openSqliteResilient({
12
+ filePath: this.filePath,
13
+ label: "session-store",
14
+ recoverCorrupt: false,
15
+ onOpen: (db) => {
16
+ db.exec(
17
+ "CREATE TABLE IF NOT EXISTS session_records (seq INTEGER PRIMARY KEY AUTOINCREMENT, agent_id TEXT NOT NULL, record TEXT NOT NULL);CREATE INDEX IF NOT EXISTS session_records_agent ON session_records (agent_id, seq);"
18
+ );
19
+ }
20
+ });
21
+ this.dbPromise.catch(() => {
22
+ this.dbPromise = void 0;
23
+ });
24
+ return this.dbPromise;
25
+ }
26
+ async readRecords(agentId) {
27
+ const db = await this.db();
28
+ const rows = db.prepare("SELECT record FROM session_records WHERE agent_id = ? ORDER BY seq").all(agentId);
29
+ return rows.map((r) => JSON.parse(r.record));
30
+ }
31
+ async appendRecords(agentId, records) {
32
+ if (records.length === 0) return;
33
+ const db = await this.db();
34
+ const insert = db.prepare("INSERT INTO session_records (agent_id, record) VALUES (?, ?)");
35
+ db.exec("BEGIN IMMEDIATE");
36
+ try {
37
+ for (const rec of records) insert.run(agentId, JSON.stringify(rec));
38
+ db.exec("COMMIT");
39
+ } catch (err) {
40
+ db.exec("ROLLBACK");
41
+ throw err;
42
+ }
43
+ }
44
+ async dispose() {
45
+ const p = this.dbPromise;
46
+ this.dbPromise = void 0;
47
+ if (p) (await p).close();
48
+ }
49
+ };
50
+
51
+ export { SqliteSessionStore };
52
+ //# sourceMappingURL=chunk-BPL5CVZ5.js.map
53
+ //# sourceMappingURL=chunk-BPL5CVZ5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/persistence/sqlite-session-store.ts"],"names":[],"mappings":";;;AA2BO,IAAM,qBAAN,MAAiD;AAAA,EACrC,QAAA;AAAA,EACT,SAAA;AAAA,EAER,YAAY,OAAA,EAAoC;AAC9C,IAAA,IAAA,CAAK,WAAW,OAAA,CAAQ,QAAA;AAAA,EAC1B;AAAA,EAEQ,EAAA,GAAkB;AACxB,IAAA,IAAA,CAAK,cAAc,mBAAA,CAAwB;AAAA,MACzC,UAAU,IAAA,CAAK,QAAA;AAAA,MACf,KAAA,EAAO,eAAA;AAAA,MACP,cAAA,EAAgB,KAAA;AAAA,MAChB,MAAA,EAAQ,CAAC,EAAA,KAAO;AACd,QAAA,EAAA,CAAG,IAAA;AAAA,UACD;AAAA,SAEF;AAAA,MACF;AAAA,KACD,CAAA;AACD,IAAA,IAAA,CAAK,SAAA,CAAU,MAAM,MAAM;AACzB,MAAA,IAAA,CAAK,SAAA,GAAY,MAAA;AAAA,IACnB,CAAC,CAAA;AACD,IAAA,OAAO,IAAA,CAAK,SAAA;AAAA,EACd;AAAA,EAEA,MAAM,YAAY,OAAA,EAA2C;AAC3D,IAAA,MAAM,EAAA,GAAK,MAAM,IAAA,CAAK,EAAA,EAAG;AACzB,IAAA,MAAM,OAAO,EAAA,CACV,OAAA,CAAQ,oEAAoE,CAAA,CAC5E,IAAI,OAAO,CAAA;AACd,IAAA,OAAO,IAAA,CAAK,IAAI,CAAC,CAAA,KAAM,KAAK,KAAA,CAAM,CAAA,CAAE,MAAM,CAAkB,CAAA;AAAA,EAC9D;AAAA,EAEA,MAAM,aAAA,CAAc,OAAA,EAAiB,OAAA,EAAkD;AACrF,IAAA,IAAI,OAAA,CAAQ,WAAW,CAAA,EAAG;AAC1B,IAAA,MAAM,EAAA,GAAK,MAAM,IAAA,CAAK,EAAA,EAAG;AACzB,IAAA,MAAM,MAAA,GAAS,EAAA,CAAG,OAAA,CAAQ,8DAA8D,CAAA;AACxF,IAAA,EAAA,CAAG,KAAK,iBAAiB,CAAA;AACzB,IAAA,IAAI;AACF,MAAA,KAAA,MAAW,GAAA,IAAO,SAAS,MAAA,CAAO,GAAA,CAAI,SAAS,IAAA,CAAK,SAAA,CAAU,GAAG,CAAC,CAAA;AAClE,MAAA,EAAA,CAAG,KAAK,QAAQ,CAAA;AAAA,IAClB,SAAS,GAAA,EAAK;AACZ,MAAA,EAAA,CAAG,KAAK,UAAU,CAAA;AAClB,MAAA,MAAM,GAAA;AAAA,IACR;AAAA,EACF;AAAA,EAEA,MAAM,OAAA,GAAyB;AAC7B,IAAA,MAAM,IAAI,IAAA,CAAK,SAAA;AACf,IAAA,IAAA,CAAK,SAAA,GAAY,MAAA;AACjB,IAAA,IAAI,CAAA,EAAG,CAAC,MAAM,CAAA,EAAG,KAAA,EAAM;AAAA,EACzB;AACF","file":"chunk-BPL5CVZ5.js","sourcesContent":["import type { SessionRecord, SessionStore } from \"../../types/session-store.js\";\nimport { openSqliteResilient, type ResilientSqliteDb } from \"./sqlite-open.js\";\n\n/** Options for {@link SqliteSessionStore}. */\nexport interface SqliteSessionStoreOptions {\n /** Absolute path of the SQLite file. Parent directories are created. */\n filePath: string;\n}\n\ninterface Stmt {\n run(...args: unknown[]): unknown;\n all(...args: unknown[]): unknown[];\n}\ninterface Db extends ResilientSqliteDb {\n prepare(sql: string): Stmt;\n}\n\n/**\n * A {@link SessionStore} that keeps the native session records in one SQLite file instead of\n * per-agent JSONL transcripts. Pass it as `local.sessionStore`.\n *\n * Uses `better-sqlite3` when installed, else the built-in `node:sqlite` (Node 22.5+).\n * Appends are one transaction, so a batch lands whole or not at all; order is the\n * autoincrement `seq`. Corruption is NOT silently rebuilt: opening a corrupt file throws.\n *\n * @public\n */\nexport class SqliteSessionStore implements SessionStore {\n private readonly filePath: string;\n private dbPromise: Promise<Db> | undefined;\n\n constructor(options: SqliteSessionStoreOptions) {\n this.filePath = options.filePath;\n }\n\n private db(): Promise<Db> {\n this.dbPromise ??= openSqliteResilient<Db>({\n filePath: this.filePath,\n label: \"session-store\",\n recoverCorrupt: false,\n onOpen: (db) => {\n db.exec(\n \"CREATE TABLE IF NOT EXISTS session_records (seq INTEGER PRIMARY KEY AUTOINCREMENT, agent_id TEXT NOT NULL, record TEXT NOT NULL);\" +\n \"CREATE INDEX IF NOT EXISTS session_records_agent ON session_records (agent_id, seq);\",\n );\n },\n });\n this.dbPromise.catch(() => {\n this.dbPromise = undefined; // allow retry after a failed open\n });\n return this.dbPromise;\n }\n\n async readRecords(agentId: string): Promise<SessionRecord[]> {\n const db = await this.db();\n const rows = db\n .prepare(\"SELECT record FROM session_records WHERE agent_id = ? ORDER BY seq\")\n .all(agentId) as { record: string }[];\n return rows.map((r) => JSON.parse(r.record) as SessionRecord);\n }\n\n async appendRecords(agentId: string, records: readonly SessionRecord[]): Promise<void> {\n if (records.length === 0) return;\n const db = await this.db();\n const insert = db.prepare(\"INSERT INTO session_records (agent_id, record) VALUES (?, ?)\");\n db.exec(\"BEGIN IMMEDIATE\");\n try {\n for (const rec of records) insert.run(agentId, JSON.stringify(rec));\n db.exec(\"COMMIT\");\n } catch (err) {\n db.exec(\"ROLLBACK\");\n throw err;\n }\n }\n\n async dispose(): Promise<void> {\n const p = this.dbPromise;\n this.dbPromise = undefined;\n if (p) (await p).close();\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { getCatalogModelInfo } from './chunk-CJN5CEI3.js';
1
+ import { getCatalogModelInfo } from './chunk-RZL2W4C3.js';
2
2
 
3
3
  // src/internal/llm/model-capabilities.ts
4
4
  var CONSERVATIVE_DEFAULTS = {
@@ -54,5 +54,5 @@ function inferVendorPrefix(bare) {
54
54
  }
55
55
 
56
56
  export { isAnthropicFamilyModel, resolveModelCapabilities };
57
- //# sourceMappingURL=chunk-NVQSBRG6.js.map
58
- //# sourceMappingURL=chunk-NVQSBRG6.js.map
57
+ //# sourceMappingURL=chunk-CBBT42VX.js.map
58
+ //# sourceMappingURL=chunk-CBBT42VX.js.map