@gpustack/loopwright 0.0.0-stage → 0.0.3

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 (477) hide show
  1. package/LICENSE +191 -0
  2. package/README.md +356 -2
  3. package/bin/loopwright.js +3 -0
  4. package/node_modules/@loopwright/agent-pi/dist/adapter-v2.d.ts +9 -0
  5. package/node_modules/@loopwright/agent-pi/dist/adapter-v2.js +122 -0
  6. package/node_modules/@loopwright/agent-pi/dist/adapter.d.ts +30 -0
  7. package/node_modules/@loopwright/agent-pi/dist/adapter.js +340 -0
  8. package/node_modules/@loopwright/agent-pi/dist/admission.d.ts +25 -0
  9. package/node_modules/@loopwright/agent-pi/dist/admission.js +65 -0
  10. package/node_modules/@loopwright/agent-pi/dist/artifacts.d.ts +15 -0
  11. package/node_modules/@loopwright/agent-pi/dist/artifacts.js +76 -0
  12. package/node_modules/@loopwright/agent-pi/dist/boundary.d.ts +18 -0
  13. package/node_modules/@loopwright/agent-pi/dist/boundary.js +113 -0
  14. package/node_modules/@loopwright/agent-pi/dist/broker-channel.d.ts +4 -0
  15. package/node_modules/@loopwright/agent-pi/dist/broker-channel.js +121 -0
  16. package/node_modules/@loopwright/agent-pi/dist/candidate.d.ts +96 -0
  17. package/node_modules/@loopwright/agent-pi/dist/candidate.js +1712 -0
  18. package/node_modules/@loopwright/agent-pi/dist/capture.d.ts +39 -0
  19. package/node_modules/@loopwright/agent-pi/dist/capture.js +146 -0
  20. package/node_modules/@loopwright/agent-pi/dist/cas.d.ts +51 -0
  21. package/node_modules/@loopwright/agent-pi/dist/cas.js +836 -0
  22. package/node_modules/@loopwright/agent-pi/dist/catalog-api.d.ts +3 -0
  23. package/node_modules/@loopwright/agent-pi/dist/catalog-api.js +2 -0
  24. package/node_modules/@loopwright/agent-pi/dist/catalog.d.ts +39 -0
  25. package/node_modules/@loopwright/agent-pi/dist/catalog.js +280 -0
  26. package/node_modules/@loopwright/agent-pi/dist/circuit-breaker-limits.d.ts +9 -0
  27. package/node_modules/@loopwright/agent-pi/dist/circuit-breaker-limits.js +12 -0
  28. package/node_modules/@loopwright/agent-pi/dist/containers.d.ts +29 -0
  29. package/node_modules/@loopwright/agent-pi/dist/containers.js +160 -0
  30. package/node_modules/@loopwright/agent-pi/dist/context.d.ts +56 -0
  31. package/node_modules/@loopwright/agent-pi/dist/context.js +351 -0
  32. package/node_modules/@loopwright/agent-pi/dist/daemon.d.ts +8 -0
  33. package/node_modules/@loopwright/agent-pi/dist/daemon.js +52 -0
  34. package/node_modules/@loopwright/agent-pi/dist/deadline.d.ts +6 -0
  35. package/node_modules/@loopwright/agent-pi/dist/deadline.js +18 -0
  36. package/node_modules/@loopwright/agent-pi/dist/decode-capture.d.ts +39 -0
  37. package/node_modules/@loopwright/agent-pi/dist/decode-capture.js +287 -0
  38. package/node_modules/@loopwright/agent-pi/dist/descriptor.d.ts +12 -0
  39. package/node_modules/@loopwright/agent-pi/dist/descriptor.js +17 -0
  40. package/node_modules/@loopwright/agent-pi/dist/docker-absence.d.ts +2 -0
  41. package/node_modules/@loopwright/agent-pi/dist/docker-absence.js +9 -0
  42. package/node_modules/@loopwright/agent-pi/dist/errors.d.ts +7 -0
  43. package/node_modules/@loopwright/agent-pi/dist/errors.js +19 -0
  44. package/node_modules/@loopwright/agent-pi/dist/event-sequence.d.ts +6 -0
  45. package/node_modules/@loopwright/agent-pi/dist/event-sequence.js +64 -0
  46. package/node_modules/@loopwright/agent-pi/dist/events.d.ts +19 -0
  47. package/node_modules/@loopwright/agent-pi/dist/events.js +132 -0
  48. package/node_modules/@loopwright/agent-pi/dist/execution-guard.d.ts +9 -0
  49. package/node_modules/@loopwright/agent-pi/dist/execution-guard.js +25 -0
  50. package/node_modules/@loopwright/agent-pi/dist/execution-lease.d.ts +24 -0
  51. package/node_modules/@loopwright/agent-pi/dist/execution-lease.js +316 -0
  52. package/node_modules/@loopwright/agent-pi/dist/execution.d.ts +32 -0
  53. package/node_modules/@loopwright/agent-pi/dist/execution.js +476 -0
  54. package/node_modules/@loopwright/agent-pi/dist/external-mcp.d.ts +87 -0
  55. package/node_modules/@loopwright/agent-pi/dist/external-mcp.js +526 -0
  56. package/node_modules/@loopwright/agent-pi/dist/factory-bootstrap.d.ts +15 -0
  57. package/node_modules/@loopwright/agent-pi/dist/factory-bootstrap.js +74 -0
  58. package/node_modules/@loopwright/agent-pi/dist/host-session.d.ts +51 -0
  59. package/node_modules/@loopwright/agent-pi/dist/host-session.js +2094 -0
  60. package/node_modules/@loopwright/agent-pi/dist/http-mcp.d.ts +32 -0
  61. package/node_modules/@loopwright/agent-pi/dist/http-mcp.js +353 -0
  62. package/node_modules/@loopwright/agent-pi/dist/index.d.ts +7 -0
  63. package/node_modules/@loopwright/agent-pi/dist/index.js +4 -0
  64. package/node_modules/@loopwright/agent-pi/dist/lifecycle.d.ts +13 -0
  65. package/node_modules/@loopwright/agent-pi/dist/lifecycle.js +11 -0
  66. package/node_modules/@loopwright/agent-pi/dist/mcp-process.d.ts +35 -0
  67. package/node_modules/@loopwright/agent-pi/dist/mcp-process.js +92 -0
  68. package/node_modules/@loopwright/agent-pi/dist/mcp-transport.d.ts +25 -0
  69. package/node_modules/@loopwright/agent-pi/dist/mcp-transport.js +63 -0
  70. package/node_modules/@loopwright/agent-pi/dist/mcp.d.ts +23 -0
  71. package/node_modules/@loopwright/agent-pi/dist/mcp.js +212 -0
  72. package/node_modules/@loopwright/agent-pi/dist/operation.d.ts +5 -0
  73. package/node_modules/@loopwright/agent-pi/dist/operation.js +28 -0
  74. package/node_modules/@loopwright/agent-pi/dist/policy-v2.d.ts +10 -0
  75. package/node_modules/@loopwright/agent-pi/dist/policy-v2.js +64 -0
  76. package/node_modules/@loopwright/agent-pi/dist/policy.d.ts +13 -0
  77. package/node_modules/@loopwright/agent-pi/dist/policy.js +260 -0
  78. package/node_modules/@loopwright/agent-pi/dist/preflight.d.ts +60 -0
  79. package/node_modules/@loopwright/agent-pi/dist/preflight.js +700 -0
  80. package/node_modules/@loopwright/agent-pi/dist/progress-summary.d.ts +1 -0
  81. package/node_modules/@loopwright/agent-pi/dist/progress-summary.js +119 -0
  82. package/node_modules/@loopwright/agent-pi/dist/protocol.d.ts +17 -0
  83. package/node_modules/@loopwright/agent-pi/dist/protocol.js +131 -0
  84. package/node_modules/@loopwright/agent-pi/dist/provider.d.ts +62 -0
  85. package/node_modules/@loopwright/agent-pi/dist/provider.js +217 -0
  86. package/node_modules/@loopwright/agent-pi/dist/receipt.d.ts +3 -0
  87. package/node_modules/@loopwright/agent-pi/dist/receipt.js +64 -0
  88. package/node_modules/@loopwright/agent-pi/dist/recovery.d.ts +6 -0
  89. package/node_modules/@loopwright/agent-pi/dist/recovery.js +188 -0
  90. package/node_modules/@loopwright/agent-pi/dist/resources.d.ts +13 -0
  91. package/node_modules/@loopwright/agent-pi/dist/resources.js +81 -0
  92. package/node_modules/@loopwright/agent-pi/dist/response.d.ts +20 -0
  93. package/node_modules/@loopwright/agent-pi/dist/response.js +259 -0
  94. package/node_modules/@loopwright/agent-pi/dist/runtime-profile.d.ts +6 -0
  95. package/node_modules/@loopwright/agent-pi/dist/runtime-profile.js +37 -0
  96. package/node_modules/@loopwright/agent-pi/dist/sdk-worker.d.ts +14 -0
  97. package/node_modules/@loopwright/agent-pi/dist/sdk-worker.js +633 -0
  98. package/node_modules/@loopwright/agent-pi/dist/sender.d.ts +46 -0
  99. package/node_modules/@loopwright/agent-pi/dist/sender.js +553 -0
  100. package/node_modules/@loopwright/agent-pi/dist/session-host.d.ts +21 -0
  101. package/node_modules/@loopwright/agent-pi/dist/session-host.js +315 -0
  102. package/node_modules/@loopwright/agent-pi/dist/snapshot-transfer.d.ts +14 -0
  103. package/node_modules/@loopwright/agent-pi/dist/snapshot-transfer.js +102 -0
  104. package/node_modules/@loopwright/agent-pi/dist/snapshot.d.ts +19 -0
  105. package/node_modules/@loopwright/agent-pi/dist/snapshot.js +121 -0
  106. package/node_modules/@loopwright/agent-pi/dist/tool-process.d.ts +32 -0
  107. package/node_modules/@loopwright/agent-pi/dist/tool-process.js +85 -0
  108. package/node_modules/@loopwright/agent-pi/dist/tool-worker.d.ts +2 -0
  109. package/node_modules/@loopwright/agent-pi/dist/tool-worker.js +105 -0
  110. package/node_modules/@loopwright/agent-pi/dist/tools.d.ts +36 -0
  111. package/node_modules/@loopwright/agent-pi/dist/tools.js +128 -0
  112. package/node_modules/@loopwright/agent-pi/dist/types-v2.d.ts +71 -0
  113. package/node_modules/@loopwright/agent-pi/dist/types-v2.js +1 -0
  114. package/node_modules/@loopwright/agent-pi/dist/types.d.ts +314 -0
  115. package/node_modules/@loopwright/agent-pi/dist/types.js +1 -0
  116. package/node_modules/@loopwright/agent-pi/dist/usage.d.ts +18 -0
  117. package/node_modules/@loopwright/agent-pi/dist/usage.js +314 -0
  118. package/node_modules/@loopwright/agent-pi/dist/workspace-mcp.d.ts +27 -0
  119. package/node_modules/@loopwright/agent-pi/dist/workspace-mcp.js +142 -0
  120. package/node_modules/@loopwright/agent-pi/package.json +24 -0
  121. package/node_modules/@loopwright/agent-pi/runtime/Dockerfile +8 -0
  122. package/node_modules/@loopwright/agent-pi/runtime/seccomp.json +1 -0
  123. package/node_modules/@loopwright/cli/dist/arguments.d.ts +19 -0
  124. package/node_modules/@loopwright/cli/dist/arguments.js +358 -0
  125. package/node_modules/@loopwright/cli/dist/closure.d.ts +93 -0
  126. package/node_modules/@loopwright/cli/dist/closure.js +230 -0
  127. package/node_modules/@loopwright/cli/dist/draft.d.ts +9 -0
  128. package/node_modules/@loopwright/cli/dist/draft.js +106 -0
  129. package/node_modules/@loopwright/cli/dist/failure-matrix.d.ts +9 -0
  130. package/node_modules/@loopwright/cli/dist/failure-matrix.js +701 -0
  131. package/node_modules/@loopwright/cli/dist/index.d.ts +6 -0
  132. package/node_modules/@loopwright/cli/dist/index.js +5 -0
  133. package/node_modules/@loopwright/cli/dist/main.d.ts +22 -0
  134. package/node_modules/@loopwright/cli/dist/main.js +1855 -0
  135. package/node_modules/@loopwright/cli/package.json +16 -0
  136. package/node_modules/@loopwright/controller/dist/acceptance.d.ts +43 -0
  137. package/node_modules/@loopwright/controller/dist/acceptance.js +446 -0
  138. package/node_modules/@loopwright/controller/dist/benchmark-gate.d.ts +273 -0
  139. package/node_modules/@loopwright/controller/dist/benchmark-gate.js +3147 -0
  140. package/node_modules/@loopwright/controller/dist/budget-observations.d.ts +25 -0
  141. package/node_modules/@loopwright/controller/dist/budget-observations.js +139 -0
  142. package/node_modules/@loopwright/controller/dist/bundle.d.ts +26 -0
  143. package/node_modules/@loopwright/controller/dist/bundle.js +64 -0
  144. package/node_modules/@loopwright/controller/dist/capture.d.ts +89 -0
  145. package/node_modules/@loopwright/controller/dist/capture.js +587 -0
  146. package/node_modules/@loopwright/controller/dist/compile.d.ts +3 -0
  147. package/node_modules/@loopwright/controller/dist/compile.js +402 -0
  148. package/node_modules/@loopwright/controller/dist/config.d.ts +22 -0
  149. package/node_modules/@loopwright/controller/dist/config.js +255 -0
  150. package/node_modules/@loopwright/controller/dist/controller.d.ts +177 -0
  151. package/node_modules/@loopwright/controller/dist/controller.js +2135 -0
  152. package/node_modules/@loopwright/controller/dist/credentials.d.ts +29 -0
  153. package/node_modules/@loopwright/controller/dist/credentials.js +189 -0
  154. package/node_modules/@loopwright/controller/dist/deadlines.d.ts +18 -0
  155. package/node_modules/@loopwright/controller/dist/deadlines.js +71 -0
  156. package/node_modules/@loopwright/controller/dist/errors.d.ts +27 -0
  157. package/node_modules/@loopwright/controller/dist/errors.js +41 -0
  158. package/node_modules/@loopwright/controller/dist/events.d.ts +52 -0
  159. package/node_modules/@loopwright/controller/dist/events.js +228 -0
  160. package/node_modules/@loopwright/controller/dist/files.d.ts +51 -0
  161. package/node_modules/@loopwright/controller/dist/files.js +386 -0
  162. package/node_modules/@loopwright/controller/dist/finalize.d.ts +25 -0
  163. package/node_modules/@loopwright/controller/dist/finalize.js +32 -0
  164. package/node_modules/@loopwright/controller/dist/gate.d.ts +84 -0
  165. package/node_modules/@loopwright/controller/dist/gate.js +640 -0
  166. package/node_modules/@loopwright/controller/dist/git-objects.d.ts +11 -0
  167. package/node_modules/@loopwright/controller/dist/git-objects.js +59 -0
  168. package/node_modules/@loopwright/controller/dist/git-reader.d.ts +17 -0
  169. package/node_modules/@loopwright/controller/dist/git-reader.js +40 -0
  170. package/node_modules/@loopwright/controller/dist/handlers.d.ts +6 -0
  171. package/node_modules/@loopwright/controller/dist/handlers.js +45 -0
  172. package/node_modules/@loopwright/controller/dist/handoff.d.ts +71 -0
  173. package/node_modules/@loopwright/controller/dist/handoff.js +554 -0
  174. package/node_modules/@loopwright/controller/dist/index.d.ts +41 -0
  175. package/node_modules/@loopwright/controller/dist/index.js +21 -0
  176. package/node_modules/@loopwright/controller/dist/inspect.d.ts +30 -0
  177. package/node_modules/@loopwright/controller/dist/inspect.js +372 -0
  178. package/node_modules/@loopwright/controller/dist/interpolation.d.ts +9 -0
  179. package/node_modules/@loopwright/controller/dist/interpolation.js +79 -0
  180. package/node_modules/@loopwright/controller/dist/ownership.d.ts +41 -0
  181. package/node_modules/@loopwright/controller/dist/ownership.js +666 -0
  182. package/node_modules/@loopwright/controller/dist/parser.d.ts +5 -0
  183. package/node_modules/@loopwright/controller/dist/parser.js +200 -0
  184. package/node_modules/@loopwright/controller/dist/progress.d.ts +41 -0
  185. package/node_modules/@loopwright/controller/dist/progress.js +904 -0
  186. package/node_modules/@loopwright/controller/dist/publication.d.ts +60 -0
  187. package/node_modules/@loopwright/controller/dist/publication.js +329 -0
  188. package/node_modules/@loopwright/controller/dist/reconcile.d.ts +26 -0
  189. package/node_modules/@loopwright/controller/dist/reconcile.js +1378 -0
  190. package/node_modules/@loopwright/controller/dist/recovery.d.ts +10 -0
  191. package/node_modules/@loopwright/controller/dist/recovery.js +315 -0
  192. package/node_modules/@loopwright/controller/dist/refusal-record.d.ts +43 -0
  193. package/node_modules/@loopwright/controller/dist/refusal-record.js +150 -0
  194. package/node_modules/@loopwright/controller/dist/registry.d.ts +6 -0
  195. package/node_modules/@loopwright/controller/dist/registry.js +374 -0
  196. package/node_modules/@loopwright/controller/dist/repair.d.ts +31 -0
  197. package/node_modules/@loopwright/controller/dist/repair.js +102 -0
  198. package/node_modules/@loopwright/controller/dist/report.d.ts +64 -0
  199. package/node_modules/@loopwright/controller/dist/report.js +596 -0
  200. package/node_modules/@loopwright/controller/dist/retained.d.ts +284 -0
  201. package/node_modules/@loopwright/controller/dist/retained.js +193 -0
  202. package/node_modules/@loopwright/controller/dist/rules.d.ts +31 -0
  203. package/node_modules/@loopwright/controller/dist/rules.js +110 -0
  204. package/node_modules/@loopwright/controller/dist/run-eval.d.ts +115 -0
  205. package/node_modules/@loopwright/controller/dist/run-eval.js +959 -0
  206. package/node_modules/@loopwright/controller/dist/scheduler.d.ts +10 -0
  207. package/node_modules/@loopwright/controller/dist/scheduler.js +41 -0
  208. package/node_modules/@loopwright/controller/dist/schema.d.ts +17 -0
  209. package/node_modules/@loopwright/controller/dist/schema.js +78 -0
  210. package/node_modules/@loopwright/controller/dist/source.d.ts +69 -0
  211. package/node_modules/@loopwright/controller/dist/source.js +872 -0
  212. package/node_modules/@loopwright/controller/dist/step.d.ts +38 -0
  213. package/node_modules/@loopwright/controller/dist/step.js +1776 -0
  214. package/node_modules/@loopwright/controller/dist/storage.d.ts +90 -0
  215. package/node_modules/@loopwright/controller/dist/storage.js +1345 -0
  216. package/node_modules/@loopwright/controller/dist/submission.d.ts +51 -0
  217. package/node_modules/@loopwright/controller/dist/submission.js +292 -0
  218. package/node_modules/@loopwright/controller/dist/types.d.ts +585 -0
  219. package/node_modules/@loopwright/controller/dist/types.js +9 -0
  220. package/node_modules/@loopwright/controller/dist/verification.d.ts +124 -0
  221. package/node_modules/@loopwright/controller/dist/verification.js +1308 -0
  222. package/node_modules/@loopwright/controller/dist/verifier-protocol.d.ts +105 -0
  223. package/node_modules/@loopwright/controller/dist/verifier-protocol.js +1312 -0
  224. package/node_modules/@loopwright/controller/dist/verifier-worker.d.ts +1 -0
  225. package/node_modules/@loopwright/controller/dist/verifier-worker.js +33 -0
  226. package/node_modules/@loopwright/controller/package.json +12 -0
  227. package/node_modules/@loopwright/core/dist/acceptance.d.ts +108 -0
  228. package/node_modules/@loopwright/core/dist/acceptance.js +327 -0
  229. package/node_modules/@loopwright/core/dist/artifacts.d.ts +63 -0
  230. package/node_modules/@loopwright/core/dist/artifacts.js +356 -0
  231. package/node_modules/@loopwright/core/dist/boundary.d.ts +21 -0
  232. package/node_modules/@loopwright/core/dist/boundary.js +484 -0
  233. package/node_modules/@loopwright/core/dist/contracts.d.ts +287 -0
  234. package/node_modules/@loopwright/core/dist/contracts.js +694 -0
  235. package/node_modules/@loopwright/core/dist/diagnostics.d.ts +21 -0
  236. package/node_modules/@loopwright/core/dist/diagnostics.js +51 -0
  237. package/node_modules/@loopwright/core/dist/evidence.d.ts +92 -0
  238. package/node_modules/@loopwright/core/dist/evidence.js +85 -0
  239. package/node_modules/@loopwright/core/dist/graph.d.ts +8 -0
  240. package/node_modules/@loopwright/core/dist/graph.js +44 -0
  241. package/node_modules/@loopwright/core/dist/identity.d.ts +162 -0
  242. package/node_modules/@loopwright/core/dist/identity.js +80 -0
  243. package/node_modules/@loopwright/core/dist/index.d.ts +30 -0
  244. package/node_modules/@loopwright/core/dist/index.js +39 -0
  245. package/node_modules/@loopwright/core/dist/limits.d.ts +99 -0
  246. package/node_modules/@loopwright/core/dist/limits.js +59 -0
  247. package/node_modules/@loopwright/core/dist/results.d.ts +161 -0
  248. package/node_modules/@loopwright/core/dist/results.js +98 -0
  249. package/node_modules/@loopwright/core/dist/scope.d.ts +13 -0
  250. package/node_modules/@loopwright/core/dist/scope.js +154 -0
  251. package/node_modules/@loopwright/core/dist/scrubber.d.ts +13 -0
  252. package/node_modules/@loopwright/core/dist/scrubber.js +63 -0
  253. package/node_modules/@loopwright/core/dist/usage.d.ts +68 -0
  254. package/node_modules/@loopwright/core/dist/usage.js +56 -0
  255. package/node_modules/@loopwright/core/package.json +12 -0
  256. package/node_modules/@loopwright/decisions/dist/benchmark.d.ts +23 -0
  257. package/node_modules/@loopwright/decisions/dist/benchmark.js +337 -0
  258. package/node_modules/@loopwright/decisions/dist/client.d.ts +74 -0
  259. package/node_modules/@loopwright/decisions/dist/client.js +292 -0
  260. package/node_modules/@loopwright/decisions/dist/index.d.ts +15 -0
  261. package/node_modules/@loopwright/decisions/dist/index.js +8 -0
  262. package/node_modules/@loopwright/decisions/dist/nodes.d.ts +63 -0
  263. package/node_modules/@loopwright/decisions/dist/nodes.js +282 -0
  264. package/node_modules/@loopwright/decisions/dist/primitives.d.ts +36 -0
  265. package/node_modules/@loopwright/decisions/dist/primitives.js +300 -0
  266. package/node_modules/@loopwright/decisions/dist/redaction.d.ts +23 -0
  267. package/node_modules/@loopwright/decisions/dist/redaction.js +146 -0
  268. package/node_modules/@loopwright/decisions/dist/router.d.ts +55 -0
  269. package/node_modules/@loopwright/decisions/dist/router.js +248 -0
  270. package/node_modules/@loopwright/decisions/dist/schema.d.ts +25 -0
  271. package/node_modules/@loopwright/decisions/dist/schema.js +536 -0
  272. package/node_modules/@loopwright/decisions/dist/types.d.ts +394 -0
  273. package/node_modules/@loopwright/decisions/dist/types.js +80 -0
  274. package/node_modules/@loopwright/decisions/package.json +12 -0
  275. package/node_modules/@loopwright/github-app/dist/action.d.ts +90 -0
  276. package/node_modules/@loopwright/github-app/dist/action.js +2429 -0
  277. package/node_modules/@loopwright/github-app/dist/config.d.ts +23 -0
  278. package/node_modules/@loopwright/github-app/dist/config.js +297 -0
  279. package/node_modules/@loopwright/github-app/dist/digests.d.ts +1 -0
  280. package/node_modules/@loopwright/github-app/dist/digests.js +1 -0
  281. package/node_modules/@loopwright/github-app/dist/index.d.ts +14 -0
  282. package/node_modules/@loopwright/github-app/dist/index.js +13 -0
  283. package/node_modules/@loopwright/github-app/dist/models-config.d.ts +1 -0
  284. package/node_modules/@loopwright/github-app/dist/models-config.js +1 -0
  285. package/node_modules/@loopwright/github-app/dist/output-format.d.ts +1 -0
  286. package/node_modules/@loopwright/github-app/dist/output-format.js +1 -0
  287. package/node_modules/@loopwright/github-app/dist/preflight.d.ts +1 -0
  288. package/node_modules/@loopwright/github-app/dist/preflight.js +1 -0
  289. package/node_modules/@loopwright/github-app/dist/publisher.d.ts +58 -0
  290. package/node_modules/@loopwright/github-app/dist/publisher.js +1368 -0
  291. package/node_modules/@loopwright/github-app/dist/qualification.d.ts +1 -0
  292. package/node_modules/@loopwright/github-app/dist/qualification.js +1 -0
  293. package/node_modules/@loopwright/github-app/dist/sandbox.d.ts +1 -0
  294. package/node_modules/@loopwright/github-app/dist/sandbox.js +1 -0
  295. package/node_modules/@loopwright/github-app/dist/schema.d.ts +1 -0
  296. package/node_modules/@loopwright/github-app/dist/schema.js +1 -0
  297. package/node_modules/@loopwright/github-app/dist/service.d.ts +52 -0
  298. package/node_modules/@loopwright/github-app/dist/service.js +1658 -0
  299. package/node_modules/@loopwright/github-app/dist/suite-pr-lookup.d.ts +90 -0
  300. package/node_modules/@loopwright/github-app/dist/suite-pr-lookup.js +392 -0
  301. package/node_modules/@loopwright/github-app/dist/taskpack.d.ts +1 -0
  302. package/node_modules/@loopwright/github-app/dist/taskpack.js +1 -0
  303. package/node_modules/@loopwright/github-app/dist/tenant-queue.d.ts +44 -0
  304. package/node_modules/@loopwright/github-app/dist/tenant-queue.js +423 -0
  305. package/node_modules/@loopwright/github-app/dist/token-broker.d.ts +50 -0
  306. package/node_modules/@loopwright/github-app/dist/token-broker.js +262 -0
  307. package/node_modules/@loopwright/github-app/dist/turnkey-memory.d.ts +35 -0
  308. package/node_modules/@loopwright/github-app/dist/turnkey-memory.js +1654 -0
  309. package/node_modules/@loopwright/github-app/dist/turnkey.d.ts +16 -0
  310. package/node_modules/@loopwright/github-app/dist/turnkey.js +34 -0
  311. package/node_modules/@loopwright/github-app/dist/types.d.ts +220 -0
  312. package/node_modules/@loopwright/github-app/dist/types.js +14 -0
  313. package/node_modules/@loopwright/github-app/dist/upstreams.d.ts +13 -0
  314. package/node_modules/@loopwright/github-app/dist/upstreams.js +65 -0
  315. package/node_modules/@loopwright/github-app/dist/webhook.d.ts +34 -0
  316. package/node_modules/@loopwright/github-app/dist/webhook.js +241 -0
  317. package/node_modules/@loopwright/github-app/dist/yaml.d.ts +1 -0
  318. package/node_modules/@loopwright/github-app/dist/yaml.js +1 -0
  319. package/node_modules/@loopwright/github-app/package.json +12 -0
  320. package/node_modules/@loopwright/hardware-runner/dist/config.d.ts +48 -0
  321. package/node_modules/@loopwright/hardware-runner/dist/config.js +719 -0
  322. package/node_modules/@loopwright/hardware-runner/dist/evaluator.d.ts +230 -0
  323. package/node_modules/@loopwright/hardware-runner/dist/evaluator.js +3178 -0
  324. package/node_modules/@loopwright/hardware-runner/dist/index.d.ts +13 -0
  325. package/node_modules/@loopwright/hardware-runner/dist/index.js +9 -0
  326. package/node_modules/@loopwright/hardware-runner/dist/provenance.d.ts +128 -0
  327. package/node_modules/@loopwright/hardware-runner/dist/provenance.js +1500 -0
  328. package/node_modules/@loopwright/hardware-runner/dist/queue.d.ts +81 -0
  329. package/node_modules/@loopwright/hardware-runner/dist/queue.js +1081 -0
  330. package/node_modules/@loopwright/hardware-runner/dist/relay-server.d.ts +13 -0
  331. package/node_modules/@loopwright/hardware-runner/dist/relay-server.js +2997 -0
  332. package/node_modules/@loopwright/hardware-runner/dist/types.d.ts +239 -0
  333. package/node_modules/@loopwright/hardware-runner/dist/types.js +12 -0
  334. package/node_modules/@loopwright/hardware-runner/dist/worker.d.ts +49 -0
  335. package/node_modules/@loopwright/hardware-runner/dist/worker.js +1648 -0
  336. package/node_modules/@loopwright/hardware-runner/package.json +12 -0
  337. package/node_modules/@loopwright/memory/dist/cas.d.ts +21 -0
  338. package/node_modules/@loopwright/memory/dist/cas.js +510 -0
  339. package/node_modules/@loopwright/memory/dist/compaction.d.ts +18 -0
  340. package/node_modules/@loopwright/memory/dist/compaction.js +110 -0
  341. package/node_modules/@loopwright/memory/dist/finalizer.d.ts +23 -0
  342. package/node_modules/@loopwright/memory/dist/finalizer.js +538 -0
  343. package/node_modules/@loopwright/memory/dist/index.d.ts +9 -0
  344. package/node_modules/@loopwright/memory/dist/index.js +8 -0
  345. package/node_modules/@loopwright/memory/dist/schema.d.ts +36 -0
  346. package/node_modules/@loopwright/memory/dist/schema.js +510 -0
  347. package/node_modules/@loopwright/memory/dist/selector.d.ts +7 -0
  348. package/node_modules/@loopwright/memory/dist/selector.js +157 -0
  349. package/node_modules/@loopwright/memory/dist/store.d.ts +51 -0
  350. package/node_modules/@loopwright/memory/dist/store.js +554 -0
  351. package/node_modules/@loopwright/memory/dist/types.d.ts +442 -0
  352. package/node_modules/@loopwright/memory/dist/types.js +8 -0
  353. package/node_modules/@loopwright/memory/dist/verifier.d.ts +5 -0
  354. package/node_modules/@loopwright/memory/dist/verifier.js +328 -0
  355. package/node_modules/@loopwright/memory/package.json +12 -0
  356. package/node_modules/@loopwright/state/dist/admission.d.ts +321 -0
  357. package/node_modules/@loopwright/state/dist/admission.js +199 -0
  358. package/node_modules/@loopwright/state/dist/boundary.d.ts +53 -0
  359. package/node_modules/@loopwright/state/dist/boundary.js +194 -0
  360. package/node_modules/@loopwright/state/dist/checkpoint.d.ts +16 -0
  361. package/node_modules/@loopwright/state/dist/checkpoint.js +84 -0
  362. package/node_modules/@loopwright/state/dist/clock.d.ts +8 -0
  363. package/node_modules/@loopwright/state/dist/clock.js +27 -0
  364. package/node_modules/@loopwright/state/dist/connection.d.ts +55 -0
  365. package/node_modules/@loopwright/state/dist/connection.js +391 -0
  366. package/node_modules/@loopwright/state/dist/errors.d.ts +13 -0
  367. package/node_modules/@loopwright/state/dist/errors.js +34 -0
  368. package/node_modules/@loopwright/state/dist/index.d.ts +3 -0
  369. package/node_modules/@loopwright/state/dist/index.js +1 -0
  370. package/node_modules/@loopwright/state/dist/journal.d.ts +119 -0
  371. package/node_modules/@loopwright/state/dist/journal.js +72 -0
  372. package/node_modules/@loopwright/state/dist/model.d.ts +40 -0
  373. package/node_modules/@loopwright/state/dist/model.js +58 -0
  374. package/node_modules/@loopwright/state/dist/ownership.d.ts +14 -0
  375. package/node_modules/@loopwright/state/dist/ownership.js +45 -0
  376. package/node_modules/@loopwright/state/dist/pages.d.ts +11 -0
  377. package/node_modules/@loopwright/state/dist/pages.js +41 -0
  378. package/node_modules/@loopwright/state/dist/receipts.d.ts +33 -0
  379. package/node_modules/@loopwright/state/dist/receipts.js +97 -0
  380. package/node_modules/@loopwright/state/dist/schema.d.ts +28 -0
  381. package/node_modules/@loopwright/state/dist/schema.js +41 -0
  382. package/node_modules/@loopwright/state/dist/settlement.d.ts +10 -0
  383. package/node_modules/@loopwright/state/dist/settlement.js +129 -0
  384. package/node_modules/@loopwright/state/dist/store.d.ts +52 -0
  385. package/node_modules/@loopwright/state/dist/store.js +100 -0
  386. package/node_modules/@loopwright/state/dist/types.d.ts +315 -0
  387. package/node_modules/@loopwright/state/dist/types.js +1 -0
  388. package/node_modules/@loopwright/state/package.json +12 -0
  389. package/node_modules/@loopwright/taskpack/dist/baseline-align.d.ts +195 -0
  390. package/node_modules/@loopwright/taskpack/dist/baseline-align.js +1847 -0
  391. package/node_modules/@loopwright/taskpack/dist/digests.d.ts +61 -0
  392. package/node_modules/@loopwright/taskpack/dist/digests.js +715 -0
  393. package/node_modules/@loopwright/taskpack/dist/index.d.ts +18 -0
  394. package/node_modules/@loopwright/taskpack/dist/index.js +17 -0
  395. package/node_modules/@loopwright/taskpack/dist/models-config.d.ts +112 -0
  396. package/node_modules/@loopwright/taskpack/dist/models-config.js +1026 -0
  397. package/node_modules/@loopwright/taskpack/dist/output-format.d.ts +28 -0
  398. package/node_modules/@loopwright/taskpack/dist/output-format.js +157 -0
  399. package/node_modules/@loopwright/taskpack/dist/preflight.d.ts +130 -0
  400. package/node_modules/@loopwright/taskpack/dist/preflight.js +1497 -0
  401. package/node_modules/@loopwright/taskpack/dist/qualification.d.ts +23 -0
  402. package/node_modules/@loopwright/taskpack/dist/qualification.js +120 -0
  403. package/node_modules/@loopwright/taskpack/dist/sandbox.d.ts +121 -0
  404. package/node_modules/@loopwright/taskpack/dist/sandbox.js +2642 -0
  405. package/node_modules/@loopwright/taskpack/dist/schema.d.ts +197 -0
  406. package/node_modules/@loopwright/taskpack/dist/schema.js +4189 -0
  407. package/node_modules/@loopwright/taskpack/dist/scrubber.d.ts +47 -0
  408. package/node_modules/@loopwright/taskpack/dist/scrubber.js +283 -0
  409. package/node_modules/@loopwright/taskpack/dist/suite.d.ts +124 -0
  410. package/node_modules/@loopwright/taskpack/dist/suite.js +3256 -0
  411. package/node_modules/@loopwright/taskpack/dist/taskpack.d.ts +154 -0
  412. package/node_modules/@loopwright/taskpack/dist/taskpack.js +3634 -0
  413. package/node_modules/@loopwright/taskpack/dist/turnkey-memory.d.ts +122 -0
  414. package/node_modules/@loopwright/taskpack/dist/turnkey-memory.js +483 -0
  415. package/node_modules/@loopwright/taskpack/dist/turnkey.d.ts +437 -0
  416. package/node_modules/@loopwright/taskpack/dist/turnkey.js +7335 -0
  417. package/node_modules/@loopwright/taskpack/dist/types.d.ts +1274 -0
  418. package/node_modules/@loopwright/taskpack/dist/types.js +99 -0
  419. package/node_modules/@loopwright/taskpack/dist/upstreams.d.ts +261 -0
  420. package/node_modules/@loopwright/taskpack/dist/upstreams.js +2242 -0
  421. package/node_modules/@loopwright/taskpack/dist/yaml.d.ts +18 -0
  422. package/node_modules/@loopwright/taskpack/dist/yaml.js +167 -0
  423. package/node_modules/@loopwright/taskpack/package.json +12 -0
  424. package/node_modules/@loopwright/taskpack-runner/dist/compile-taskpack.d.ts +137 -0
  425. package/node_modules/@loopwright/taskpack-runner/dist/compile-taskpack.js +474 -0
  426. package/node_modules/@loopwright/taskpack-runner/dist/corpus.d.ts +8 -0
  427. package/node_modules/@loopwright/taskpack-runner/dist/corpus.js +129 -0
  428. package/node_modules/@loopwright/taskpack-runner/dist/index.d.ts +13 -0
  429. package/node_modules/@loopwright/taskpack-runner/dist/index.js +7 -0
  430. package/node_modules/@loopwright/taskpack-runner/dist/intake.d.ts +149 -0
  431. package/node_modules/@loopwright/taskpack-runner/dist/intake.js +135 -0
  432. package/node_modules/@loopwright/taskpack-runner/dist/parity.d.ts +130 -0
  433. package/node_modules/@loopwright/taskpack-runner/dist/parity.js +927 -0
  434. package/node_modules/@loopwright/taskpack-runner/dist/python-bridge.d.ts +68 -0
  435. package/node_modules/@loopwright/taskpack-runner/dist/python-bridge.js +517 -0
  436. package/node_modules/@loopwright/taskpack-runner/dist/service.d.ts +149 -0
  437. package/node_modules/@loopwright/taskpack-runner/dist/service.js +1796 -0
  438. package/node_modules/@loopwright/taskpack-runner/dist/types.d.ts +29 -0
  439. package/node_modules/@loopwright/taskpack-runner/dist/types.js +11 -0
  440. package/node_modules/@loopwright/taskpack-runner/package.json +12 -0
  441. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/README.md +77 -0
  442. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/docs/support-records.md +57 -0
  443. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/docs/supported-runners.md +98 -0
  444. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/manifest.json +205 -0
  445. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pack/expand_matrix.sh +273 -0
  446. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pack/matrix.yaml +280 -0
  447. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pack/resolve_dockerfile.sh +24 -0
  448. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pyproject.toml +46 -0
  449. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/runtime_runner/runner.py.json +5270 -0
  450. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/discovery/legacy-support.md +86 -0
  451. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/github/service.py +401 -0
  452. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/proposals/analysis.json +95 -0
  453. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/proposals/ready.json +109 -0
  454. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_assemble.py +263 -0
  455. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_check_draft.py +333 -0
  456. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_checks.py +1099 -0
  457. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_discovery.py +817 -0
  458. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_proposal.py +658 -0
  459. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_publish.py +987 -0
  460. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_summary.py +107 -0
  461. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/agent.py +610 -0
  462. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/assemble.py +84 -0
  463. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/check_draft.py +94 -0
  464. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/checks.py +1002 -0
  465. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/discovery.py +789 -0
  466. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/model.py +557 -0
  467. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/progress.py +174 -0
  468. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/prompts/analysis.md +40 -0
  469. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/prompts/proposal.md +65 -0
  470. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/prompts/repair.md +17 -0
  471. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/proposal.py +903 -0
  472. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/publish.py +997 -0
  473. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/summary.py +131 -0
  474. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/tool-versions.json +133 -0
  475. package/node_modules/package-lock.json +3025 -0
  476. package/package-lock.json +3025 -0
  477. package/package.json +52 -4
@@ -0,0 +1,1026 @@
1
+ import { resolve } from 'node:path';
2
+ import { PI_OAUTH_ONLY_PROVIDERS, PI_THINKING_LEVELS, PI_WIRE_APIS, STANDARD_PI_PROVIDER_ENV, isOAuthOnlyPiProvider, resolveBuiltInPiCatalogModel, resolveProviderAuthHeaderName, resolveProviderDestination, validateCustomProviderConfig, validateProviderBaseUrl, validateSelection, } from '@loopwright/agent-pi/catalog';
3
+ import { SecretScrubber } from './scrubber.js';
4
+ import { readBoundedRegularFile } from './yaml.js';
5
+ import { MAX_EXPANDED_MODEL_CANDIDATES, MAX_TASKPACK_MODEL_CANDIDATES, TASKPACK_MANIFEST_BYTES, TaskpackError, } from './types.js';
6
+ const PROVIDER_ID_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
7
+ const ENV_NAME_PATTERN = /^[A-Z][A-Z0-9_]*$/;
8
+ const VAULT_TOKEN_PATTERN = /^[A-Za-z0-9._~+/-]+=*$/;
9
+ const ENV_INTERPOLATION_PATTERN = /^(?:\$\{([A-Z][A-Z0-9_]*)\}|\$([A-Z][A-Z0-9_]*)|([A-Z][A-Z0-9_]*))$/;
10
+ const FORBIDDEN_HEADER_NAMES = new Set([
11
+ 'authorization', 'x-api-key', 'api-key', 'x-goog-api-key', 'cookie', 'proxy-authorization', 'host', 'content-length',
12
+ ]);
13
+ const SAMPLING_KEYS = ['temperature', 'top_p', 'top_k', 'min_p', 'presence_penalty', 'repetition_penalty'];
14
+ const COMPAT_BOOLEAN_KEYS = [
15
+ 'supportsStore', 'supportsDeveloperRole', 'supportsReasoningEffort', 'supportsUsageInStreaming',
16
+ 'requiresToolResultName', 'requiresAssistantAfterToolResult', 'requiresThinkingAsText',
17
+ 'supportsStrictMode', 'zaiToolStream',
18
+ ];
19
+ const COMPAT_ALL_KEYS = [...COMPAT_BOOLEAN_KEYS, 'maxTokensField', 'thinkingFormat'];
20
+ const THINKING_FORMATS = ['openai', 'zai', 'qwen', 'qwen-chat-template', 'openrouter', 'deepseek'];
21
+ const MODEL_COST_KEYS = ['input', 'output', 'cacheRead', 'cacheWrite'];
22
+ const PROBE_MAX_RESPONSE_BYTES = 65_536;
23
+ const DEFAULT_PROBE_TOTAL_TIMEOUT_MS = 30_000;
24
+ const DEFAULT_PROBE_CANDIDATE_TIMEOUT_MS = 15_000;
25
+ export const DEFAULT_PI_PROVIDER = 'zai';
26
+ export const DEFAULT_PI_MODEL = 'glm-5.3';
27
+ export const DEFAULT_PI_THINKING = 'high';
28
+ export const LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV = 'LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN';
29
+ function isOneOf(list, value) {
30
+ return typeof value === 'string' && list.some(item => item === value);
31
+ }
32
+ function errorCode(err) {
33
+ return err !== null && typeof err === 'object' && 'code' in err ? String(err.code) : '';
34
+ }
35
+ function isPlainRecord(value) {
36
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
37
+ return false;
38
+ const proto = Object.getPrototypeOf(value);
39
+ return proto === Object.prototype || proto === null;
40
+ }
41
+ function manifestInvalid(message, path) {
42
+ throw new TaskpackError('TASKPACK_MANIFEST_INVALID', message, path);
43
+ }
44
+ function oauthUnsupported(message, path = null) {
45
+ throw new TaskpackError('PROVIDER_OAUTH_UNSUPPORTED', message, path);
46
+ }
47
+ function bindingInvalid(message, path = null) {
48
+ throw new TaskpackError('TASKPACK_HOST_BINDING_INVALID', message, path);
49
+ }
50
+ function validateSamplingObject(raw, path, fail) {
51
+ if (!isPlainRecord(raw))
52
+ fail('samplingParams must be an object', path);
53
+ const out = {};
54
+ for (const [key, val] of Object.entries(raw)) {
55
+ if (!isOneOf(SAMPLING_KEYS, key))
56
+ fail(`unknown sampling parameter "${key}"`, `${path}/${key}`);
57
+ if (typeof val !== 'number' || !Number.isFinite(val) || Object.is(val, -0)) {
58
+ fail(`sampling parameter "${key}" must be a finite number`, `${path}/${key}`);
59
+ }
60
+ if (key === 'top_k') {
61
+ if (!Number.isSafeInteger(val) || val < 0 || val > 100_000)
62
+ fail('top_k must be an integer in [0, 100000]', `${path}/${key}`);
63
+ }
64
+ else if (val < -4 || val > 4) {
65
+ fail(`sampling parameter "${key}" must be within [-4, 4]`, `${path}/${key}`);
66
+ }
67
+ out[key] = val;
68
+ }
69
+ return Object.freeze(out);
70
+ }
71
+ function validateCompatObject(raw, path, fail) {
72
+ if (!isPlainRecord(raw))
73
+ fail('compat must be an object', path);
74
+ const out = {};
75
+ for (const [key, val] of Object.entries(raw)) {
76
+ if (!isOneOf(COMPAT_ALL_KEYS, key))
77
+ fail(`unknown compat field "${key}"`, `${path}/${key}`);
78
+ if (isOneOf(COMPAT_BOOLEAN_KEYS, key)) {
79
+ if (typeof val !== 'boolean')
80
+ fail(`compat.${key} must be a boolean`, `${path}/${key}`);
81
+ out[key] = val;
82
+ }
83
+ else if (key === 'maxTokensField') {
84
+ if (val !== 'max_completion_tokens' && val !== 'max_tokens') {
85
+ fail('compat.maxTokensField must be "max_completion_tokens" or "max_tokens"', `${path}/${key}`);
86
+ }
87
+ out.maxTokensField = val;
88
+ }
89
+ else if (key === 'thinkingFormat') {
90
+ if (!isOneOf(THINKING_FORMATS, val)) {
91
+ fail(`compat.thinkingFormat must be one of ${THINKING_FORMATS.join(', ')}`, `${path}/${key}`);
92
+ }
93
+ out.thinkingFormat = val;
94
+ }
95
+ }
96
+ return Object.freeze(out);
97
+ }
98
+ function validateHeadersObject(raw, path, fail) {
99
+ if (!isPlainRecord(raw))
100
+ fail('headers must be an object', path);
101
+ const entries = Object.entries(raw);
102
+ if (entries.length > 32)
103
+ fail('headers may contain at most 32 entries', path);
104
+ const out = {};
105
+ for (const [key, val] of entries) {
106
+ const lower = key.toLowerCase();
107
+ if (!/^[A-Za-z0-9-]{1,128}$/.test(key) || FORBIDDEN_HEADER_NAMES.has(lower)) {
108
+ fail(`header "${key}" is forbidden or invalid; pass credentials via environment bindings only`, `${path}/${key}`);
109
+ }
110
+ if (typeof val !== 'string' || val.length > 1024 || /[\0\r\n]/.test(val)) {
111
+ fail(`header "${key}" must be a single-line string of at most 1024 characters`, `${path}/${key}`);
112
+ }
113
+ if (val.startsWith('!')) {
114
+ oauthUnsupported(`shell command header resolvers (!command) are unsupported on "${key}"`, `${path}/${key}`);
115
+ }
116
+ out[key] = val;
117
+ }
118
+ return Object.freeze(out);
119
+ }
120
+ function validateThinkingLevelMapObject(raw, path, fail) {
121
+ if (!isPlainRecord(raw))
122
+ fail('thinkingLevelMap must be an object', path);
123
+ const out = {};
124
+ for (const [key, val] of Object.entries(raw)) {
125
+ if (!isOneOf(PI_THINKING_LEVELS, key)) {
126
+ fail(`thinkingLevelMap key "${key}" must be a valid Pi thinking level`, `${path}/${key}`);
127
+ }
128
+ if (val !== null && (typeof val !== 'string' || val.length < 1 || val.length > 64 || /\s/.test(val))) {
129
+ fail(`thinkingLevelMap["${key}"] must be null or a non-empty token`, `${path}/${key}`);
130
+ }
131
+ out[key] = val;
132
+ }
133
+ return Object.freeze(out);
134
+ }
135
+ function validateSamplingByThinkingObject(raw, path, fail) {
136
+ if (!isPlainRecord(raw))
137
+ fail('samplingParamsByThinkingLevel must be an object', path);
138
+ const out = {};
139
+ for (const [key, val] of Object.entries(raw)) {
140
+ if (!isOneOf(PI_THINKING_LEVELS, key)) {
141
+ fail(`samplingParamsByThinkingLevel key "${key}" must be a valid Pi thinking level`, `${path}/${key}`);
142
+ }
143
+ out[key] = validateSamplingObject(val, `${path}/${key}`, fail);
144
+ }
145
+ return Object.freeze(out);
146
+ }
147
+ function validateModelCostObject(raw, path, fail) {
148
+ if (!isPlainRecord(raw))
149
+ fail('cost must be an object', path);
150
+ for (const key of Object.keys(raw)) {
151
+ if (!isOneOf(MODEL_COST_KEYS, key)) {
152
+ fail(`unknown cost field "${key}"`, `${path}/${key}`);
153
+ }
154
+ }
155
+ if (!Object.hasOwn(raw, 'input') || !Object.hasOwn(raw, 'output')) {
156
+ fail('cost must include required "input" and "output" rates', path);
157
+ }
158
+ const out = { input: 0, output: 0 };
159
+ for (const key of MODEL_COST_KEYS) {
160
+ if (!Object.hasOwn(raw, key))
161
+ continue;
162
+ const val = raw[key];
163
+ if (typeof val !== 'number' || !Number.isFinite(val) || Object.is(val, -0) || val < 0 || val > 1_000_000) {
164
+ fail(`cost.${key} must be a finite number in [0, 1000000]`, `${path}/${key}`);
165
+ }
166
+ out[key] = val;
167
+ }
168
+ return Object.freeze(out);
169
+ }
170
+ /** Validate a single entry inside `spec.models` in `taskpack.yaml`. */
171
+ export function validateTaskpackModelDeclaration(raw, path = '/spec/models/0') {
172
+ if (!isPlainRecord(raw))
173
+ manifestInvalid('spec.models entry must be an object', path);
174
+ if (Object.hasOwn(raw, 'oauth')) {
175
+ oauthUnsupported('OAuth model authentication is unsupported; configure a token-based Pi provider', `${path}/oauth`);
176
+ }
177
+ if (Object.hasOwn(raw, 'apiKey')) {
178
+ manifestInvalid('literal apiKey is forbidden in taskpack.yaml; use apiKeyEnv with an environment variable name', `${path}/apiKey`);
179
+ }
180
+ const allowed = [
181
+ 'provider', 'id', 'thinking', 'api', 'apiKeyEnv', 'baseUrl', 'authHeader', 'headers',
182
+ 'contextWindow', 'maxTokens', 'reasoning', 'thinkingLevelMap', 'samplingParams',
183
+ 'samplingParamsByThinkingLevel', 'compat', 'cost',
184
+ ];
185
+ for (const key of Object.keys(raw)) {
186
+ if (!allowed.includes(key))
187
+ manifestInvalid(`unknown field "${key}" in spec.models entry`, `${path}/${key}`);
188
+ }
189
+ const provider = raw['provider'];
190
+ if (typeof provider !== 'string' || !PROVIDER_ID_PATTERN.test(provider) || provider.includes('..')) {
191
+ manifestInvalid('spec.models[].provider must be a lowercase Pi provider identifier', `${path}/provider`);
192
+ }
193
+ if (isOAuthOnlyPiProvider(provider)) {
194
+ oauthUnsupported(`Pi provider "${provider}" uses OAuth or CLI login (${PI_OAUTH_ONLY_PROVIDERS.join(', ')}), which Loopwright refuses; use a token-authenticated Pi provider`, `${path}/provider`);
195
+ }
196
+ const id = raw['id'];
197
+ if (typeof id !== 'string' || id.length < 1 || id.length > 128 || /[\s\0\r\n]/.test(id)) {
198
+ manifestInvalid('spec.models[].id must be a non-empty model identifier of at most 128 characters', `${path}/id`);
199
+ }
200
+ const result = { provider, id };
201
+ if (raw['thinking'] !== undefined) {
202
+ if (!isOneOf(PI_THINKING_LEVELS, raw['thinking'])) {
203
+ manifestInvalid(`spec.models[].thinking must be one of ${PI_THINKING_LEVELS.join(', ')}`, `${path}/thinking`);
204
+ }
205
+ result.thinking = raw['thinking'];
206
+ }
207
+ if (raw['api'] !== undefined) {
208
+ if (!isOneOf(PI_WIRE_APIS, raw['api'])) {
209
+ manifestInvalid(`spec.models[].api must be one of ${PI_WIRE_APIS.join(', ')}`, `${path}/api`);
210
+ }
211
+ result.api = raw['api'];
212
+ }
213
+ if (raw['apiKeyEnv'] !== undefined) {
214
+ if (typeof raw['apiKeyEnv'] !== 'string') {
215
+ manifestInvalid('spec.models[].apiKeyEnv must be an environment variable name matching [A-Z][A-Z0-9_]*', `${path}/apiKeyEnv`);
216
+ }
217
+ if (raw['apiKeyEnv'].startsWith('!')) {
218
+ oauthUnsupported('shell command credential resolvers (!command) are unsupported', `${path}/apiKeyEnv`);
219
+ }
220
+ if (!ENV_NAME_PATTERN.test(raw['apiKeyEnv'])) {
221
+ manifestInvalid('spec.models[].apiKeyEnv must match [A-Z][A-Z0-9_]*', `${path}/apiKeyEnv`);
222
+ }
223
+ result.apiKeyEnv = raw['apiKeyEnv'];
224
+ }
225
+ if (raw['baseUrl'] !== undefined) {
226
+ try {
227
+ result.baseUrl = validateProviderBaseUrl(raw['baseUrl'], `${path}/baseUrl`);
228
+ }
229
+ catch {
230
+ manifestInvalid('spec.models[].baseUrl must be an https:// URL (or explicit-port http://127.0.0.1 loopback URL) without query, hash, or credentials', `${path}/baseUrl`);
231
+ }
232
+ }
233
+ if (raw['authHeader'] !== undefined) {
234
+ if (typeof raw['authHeader'] !== 'boolean')
235
+ manifestInvalid('spec.models[].authHeader must be a boolean', `${path}/authHeader`);
236
+ result.authHeader = raw['authHeader'];
237
+ }
238
+ if (raw['headers'] !== undefined) {
239
+ result.headers = validateHeadersObject(raw['headers'], `${path}/headers`, manifestInvalid);
240
+ }
241
+ if (raw['contextWindow'] !== undefined) {
242
+ const cw = raw['contextWindow'];
243
+ if (typeof cw !== 'number' || !Number.isSafeInteger(cw) || cw < 1024 || cw > 10_000_000) {
244
+ manifestInvalid('spec.models[].contextWindow must be an integer in [1024, 10000000]', `${path}/contextWindow`);
245
+ }
246
+ result.contextWindow = cw;
247
+ }
248
+ if (raw['maxTokens'] !== undefined) {
249
+ const mt = raw['maxTokens'];
250
+ if (typeof mt !== 'number' || !Number.isSafeInteger(mt) || mt < 1 || mt > 1_048_576) {
251
+ manifestInvalid('spec.models[].maxTokens must be an integer in [1, 1048576]', `${path}/maxTokens`);
252
+ }
253
+ result.maxTokens = mt;
254
+ }
255
+ if (raw['reasoning'] !== undefined) {
256
+ if (typeof raw['reasoning'] !== 'boolean')
257
+ manifestInvalid('spec.models[].reasoning must be a boolean', `${path}/reasoning`);
258
+ result.reasoning = raw['reasoning'];
259
+ }
260
+ if (raw['thinkingLevelMap'] !== undefined) {
261
+ result.thinkingLevelMap = validateThinkingLevelMapObject(raw['thinkingLevelMap'], `${path}/thinkingLevelMap`, manifestInvalid);
262
+ }
263
+ if (raw['samplingParams'] !== undefined) {
264
+ result.samplingParams = validateSamplingObject(raw['samplingParams'], `${path}/samplingParams`, manifestInvalid);
265
+ }
266
+ if (raw['samplingParamsByThinkingLevel'] !== undefined) {
267
+ result.samplingParamsByThinkingLevel = validateSamplingByThinkingObject(raw['samplingParamsByThinkingLevel'], `${path}/samplingParamsByThinkingLevel`, manifestInvalid);
268
+ }
269
+ if (raw['compat'] !== undefined) {
270
+ result.compat = validateCompatObject(raw['compat'], `${path}/compat`, manifestInvalid);
271
+ }
272
+ if (raw['cost'] !== undefined) {
273
+ result.cost = validateModelCostObject(raw['cost'], `${path}/cost`, manifestInvalid);
274
+ }
275
+ return Object.freeze(result);
276
+ }
277
+ /** Validate `spec.models` (`1..8` ordered model candidates) inside `taskpack.yaml`. */
278
+ export function validateTaskpackModelsDeclaration(raw, path = '/spec/models') {
279
+ if (!Array.isArray(raw) || raw.length < 1 || raw.length > MAX_TASKPACK_MODEL_CANDIDATES) {
280
+ manifestInvalid(`spec.models must be an array of 1..${MAX_TASKPACK_MODEL_CANDIDATES} model entries`, path);
281
+ }
282
+ return Object.freeze(raw.map((entry, idx) => validateTaskpackModelDeclaration(entry, `${path}/${idx}`)));
283
+ }
284
+ function parseModelOverrideFields(raw, path) {
285
+ const out = {};
286
+ if (raw['api'] !== undefined) {
287
+ if (!isOneOf(PI_WIRE_APIS, raw['api'])) {
288
+ bindingInvalid(`models.json api must be one of ${PI_WIRE_APIS.join(', ')}`, `${path}/api`);
289
+ }
290
+ out.api = raw['api'];
291
+ }
292
+ if (raw['baseUrl'] !== undefined) {
293
+ try {
294
+ out.baseUrl = validateProviderBaseUrl(raw['baseUrl'], `${path}/baseUrl`);
295
+ }
296
+ catch {
297
+ bindingInvalid('models.json baseUrl must be a valid https:// or loopback URL without query or credentials', `${path}/baseUrl`);
298
+ }
299
+ }
300
+ if (raw['reasoning'] !== undefined) {
301
+ if (typeof raw['reasoning'] !== 'boolean')
302
+ bindingInvalid('models.json reasoning must be a boolean', `${path}/reasoning`);
303
+ out.reasoning = raw['reasoning'];
304
+ }
305
+ if (raw['thinkingLevelMap'] !== undefined) {
306
+ out.thinkingLevelMap = validateThinkingLevelMapObject(raw['thinkingLevelMap'], `${path}/thinkingLevelMap`, bindingInvalid);
307
+ }
308
+ if (raw['contextWindow'] !== undefined) {
309
+ const cw = raw['contextWindow'];
310
+ if (typeof cw !== 'number' || !Number.isSafeInteger(cw) || cw < 1024 || cw > 10_000_000) {
311
+ bindingInvalid('models.json contextWindow must be an integer in [1024, 10000000]', `${path}/contextWindow`);
312
+ }
313
+ out.contextWindow = cw;
314
+ }
315
+ if (raw['maxTokens'] !== undefined) {
316
+ const mt = raw['maxTokens'];
317
+ if (typeof mt !== 'number' || !Number.isSafeInteger(mt) || mt < 1 || mt > 1_048_576) {
318
+ bindingInvalid('models.json maxTokens must be an integer in [1, 1048576]', `${path}/maxTokens`);
319
+ }
320
+ out.maxTokens = mt;
321
+ }
322
+ if (raw['samplingParams'] !== undefined) {
323
+ out.samplingParams = validateSamplingObject(raw['samplingParams'], `${path}/samplingParams`, bindingInvalid);
324
+ }
325
+ if (raw['samplingParamsByThinkingLevel'] !== undefined) {
326
+ out.samplingParamsByThinkingLevel = validateSamplingByThinkingObject(raw['samplingParamsByThinkingLevel'], `${path}/samplingParamsByThinkingLevel`, bindingInvalid);
327
+ }
328
+ if (raw['headers'] !== undefined) {
329
+ out.headers = validateHeadersObject(raw['headers'], `${path}/headers`, bindingInvalid);
330
+ }
331
+ if (raw['compat'] !== undefined) {
332
+ out.compat = validateCompatObject(raw['compat'], `${path}/compat`, bindingInvalid);
333
+ }
334
+ if (raw['cost'] !== undefined) {
335
+ out.cost = validateModelCostObject(raw['cost'], `${path}/cost`, bindingInvalid);
336
+ }
337
+ return Object.freeze(out);
338
+ }
339
+ /** Parse a Pi `models.json` document while enforcing token-only auth and Loopwright send-path boundaries. */
340
+ export function parsePiModelsJson(bytes) {
341
+ if (bytes.byteLength > TASKPACK_MANIFEST_BYTES) {
342
+ bindingInvalid(`models.json exceeds ${TASKPACK_MANIFEST_BYTES} bytes`, '/');
343
+ }
344
+ let text;
345
+ try {
346
+ text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
347
+ }
348
+ catch {
349
+ bindingInvalid('models.json is not valid UTF-8', '/');
350
+ }
351
+ let parsed;
352
+ try {
353
+ parsed = JSON.parse(text);
354
+ }
355
+ catch {
356
+ bindingInvalid('models.json is not valid JSON', '/');
357
+ }
358
+ if (!isPlainRecord(parsed))
359
+ bindingInvalid('models.json root must be an object', '/');
360
+ for (const rootKey of Object.keys(parsed)) {
361
+ if (rootKey !== '$schema' && rootKey !== 'providers') {
362
+ bindingInvalid(`unknown top-level field "${rootKey}" in models.json`, `/${rootKey}`);
363
+ }
364
+ }
365
+ const providersRaw = parsed['providers'];
366
+ if (!isPlainRecord(providersRaw))
367
+ bindingInvalid('models.json must contain a "providers" object', '/providers');
368
+ const providers = new Map();
369
+ for (const [providerId, entryRaw] of Object.entries(providersRaw)) {
370
+ const pPath = `/providers/${providerId}`;
371
+ if (!PROVIDER_ID_PATTERN.test(providerId) || providerId.includes('..')) {
372
+ bindingInvalid(`invalid provider id "${providerId}" in models.json`, pPath);
373
+ }
374
+ if (isOAuthOnlyPiProvider(providerId)) {
375
+ oauthUnsupported(`Pi provider "${providerId}" uses OAuth or CLI login, which Loopwright refuses`, pPath);
376
+ }
377
+ if (!isPlainRecord(entryRaw))
378
+ bindingInvalid('provider entry must be an object', pPath);
379
+ if (entryRaw['oauth'] !== undefined) {
380
+ oauthUnsupported(`models.json provider "${providerId}" declares OAuth login, which Loopwright refuses`, `${pPath}/oauth`);
381
+ }
382
+ const allowedProviderKeys = ['name', 'baseUrl', 'apiKey', 'api', 'headers', 'compat', 'authHeader', 'models', 'modelOverrides'];
383
+ for (const k of Object.keys(entryRaw)) {
384
+ if (!allowedProviderKeys.includes(k))
385
+ bindingInvalid(`unknown field "${k}" in models.json provider "${providerId}"`, `${pPath}/${k}`);
386
+ }
387
+ const entry = { id: providerId, models: new Map(), modelOverrides: new Map() };
388
+ if (entryRaw['baseUrl'] !== undefined) {
389
+ try {
390
+ entry.baseUrl = validateProviderBaseUrl(entryRaw['baseUrl'], `${pPath}/baseUrl`);
391
+ }
392
+ catch {
393
+ bindingInvalid(`invalid baseUrl in models.json provider "${providerId}"`, `${pPath}/baseUrl`);
394
+ }
395
+ }
396
+ if (entryRaw['api'] !== undefined) {
397
+ if (!isOneOf(PI_WIRE_APIS, entryRaw['api'])) {
398
+ bindingInvalid(`models.json provider "${providerId}" api must be one of ${PI_WIRE_APIS.join(', ')}`, `${pPath}/api`);
399
+ }
400
+ entry.api = entryRaw['api'];
401
+ }
402
+ if (entryRaw['apiKey'] !== undefined) {
403
+ if (typeof entryRaw['apiKey'] !== 'string')
404
+ bindingInvalid('models.json apiKey must be a string', `${pPath}/apiKey`);
405
+ if (entryRaw['apiKey'].startsWith('!')) {
406
+ oauthUnsupported('shell command apiKey resolvers (!command) in models.json are unsupported', `${pPath}/apiKey`);
407
+ }
408
+ const match = ENV_INTERPOLATION_PATTERN.exec(entryRaw['apiKey']);
409
+ const envName = match?.[1] ?? match?.[2] ?? match?.[3];
410
+ if (!envName) {
411
+ bindingInvalid('models.json apiKey in Loopwright must reference an uppercase environment variable ($ENV_VAR, ${ENV_VAR}, or ENV_VAR), never a literal secret', `${pPath}/apiKey`);
412
+ }
413
+ entry.apiKeyEnv = envName;
414
+ }
415
+ if (entryRaw['authHeader'] !== undefined) {
416
+ if (typeof entryRaw['authHeader'] !== 'boolean')
417
+ bindingInvalid('models.json authHeader must be a boolean', `${pPath}/authHeader`);
418
+ entry.authHeader = entryRaw['authHeader'];
419
+ }
420
+ if (entryRaw['headers'] !== undefined) {
421
+ entry.headers = validateHeadersObject(entryRaw['headers'], `${pPath}/headers`, bindingInvalid);
422
+ }
423
+ if (entryRaw['compat'] !== undefined) {
424
+ entry.compat = validateCompatObject(entryRaw['compat'], `${pPath}/compat`, bindingInvalid);
425
+ }
426
+ if (entryRaw['models'] !== undefined) {
427
+ if (!Array.isArray(entryRaw['models']) || entryRaw['models'].length > 128) {
428
+ bindingInvalid('models.json models must be an array of at most 128 entries', `${pPath}/models`);
429
+ }
430
+ for (const [idx, mRaw] of entryRaw['models'].entries()) {
431
+ const mPath = `${pPath}/models/${idx}`;
432
+ if (!isPlainRecord(mRaw))
433
+ bindingInvalid('model entry must be an object', mPath);
434
+ const mId = mRaw['id'];
435
+ if (typeof mId !== 'string' || mId.length < 1 || mId.length > 128 || /[\s\0\r\n]/.test(mId)) {
436
+ bindingInvalid('model id must be a non-empty string without whitespace', `${mPath}/id`);
437
+ }
438
+ const overrides = parseModelOverrideFields(mRaw, mPath);
439
+ entry.models.set(mId, Object.freeze({ id: mId, ...overrides }));
440
+ }
441
+ }
442
+ if (entryRaw['modelOverrides'] !== undefined) {
443
+ if (!isPlainRecord(entryRaw['modelOverrides']))
444
+ bindingInvalid('modelOverrides must be an object', `${pPath}/modelOverrides`);
445
+ for (const [mId, oRaw] of Object.entries(entryRaw['modelOverrides'])) {
446
+ const oPath = `${pPath}/modelOverrides/${mId}`;
447
+ if (!isPlainRecord(oRaw))
448
+ bindingInvalid('modelOverride entry must be an object', oPath);
449
+ entry.modelOverrides.set(mId, parseModelOverrideFields(oRaw, oPath));
450
+ }
451
+ }
452
+ providers.set(providerId, Object.freeze(entry));
453
+ }
454
+ return Object.freeze({ providers });
455
+ }
456
+ export async function loadPiModelsJson(filePath) {
457
+ const resolved = resolve(filePath);
458
+ const bytes = await readBoundedRegularFile(resolved, TASKPACK_MANIFEST_BYTES, message => bindingInvalid(`models.json unreadable: ${message}`, '/'));
459
+ return parsePiModelsJson(bytes);
460
+ }
461
+ // ---------------------------------------------------------------------------
462
+ // Candidate resolution, comma-separated token expansion, and readiness probing
463
+ // ---------------------------------------------------------------------------
464
+ export function resolveDefaultProviderTokenEnv(provider, options = {}) {
465
+ if (options.explicitEnv !== undefined)
466
+ return options.explicitEnv;
467
+ if (options.modelsJsonApiKeyEnv !== undefined)
468
+ return options.modelsJsonApiKeyEnv;
469
+ if (options.manifestApiKeyEnv !== undefined)
470
+ return options.manifestApiKeyEnv;
471
+ const standardEnv = STANDARD_PI_PROVIDER_ENV[provider];
472
+ if (standardEnv !== undefined && options.env !== undefined) {
473
+ const hasStandard = typeof options.env[standardEnv] === 'string' && options.env[standardEnv].length > 0;
474
+ const hasGeneric = typeof options.env['LOOPWRIGHT_PROVIDER_TOKEN'] === 'string' && options.env['LOOPWRIGHT_PROVIDER_TOKEN'].length > 0;
475
+ if (hasStandard && !hasGeneric)
476
+ return standardEnv;
477
+ }
478
+ return 'LOOPWRIGHT_PROVIDER_TOKEN';
479
+ }
480
+ /**
481
+ * Split a raw provider token environment variable into ordered deduplicated tokens.
482
+ * Supports comma-separated token pools (`tok1,tok2`), validates vault-safe token characters,
483
+ * and registers every token into `scrubber` immediately.
484
+ */
485
+ export function splitProviderTokens(rawValue, envName, scrubber) {
486
+ if (rawValue === undefined || rawValue.trim().length === 0)
487
+ return Object.freeze([]);
488
+ const seen = new Set();
489
+ const tokens = [];
490
+ for (const part of rawValue.split(',')) {
491
+ const trimmed = part.trim();
492
+ if (trimmed.length === 0)
493
+ continue;
494
+ if (trimmed.length > 4096 || !VAULT_TOKEN_PATTERN.test(trimmed)) {
495
+ scrubber?.register(trimmed);
496
+ bindingInvalid(`provider token in environment variable "${envName}" contains invalid characters or exceeds 4096 bytes`, `/credentials/${envName}`);
497
+ }
498
+ scrubber?.register(trimmed);
499
+ if (!seen.has(trimmed)) {
500
+ seen.add(trimmed);
501
+ tokens.push(trimmed);
502
+ }
503
+ }
504
+ return Object.freeze(tokens);
505
+ }
506
+ function resolveSingleModelEntry(manifestModel, manifestIndex, bindings, modelsConfig, applyHostRoleOverrides, manifestLimitsContextWindow) {
507
+ const hostRole = applyHostRoleOverrides ? bindings.roleSelection : undefined;
508
+ const entryPath = `/spec/models/${manifestIndex}`;
509
+ const provider = hostRole?.provider ?? manifestModel?.provider ?? DEFAULT_PI_PROVIDER;
510
+ if (!PROVIDER_ID_PATTERN.test(provider) || provider.includes('..')) {
511
+ bindingInvalid(`invalid Pi provider identifier "${provider}"`, '/roleSelection/provider');
512
+ }
513
+ if (isOAuthOnlyPiProvider(provider)) {
514
+ oauthUnsupported(`Pi provider "${provider}" uses OAuth or CLI login (${PI_OAUTH_ONLY_PROVIDERS.join(', ')}), which Loopwright refuses; configure a token-based Pi provider`, '/roleSelection/provider');
515
+ }
516
+ const modelsProvider = modelsConfig?.providers.get(provider);
517
+ const manifestMatchesProvider = manifestModel !== undefined && manifestModel.provider === provider;
518
+ const effectiveManifest = manifestMatchesProvider ? manifestModel : undefined;
519
+ const model = hostRole?.model
520
+ ?? effectiveManifest?.id
521
+ ?? (provider === 'zai' || provider === 'zai-coding-cn' ? DEFAULT_PI_MODEL : undefined);
522
+ if (model === undefined || model.length < 1 || model.length > 128 || /[\s\0\r\n]/.test(model)) {
523
+ bindingInvalid(`model identifier is required for Pi provider "${provider}"`, '/roleSelection/model');
524
+ }
525
+ const modelsEntry = modelsProvider?.models.get(model);
526
+ const modelsOverride = modelsProvider?.modelOverrides.get(model);
527
+ if (effectiveManifest?.baseUrl !== undefined &&
528
+ hostRole?.customProvider?.baseUrl === undefined &&
529
+ hostRole?.baseUrl === undefined &&
530
+ modelsEntry?.baseUrl === undefined &&
531
+ modelsOverride?.baseUrl === undefined &&
532
+ modelsProvider?.baseUrl === undefined &&
533
+ bindings.allowManifestCustomBaseUrl !== true) {
534
+ bindingInvalid('manifest spec.models[].baseUrl requires allowManifestCustomBaseUrl (or host base-url / models.json) so untrusted manifests cannot redirect provider credentials', `${entryPath}/baseUrl`);
535
+ }
536
+ const explicitApi = hostRole?.api
537
+ ?? modelsEntry?.api
538
+ ?? modelsOverride?.api
539
+ ?? modelsProvider?.api
540
+ ?? effectiveManifest?.api;
541
+ const builtIn = explicitApi === undefined
542
+ ? resolveBuiltInPiCatalogModel(provider, model)
543
+ : resolveBuiltInPiCatalogModel(provider, model, explicitApi);
544
+ const api = explicitApi ?? builtIn?.api;
545
+ if (api === undefined) {
546
+ bindingInvalid(`Pi model "${provider}/${model}" is not in the built-in Pi catalog; specify api (${PI_WIRE_APIS.join(', ')}) and baseUrl via custom provider configuration or models.json`, '/roleSelection/api');
547
+ }
548
+ const hostCustom = hostRole?.customProvider;
549
+ const mergedBaseUrl = hostCustom?.baseUrl
550
+ ?? hostRole?.baseUrl
551
+ ?? modelsEntry?.baseUrl
552
+ ?? modelsOverride?.baseUrl
553
+ ?? modelsProvider?.baseUrl
554
+ ?? effectiveManifest?.baseUrl;
555
+ const mergedAuthHeader = hostCustom?.authHeader ?? modelsProvider?.authHeader ?? effectiveManifest?.authHeader;
556
+ const mergedHeaders = (() => {
557
+ const parts = [modelsProvider?.headers, effectiveManifest?.headers, modelsOverride?.headers, modelsEntry?.headers, hostCustom?.headers]
558
+ .filter((item) => item !== undefined);
559
+ if (parts.length === 0)
560
+ return undefined;
561
+ const merged = {};
562
+ for (const part of parts)
563
+ Object.assign(merged, part);
564
+ return Object.freeze(merged);
565
+ })();
566
+ const mergedCompat = (() => {
567
+ const parts = [modelsProvider?.compat, effectiveManifest?.compat, modelsOverride?.compat, modelsEntry?.compat, hostCustom?.compat]
568
+ .filter((item) => item !== undefined);
569
+ if (parts.length === 0)
570
+ return undefined;
571
+ const merged = {};
572
+ for (const part of parts)
573
+ Object.assign(merged, part);
574
+ return Object.freeze(merged);
575
+ })();
576
+ const mergedContextWindow = bindings.limits?.contextWindow
577
+ ?? hostCustom?.contextWindow
578
+ ?? manifestLimitsContextWindow
579
+ ?? modelsEntry?.contextWindow
580
+ ?? modelsOverride?.contextWindow
581
+ ?? effectiveManifest?.contextWindow
582
+ ?? bindings.envLimits?.contextWindow;
583
+ const mergedMaxTokens = hostCustom?.maxTokens
584
+ ?? modelsEntry?.maxTokens
585
+ ?? modelsOverride?.maxTokens
586
+ ?? effectiveManifest?.maxTokens;
587
+ const mergedReasoning = hostCustom?.reasoning
588
+ ?? modelsEntry?.reasoning
589
+ ?? modelsOverride?.reasoning
590
+ ?? effectiveManifest?.reasoning;
591
+ const mergedThinkingMap = hostCustom?.thinkingLevelMap
592
+ ?? modelsEntry?.thinkingLevelMap
593
+ ?? modelsOverride?.thinkingLevelMap
594
+ ?? effectiveManifest?.thinkingLevelMap;
595
+ const mergedSampling = hostCustom?.samplingParams
596
+ ?? modelsEntry?.samplingParams
597
+ ?? modelsOverride?.samplingParams
598
+ ?? effectiveManifest?.samplingParams;
599
+ const mergedSamplingByThinking = hostCustom?.samplingParamsByThinkingLevel
600
+ ?? modelsEntry?.samplingParamsByThinkingLevel
601
+ ?? modelsOverride?.samplingParamsByThinkingLevel
602
+ ?? effectiveManifest?.samplingParamsByThinkingLevel;
603
+ const mergedCost = hostCustom?.cost
604
+ ?? modelsEntry?.cost
605
+ ?? modelsOverride?.cost
606
+ ?? effectiveManifest?.cost;
607
+ const hasCustomOverrides = builtIn === null
608
+ || mergedBaseUrl !== undefined
609
+ || mergedAuthHeader !== undefined
610
+ || mergedHeaders !== undefined
611
+ || mergedCompat !== undefined
612
+ || mergedContextWindow !== undefined
613
+ || mergedMaxTokens !== undefined
614
+ || mergedReasoning !== undefined
615
+ || mergedThinkingMap !== undefined
616
+ || mergedSampling !== undefined
617
+ || mergedSamplingByThinking !== undefined
618
+ || mergedCost !== undefined;
619
+ const requestedThinking = hostRole?.thinking ?? effectiveManifest?.thinking;
620
+ const effectiveReasoning = mergedReasoning ?? builtIn?.reasoning ?? (requestedThinking !== undefined ? requestedThinking !== 'off' : true);
621
+ const thinking = requestedThinking ?? (effectiveReasoning ? DEFAULT_PI_THINKING : 'off');
622
+ let customProvider;
623
+ if (hasCustomOverrides) {
624
+ const baseUrl = mergedBaseUrl ?? builtIn?.baseUrl;
625
+ if (baseUrl === undefined) {
626
+ bindingInvalid(`custom Pi provider "${provider}/${model}" requires baseUrl`, '/roleSelection/customProvider/baseUrl');
627
+ }
628
+ const rawCustom = {
629
+ baseUrl,
630
+ contextWindow: mergedContextWindow ?? builtIn?.contextWindow ?? 128_000,
631
+ maxTokens: mergedMaxTokens ?? builtIn?.maxTokens ?? 16_384,
632
+ reasoning: effectiveReasoning,
633
+ };
634
+ if (mergedAuthHeader !== undefined)
635
+ rawCustom.authHeader = mergedAuthHeader;
636
+ if (mergedHeaders !== undefined)
637
+ rawCustom.headers = mergedHeaders;
638
+ const effectiveMap = mergedThinkingMap ?? builtIn?.thinkingLevelMap;
639
+ if (effectiveMap !== undefined)
640
+ rawCustom.thinkingLevelMap = effectiveMap;
641
+ if (mergedSampling !== undefined)
642
+ rawCustom.samplingParams = mergedSampling;
643
+ if (mergedSamplingByThinking !== undefined)
644
+ rawCustom.samplingParamsByThinkingLevel = mergedSamplingByThinking;
645
+ if (mergedCompat !== undefined)
646
+ rawCustom.compat = mergedCompat;
647
+ const effectiveCost = mergedCost ?? builtIn?.cost;
648
+ if (effectiveCost !== undefined)
649
+ rawCustom.cost = effectiveCost;
650
+ try {
651
+ customProvider = validateCustomProviderConfig(rawCustom, '/roleSelection/customProvider');
652
+ }
653
+ catch (err) {
654
+ const code = errorCode(err);
655
+ if (code === 'SEND_PATH_UNSUPPORTED')
656
+ oauthUnsupported('custom Pi provider configuration uses an unsupported credential or send path', '/roleSelection/customProvider');
657
+ bindingInvalid('custom Pi provider configuration failed validation', '/roleSelection/customProvider');
658
+ }
659
+ }
660
+ const candidateSelection = customProvider === undefined
661
+ ? { provider, model, thinking, api }
662
+ : { provider, model, thinking, api, customProvider };
663
+ try {
664
+ validateSelection(candidateSelection, '/roleSelection');
665
+ }
666
+ catch (err) {
667
+ const code = errorCode(err);
668
+ if (code === 'SEND_PATH_UNSUPPORTED') {
669
+ oauthUnsupported(`Pi selection "${provider}/${model}" uses an unsupported OAuth or non-fenced send path`, '/roleSelection');
670
+ }
671
+ bindingInvalid(`Pi selection "${provider}/${model}" (thinking="${thinking}", api="${api}") is unsupported: ${code || 'invalid'}`, '/roleSelection');
672
+ }
673
+ const apiKeyEnv = modelsProvider?.apiKeyEnv ?? effectiveManifest?.apiKeyEnv;
674
+ return apiKeyEnv === undefined ? { selection: candidateSelection } : { selection: candidateSelection, apiKeyEnv };
675
+ }
676
+ /**
677
+ * Shared provider credential env precedence used by both candidate resolution and implicit-author compilation:
678
+ * 1. Host per-provider isolation binding (`credentialEnvMap.byProvider[provider]`) takes highest priority
679
+ * so host-configured per-provider secrets cannot be overridden by ad-hoc options.
680
+ * 2. Caller `explicitProviderTokenEnv` (e.g. `provider-token-env`).
681
+ * 3. For single-model or pinned runs: `credentialEnvMap.provider` > `modelsJsonApiKeyEnv` > `manifestApiKeyEnv`.
682
+ * For unpinned multi-model pools: `modelsJsonApiKeyEnv` > `manifestApiKeyEnv` > `credentialEnvMap.provider`
683
+ * so one global fallback env does not clobber distinct providers' declared keys.
684
+ */
685
+ export function resolveBoundProviderCredentialEnv(input) {
686
+ const byProvider = input.credentialEnvMap?.byProvider;
687
+ const perProviderEnv = byProvider !== undefined && Object.hasOwn(byProvider, input.provider)
688
+ ? byProvider[input.provider]
689
+ : undefined;
690
+ if (perProviderEnv !== undefined)
691
+ return perProviderEnv;
692
+ if (input.explicitProviderTokenEnv !== undefined)
693
+ return input.explicitProviderTokenEnv;
694
+ if (input.hasMultipleModels && !input.hasPinnedCandidate) {
695
+ return input.modelsJsonApiKeyEnv ?? input.manifestApiKeyEnv ?? input.credentialEnvMap?.provider;
696
+ }
697
+ return input.credentialEnvMap?.provider ?? input.modelsJsonApiKeyEnv ?? input.manifestApiKeyEnv;
698
+ }
699
+ /**
700
+ * Validate every declared entry in `manifest.spec.models` and expand comma-separated token pools
701
+ * into an ordered list of `ResolvedModelCandidate` items.
702
+ */
703
+ export function resolveTaskpackModelCandidates(manifest, bindings, options = {}) {
704
+ const effectiveModelsConfig = options.modelsConfig ?? bindings.modelsConfig;
705
+ const manifestModels = manifest.spec.models;
706
+ const manifestLimitsContextWindow = manifest.spec.limits?.contextWindow;
707
+ const hostRole = bindings.roleSelection;
708
+ const hostPinsProviderOrModel = hostRole?.provider !== undefined || hostRole?.model !== undefined;
709
+ const hasMultipleModels = (manifestModels?.length ?? 0) > 1;
710
+ const hasPinnedCandidate = hostPinsProviderOrModel || bindings.candidateIndex !== undefined;
711
+ const validatedManifestEntries = manifestModels === undefined
712
+ ? []
713
+ : manifestModels.map((entry, idx) => resolveSingleModelEntry(entry, idx, bindings, effectiveModelsConfig, false, manifestLimitsContextWindow));
714
+ let baseEntries;
715
+ if (hostPinsProviderOrModel) {
716
+ let matchingIdx = manifestModels?.findIndex(m => (hostRole?.provider === undefined || m.provider === hostRole.provider)
717
+ && (hostRole?.model === undefined || m.id === hostRole.model)) ?? -1;
718
+ if (matchingIdx < 0 && hostRole?.provider !== undefined) {
719
+ matchingIdx = manifestModels?.findIndex(m => m.provider === hostRole.provider) ?? -1;
720
+ }
721
+ const matchedEntry = matchingIdx >= 0 ? manifestModels[matchingIdx] : manifestModels?.[0];
722
+ const resolved = resolveSingleModelEntry(matchedEntry, Math.max(0, matchingIdx), bindings, effectiveModelsConfig, true, manifestLimitsContextWindow);
723
+ baseEntries = [{ manifestIndex: Math.max(0, matchingIdx), ...resolved }];
724
+ }
725
+ else if (manifestModels !== undefined && manifestModels.length > 0) {
726
+ baseEntries = manifestModels.map((entry, idx) => {
727
+ const resolved = hostRole !== undefined
728
+ ? resolveSingleModelEntry(entry, idx, bindings, effectiveModelsConfig, true, manifestLimitsContextWindow)
729
+ : validatedManifestEntries[idx];
730
+ return { manifestIndex: idx, ...resolved };
731
+ });
732
+ }
733
+ else {
734
+ const resolved = resolveSingleModelEntry(undefined, 0, bindings, effectiveModelsConfig, true, manifestLimitsContextWindow);
735
+ baseEntries = [{ manifestIndex: 0, ...resolved }];
736
+ }
737
+ const expanded = [];
738
+ for (const base of baseEntries) {
739
+ const modelsJsonApiKeyEnv = effectiveModelsConfig?.providers.get(base.selection.provider)?.apiKeyEnv;
740
+ const boundEnv = resolveBoundProviderCredentialEnv({
741
+ provider: base.selection.provider,
742
+ credentialEnvMap: bindings.credentialEnvMap,
743
+ explicitProviderTokenEnv: options.explicitProviderTokenEnv,
744
+ modelsJsonApiKeyEnv,
745
+ manifestApiKeyEnv: base.apiKeyEnv,
746
+ hasMultipleModels,
747
+ hasPinnedCandidate,
748
+ });
749
+ const sourceEnvName = resolveDefaultProviderTokenEnv(base.selection.provider, {
750
+ explicitEnv: boundEnv,
751
+ env: options.env,
752
+ });
753
+ const tokens = options.env === undefined
754
+ ? []
755
+ : splitProviderTokens(options.env[sourceEnvName], sourceEnvName, options.scrubber);
756
+ if (tokens.length <= 1) {
757
+ if (expanded.length >= MAX_EXPANDED_MODEL_CANDIDATES) {
758
+ bindingInvalid(`expanded model candidates exceed limit of ${MAX_EXPANDED_MODEL_CANDIDATES}`, '/spec/models');
759
+ }
760
+ expanded.push(Object.freeze({
761
+ index: expanded.length,
762
+ manifestIndex: base.manifestIndex,
763
+ selection: base.selection,
764
+ ...(base.apiKeyEnv !== undefined ? { apiKeyEnv: base.apiKeyEnv } : {}),
765
+ providerEnvName: sourceEnvName,
766
+ ...(tokens[0] !== undefined ? { token: tokens[0] } : {}),
767
+ usesActiveTokenEnv: false,
768
+ }));
769
+ }
770
+ else {
771
+ for (const token of tokens) {
772
+ if (expanded.length >= MAX_EXPANDED_MODEL_CANDIDATES) {
773
+ bindingInvalid(`expanded model candidates exceed limit of ${MAX_EXPANDED_MODEL_CANDIDATES}`, '/spec/models');
774
+ }
775
+ expanded.push(Object.freeze({
776
+ index: expanded.length,
777
+ manifestIndex: base.manifestIndex,
778
+ selection: base.selection,
779
+ ...(base.apiKeyEnv !== undefined ? { apiKeyEnv: base.apiKeyEnv } : {}),
780
+ providerEnvName: LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV,
781
+ sourceTokenEnvName: sourceEnvName,
782
+ token,
783
+ usesActiveTokenEnv: true,
784
+ }));
785
+ }
786
+ }
787
+ }
788
+ return Object.freeze(expanded);
789
+ }
790
+ /** Resolve a single model selection (defaults to index `bindings.candidateIndex ?? 0`) after validating all `spec.models` entries. */
791
+ export function resolveTaskpackModelSelection(manifest, bindings, modelsConfig) {
792
+ const candidates = resolveTaskpackModelCandidates(manifest, bindings, { modelsConfig });
793
+ const idx = bindings.candidateIndex ?? 0;
794
+ if (!Number.isSafeInteger(idx) || idx < 0 || idx >= candidates.length) {
795
+ bindingInvalid(`candidateIndex ${String(idx)} is out of range for ${candidates.length} resolved model candidate(s)`, '/candidateIndex');
796
+ }
797
+ const chosen = candidates[idx];
798
+ return chosen.apiKeyEnv === undefined
799
+ ? { selection: chosen.selection }
800
+ : { selection: chosen.selection, apiKeyEnv: chosen.apiKeyEnv };
801
+ }
802
+ async function readBoundedProbeText(response, maxBytes) {
803
+ if (!response.body)
804
+ return '';
805
+ const reader = response.body.getReader();
806
+ const chunks = [];
807
+ let total = 0;
808
+ try {
809
+ while (true) {
810
+ const { done, value } = await reader.read();
811
+ if (done)
812
+ break;
813
+ total += value.byteLength;
814
+ if (total > maxBytes) {
815
+ await reader.cancel().catch(() => undefined);
816
+ return new TextDecoder('utf-8', { fatal: false }).decode(Buffer.concat(chunks).subarray(0, maxBytes));
817
+ }
818
+ chunks.push(value);
819
+ }
820
+ }
821
+ finally {
822
+ reader.releaseLock();
823
+ }
824
+ return new TextDecoder('utf-8', { fatal: false }).decode(Buffer.concat(chunks));
825
+ }
826
+ function buildProbePayload(selection) {
827
+ if (selection.api === 'anthropic-messages') {
828
+ return { model: selection.model, max_tokens: 1, messages: [{ role: 'user', content: 'Reply OK.' }] };
829
+ }
830
+ if (selection.api === 'openai-responses') {
831
+ return { model: selection.model, max_output_tokens: 16, input: 'Reply OK.' };
832
+ }
833
+ const maxTokensField = selection.customProvider?.compat?.maxTokensField ?? 'max_tokens';
834
+ return {
835
+ model: selection.model,
836
+ stream: false,
837
+ messages: [{ role: 'user', content: 'Reply OK.' }],
838
+ [maxTokensField]: 1,
839
+ };
840
+ }
841
+ function isHealthyProbeBody(bodyText, contentType, api) {
842
+ const trimmed = bodyText.trim();
843
+ if (trimmed.length === 0)
844
+ return { ok: false, reason: 'empty_response_body' };
845
+ if (contentType.toLowerCase().includes('text/event-stream') || trimmed.startsWith('data:') || trimmed.startsWith('event:')) {
846
+ if (/"error"\s*:/.test(trimmed) && !/"error"\s*:\s*null/.test(trimmed)) {
847
+ return { ok: false, reason: 'sse_error_payload' };
848
+ }
849
+ if (trimmed.includes('"choices"') || trimmed.includes('"message_start"') || trimmed.includes('"response.completed"') || trimmed.includes('"output"')) {
850
+ return { ok: true, reason: 'ok' };
851
+ }
852
+ return { ok: false, reason: 'sse_missing_completion' };
853
+ }
854
+ let parsed;
855
+ try {
856
+ parsed = JSON.parse(trimmed);
857
+ }
858
+ catch {
859
+ return { ok: false, reason: 'invalid_json_response' };
860
+ }
861
+ if (!isPlainRecord(parsed))
862
+ return { ok: false, reason: 'non_object_response' };
863
+ if (parsed['error'] !== undefined && parsed['error'] !== null) {
864
+ const errObj = isPlainRecord(parsed['error']) ? parsed['error'] : null;
865
+ const code = errObj && (typeof errObj['code'] === 'string' || typeof errObj['code'] === 'number') ? String(errObj['code']) : 'error';
866
+ return { ok: false, reason: `provider_error_${code}` };
867
+ }
868
+ if (api === 'anthropic-messages') {
869
+ return Array.isArray(parsed['content']) && parsed['content'].length > 0
870
+ ? { ok: true, reason: 'ok' }
871
+ : { ok: false, reason: 'missing_anthropic_content' };
872
+ }
873
+ if (api === 'openai-responses') {
874
+ return (Array.isArray(parsed['output']) && parsed['output'].length > 0) || typeof parsed['output_text'] === 'string'
875
+ ? { ok: true, reason: 'ok' }
876
+ : { ok: false, reason: 'missing_responses_output' };
877
+ }
878
+ return Array.isArray(parsed['choices']) && parsed['choices'].length > 0
879
+ ? { ok: true, reason: 'ok' }
880
+ : { ok: false, reason: 'missing_chat_choices' };
881
+ }
882
+ /**
883
+ * Send a minimal `max_tokens=1` readiness probe (`redirect: 'error'`) to verify that a candidate
884
+ * provider and token have live quota and return a valid completion structure.
885
+ */
886
+ export async function probeModelCandidate(candidate, token, options = {}) {
887
+ const scrubber = options.scrubber ?? new SecretScrubber();
888
+ scrubber.register(token);
889
+ const fetchFn = options.fetchImpl ?? globalThis.fetch;
890
+ const timeoutMs = Math.max(50, Math.min(30_000, options.timeoutMs ?? DEFAULT_PROBE_CANDIDATE_TIMEOUT_MS));
891
+ const { selection } = candidate;
892
+ const url = resolveProviderDestination(selection);
893
+ const authHeader = resolveProviderAuthHeaderName(selection);
894
+ const headers = {
895
+ 'content-type': 'application/json',
896
+ accept: 'application/json',
897
+ ...(selection.api === 'anthropic-messages' ? { 'anthropic-version': '2023-06-01' } : {}),
898
+ ...(selection.customProvider?.headers ?? {}),
899
+ [authHeader]: authHeader === 'x-api-key' ? token : `Bearer ${token}`,
900
+ };
901
+ let response;
902
+ try {
903
+ response = await fetchFn(url, {
904
+ method: 'POST',
905
+ headers,
906
+ body: JSON.stringify(buildProbePayload(selection)),
907
+ redirect: 'error',
908
+ signal: AbortSignal.timeout(timeoutMs),
909
+ });
910
+ }
911
+ catch (err) {
912
+ const rawMsg = err instanceof Error ? err.message : 'network_error';
913
+ return Object.freeze({
914
+ index: candidate.index,
915
+ provider: selection.provider,
916
+ model: selection.model,
917
+ api: selection.api,
918
+ ok: false,
919
+ status: null,
920
+ reason: scrubber.scrub(rawMsg).slice(0, 160),
921
+ });
922
+ }
923
+ const bodyText = await readBoundedProbeText(response, PROBE_MAX_RESPONSE_BYTES).catch(() => '');
924
+ if (response.status !== 200) {
925
+ let reason = `http_${response.status}`;
926
+ try {
927
+ const parsed = JSON.parse(bodyText);
928
+ if (isPlainRecord(parsed) && isPlainRecord(parsed['error'])) {
929
+ const code = parsed['error']['code'] ?? parsed['error']['type'];
930
+ if (typeof code === 'string' || typeof code === 'number')
931
+ reason = `http_${response.status}_${String(code)}`;
932
+ }
933
+ }
934
+ catch {
935
+ // Keep status-based reason when error payload is non-JSON.
936
+ }
937
+ return Object.freeze({
938
+ index: candidate.index,
939
+ provider: selection.provider,
940
+ model: selection.model,
941
+ api: selection.api,
942
+ ok: false,
943
+ status: response.status,
944
+ reason: scrubber.scrub(reason).slice(0, 160),
945
+ });
946
+ }
947
+ const contentType = response.headers.get('content-type') ?? 'application/json';
948
+ const bodyCheck = isHealthyProbeBody(bodyText, contentType, selection.api);
949
+ return Object.freeze({
950
+ index: candidate.index,
951
+ provider: selection.provider,
952
+ model: selection.model,
953
+ api: selection.api,
954
+ ok: bodyCheck.ok,
955
+ status: response.status,
956
+ reason: scrubber.scrub(bodyCheck.reason).slice(0, 160),
957
+ });
958
+ }
959
+ /**
960
+ * Select a healthy model candidate in priority order:
961
+ * - Fast path: when only 1 candidate exists (and `forceProbe` is not set), returns immediately with zero network overhead.
962
+ * - Multi-candidate path: probes candidates in order with a `max_tokens=1` request (`<= 15s` per candidate, `<= 30s` total)
963
+ * and returns the first candidate with live quota and a valid completion response.
964
+ */
965
+ export async function selectHealthyModelCandidate(candidates, options = {}) {
966
+ if (candidates.length === 0) {
967
+ bindingInvalid('at least one model candidate is required', '/spec/models');
968
+ }
969
+ if (candidates.length === 1 && options.forceProbe !== true) {
970
+ return Object.freeze({
971
+ selected: candidates[0],
972
+ index: 0,
973
+ probed: false,
974
+ attempts: Object.freeze([]),
975
+ });
976
+ }
977
+ const scrubber = options.scrubber ?? new SecretScrubber();
978
+ const nowMs = options.nowMs ?? (() => Date.now());
979
+ const totalBudgetMs = Math.max(100, Math.min(60_000, options.totalTimeoutMs ?? DEFAULT_PROBE_TOTAL_TIMEOUT_MS));
980
+ const perCandidateMs = Math.max(50, Math.min(30_000, options.perCandidateTimeoutMs ?? DEFAULT_PROBE_CANDIDATE_TIMEOUT_MS));
981
+ const deadlineMs = nowMs() + totalBudgetMs;
982
+ const attempts = [];
983
+ for (const [pos, candidate] of candidates.entries()) {
984
+ const remainingMs = deadlineMs - nowMs();
985
+ if (remainingMs <= 0) {
986
+ attempts.push(Object.freeze({
987
+ index: candidate.index,
988
+ provider: candidate.selection.provider,
989
+ model: candidate.selection.model,
990
+ api: candidate.selection.api,
991
+ ok: false,
992
+ status: null,
993
+ reason: 'probe_budget_exhausted',
994
+ }));
995
+ break;
996
+ }
997
+ if (candidate.token === undefined || candidate.token.length === 0) {
998
+ attempts.push(Object.freeze({
999
+ index: candidate.index,
1000
+ provider: candidate.selection.provider,
1001
+ model: candidate.selection.model,
1002
+ api: candidate.selection.api,
1003
+ ok: false,
1004
+ status: null,
1005
+ reason: 'missing_token',
1006
+ }));
1007
+ continue;
1008
+ }
1009
+ const attempt = await probeModelCandidate(candidate, candidate.token, {
1010
+ fetchImpl: options.fetchImpl,
1011
+ timeoutMs: Math.min(perCandidateMs, remainingMs),
1012
+ scrubber,
1013
+ });
1014
+ attempts.push(attempt);
1015
+ if (attempt.ok) {
1016
+ return Object.freeze({
1017
+ selected: candidate,
1018
+ index: pos,
1019
+ probed: true,
1020
+ attempts: Object.freeze(attempts),
1021
+ });
1022
+ }
1023
+ }
1024
+ const summary = attempts.map(a => `#${a.index} ${a.provider}/${a.model}: ${a.reason}`).join('; ');
1025
+ bindingInvalid(scrubber.scrub(`no model candidate passed readiness probe (${summary})`), '/spec/models');
1026
+ }