@ggui-ai/ui-gen 0.28.0 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (308) hide show
  1. package/dist/{adapter-h4_V69LI.d.ts → adapter-DLQ-5COm.d.ts} +1 -1
  2. package/dist/adapters/base.js +2 -27
  3. package/dist/adapters/base.js.map +1 -1
  4. package/dist/adapters/generation-dispatch.d.ts +14 -6
  5. package/dist/adapters/generation-dispatch.js +40 -19260
  6. package/dist/adapters/generation-dispatch.js.map +1 -1
  7. package/dist/adapters/index.d.ts +1 -1
  8. package/dist/adapters/index.js +25 -3561
  9. package/dist/adapters/index.js.map +1 -1
  10. package/dist/adapters/types.js +2 -9
  11. package/dist/adapters/types.js.map +1 -1
  12. package/dist/advanced/index.d.ts +13 -12
  13. package/dist/advanced/index.js +63 -21954
  14. package/dist/advanced/index.js.map +1 -1
  15. package/dist/{bank-Ctdp3FUA.d.ts → bank-LWaiAtaA.d.ts} +1 -1
  16. package/dist/blueprint-validator.js +6 -2301
  17. package/dist/blueprint-validator.js.map +1 -1
  18. package/dist/boilerplate.d.ts +3 -2
  19. package/dist/boilerplate.js +6 -1867
  20. package/dist/boilerplate.js.map +1 -1
  21. package/dist/check/index.d.ts +3 -2
  22. package/dist/check/index.js +6 -1923
  23. package/dist/check/index.js.map +1 -1
  24. package/dist/chunk-33B3BAWS.js +24 -0
  25. package/dist/chunk-33B3BAWS.js.map +1 -0
  26. package/dist/chunk-3HSGA6NI.js +591 -0
  27. package/dist/chunk-3HSGA6NI.js.map +1 -0
  28. package/dist/chunk-3NNNGNTO.js +1707 -0
  29. package/dist/chunk-3NNNGNTO.js.map +1 -0
  30. package/dist/chunk-3T2HMTON.js +79 -0
  31. package/dist/chunk-3T2HMTON.js.map +1 -0
  32. package/dist/chunk-3ZSSDV3L.js +123 -0
  33. package/dist/chunk-3ZSSDV3L.js.map +1 -0
  34. package/dist/chunk-4MBR5GA3.js +99 -0
  35. package/dist/chunk-4MBR5GA3.js.map +1 -0
  36. package/dist/chunk-56NJFD55.js +337 -0
  37. package/dist/chunk-56NJFD55.js.map +1 -0
  38. package/dist/chunk-5AGTY555.js +26 -0
  39. package/dist/chunk-5AGTY555.js.map +1 -0
  40. package/dist/chunk-5EJM7EGY.js +115 -0
  41. package/dist/chunk-5EJM7EGY.js.map +1 -0
  42. package/dist/chunk-5KXCQLLR.js +529 -0
  43. package/dist/chunk-5KXCQLLR.js.map +1 -0
  44. package/dist/chunk-5VBXHVEH.js +171 -0
  45. package/dist/chunk-5VBXHVEH.js.map +1 -0
  46. package/dist/chunk-6KDDEING.js +515 -0
  47. package/dist/chunk-6KDDEING.js.map +1 -0
  48. package/dist/chunk-6VDRWAP6.js +123 -0
  49. package/dist/chunk-6VDRWAP6.js.map +1 -0
  50. package/dist/chunk-732IBFEJ.js +2400 -0
  51. package/dist/chunk-732IBFEJ.js.map +1 -0
  52. package/dist/chunk-73AURS3I.js +46 -0
  53. package/dist/chunk-73AURS3I.js.map +1 -0
  54. package/dist/chunk-77H5SKLX.js +8 -0
  55. package/dist/chunk-77H5SKLX.js.map +1 -0
  56. package/dist/chunk-7QE3AHLE.js +35 -0
  57. package/dist/chunk-7QE3AHLE.js.map +1 -0
  58. package/dist/chunk-A375NNWN.js +11 -0
  59. package/dist/chunk-A375NNWN.js.map +1 -0
  60. package/dist/chunk-AOU33EFS.js +140 -0
  61. package/dist/chunk-AOU33EFS.js.map +1 -0
  62. package/dist/chunk-BA4QYA6E.js +461 -0
  63. package/dist/chunk-BA4QYA6E.js.map +1 -0
  64. package/dist/chunk-DBP764GL.js +3 -0
  65. package/dist/chunk-DBP764GL.js.map +1 -0
  66. package/dist/chunk-DUU3ZJDQ.js +41 -0
  67. package/dist/chunk-DUU3ZJDQ.js.map +1 -0
  68. package/dist/chunk-DXKRBXNU.js +30 -0
  69. package/dist/chunk-DXKRBXNU.js.map +1 -0
  70. package/dist/chunk-FB7OEEAH.js +1467 -0
  71. package/dist/chunk-FB7OEEAH.js.map +1 -0
  72. package/dist/chunk-FLRNMZV2.js +18 -0
  73. package/dist/chunk-FLRNMZV2.js.map +1 -0
  74. package/dist/chunk-FWJIMKFZ.js +2032 -0
  75. package/dist/chunk-FWJIMKFZ.js.map +1 -0
  76. package/dist/chunk-FXRHWYIQ.js +163 -0
  77. package/dist/chunk-FXRHWYIQ.js.map +1 -0
  78. package/dist/chunk-G3PMV62Z.js +33 -0
  79. package/dist/chunk-G3PMV62Z.js.map +1 -0
  80. package/dist/chunk-GAJI7Y3P.js +13 -0
  81. package/dist/chunk-GAJI7Y3P.js.map +1 -0
  82. package/dist/chunk-GYINWMPR.js +2052 -0
  83. package/dist/chunk-GYINWMPR.js.map +1 -0
  84. package/dist/chunk-HD6ABIK7.js +484 -0
  85. package/dist/chunk-HD6ABIK7.js.map +1 -0
  86. package/dist/chunk-HDQVHYO6.js +100 -0
  87. package/dist/chunk-HDQVHYO6.js.map +1 -0
  88. package/dist/chunk-IHUT3SIW.js +7 -0
  89. package/dist/chunk-IHUT3SIW.js.map +1 -0
  90. package/dist/chunk-JDH5EGNZ.js +126 -0
  91. package/dist/chunk-JDH5EGNZ.js.map +1 -0
  92. package/dist/chunk-JMD4RGSV.js +37 -0
  93. package/dist/chunk-JMD4RGSV.js.map +1 -0
  94. package/dist/chunk-KJWGZL5B.js +33 -0
  95. package/dist/chunk-KJWGZL5B.js.map +1 -0
  96. package/dist/chunk-MKMDQFZ7.js +86 -0
  97. package/dist/chunk-MKMDQFZ7.js.map +1 -0
  98. package/dist/chunk-NF6JUZWF.js +85 -0
  99. package/dist/chunk-NF6JUZWF.js.map +1 -0
  100. package/dist/chunk-O2YC6XDC.js +1933 -0
  101. package/dist/chunk-O2YC6XDC.js.map +1 -0
  102. package/dist/chunk-OVLH5ICV.js +29 -0
  103. package/dist/chunk-OVLH5ICV.js.map +1 -0
  104. package/dist/chunk-PBOYHGSD.js +106 -0
  105. package/dist/chunk-PBOYHGSD.js.map +1 -0
  106. package/dist/chunk-PJFH7QWA.js +81 -0
  107. package/dist/chunk-PJFH7QWA.js.map +1 -0
  108. package/dist/chunk-PUH4CXGZ.js +284 -0
  109. package/dist/chunk-PUH4CXGZ.js.map +1 -0
  110. package/dist/chunk-QLXXPGTV.js +18 -0
  111. package/dist/chunk-QLXXPGTV.js.map +1 -0
  112. package/dist/chunk-R5GIGPW2.js +2845 -0
  113. package/dist/chunk-R5GIGPW2.js.map +1 -0
  114. package/dist/chunk-RH4IUSTO.js +83 -0
  115. package/dist/chunk-RH4IUSTO.js.map +1 -0
  116. package/dist/chunk-S2GVXKKY.js +153 -0
  117. package/dist/chunk-S2GVXKKY.js.map +1 -0
  118. package/dist/chunk-TVHGKFJS.js +58 -0
  119. package/dist/chunk-TVHGKFJS.js.map +1 -0
  120. package/dist/chunk-U7GALWLG.js +66 -0
  121. package/dist/chunk-U7GALWLG.js.map +1 -0
  122. package/dist/chunk-VTC263LT.js +256 -0
  123. package/dist/chunk-VTC263LT.js.map +1 -0
  124. package/dist/chunk-WEOXFEVE.js +739 -0
  125. package/dist/chunk-WEOXFEVE.js.map +1 -0
  126. package/dist/chunk-WYHP46LT.js +28 -0
  127. package/dist/chunk-WYHP46LT.js.map +1 -0
  128. package/dist/chunk-XGLO5LGG.js +274 -0
  129. package/dist/chunk-XGLO5LGG.js.map +1 -0
  130. package/dist/chunk-XRBCRKA2.js +29 -0
  131. package/dist/chunk-XRBCRKA2.js.map +1 -0
  132. package/dist/chunk-XW7ADFFV.js +340 -0
  133. package/dist/chunk-XW7ADFFV.js.map +1 -0
  134. package/dist/chunk-YIQ42IUX.js +34 -0
  135. package/dist/chunk-YIQ42IUX.js.map +1 -0
  136. package/dist/chunk-YJZTUY7B.js +101 -0
  137. package/dist/chunk-YJZTUY7B.js.map +1 -0
  138. package/dist/chunk-Z3CXME3K.js +107 -0
  139. package/dist/chunk-Z3CXME3K.js.map +1 -0
  140. package/dist/classifier/index.js +2 -527
  141. package/dist/classifier/index.js.map +1 -1
  142. package/dist/client-JBPCXU7W.js +4 -0
  143. package/dist/client-JBPCXU7W.js.map +1 -0
  144. package/dist/compose.js +3 -367
  145. package/dist/compose.js.map +1 -1
  146. package/dist/cost-tracker-HHGQ4FTW.js +67 -0
  147. package/dist/cost-tracker-HHGQ4FTW.js.map +1 -0
  148. package/dist/{create-ui-generator-BrZHF0cf.d.ts → create-ui-generator-BY-WeaPi.d.ts} +3 -3
  149. package/dist/{design-mode-DGWN_Gkm.d.ts → design-mode-XyOQmzE0.d.ts} +4 -3
  150. package/dist/{dispatch-B07TI30d.d.ts → dispatch-8LzTddKw.d.ts} +3 -2
  151. package/dist/dist-UALN6ZVB.js +543 -0
  152. package/dist/dist-UALN6ZVB.js.map +1 -0
  153. package/dist/dupe-break-X6K7QFIS.js +4 -0
  154. package/dist/dupe-break-X6K7QFIS.js.map +1 -0
  155. package/dist/evaluation/axis-checks/index.d.ts +5 -4
  156. package/dist/evaluation/axis-checks/index.js +6 -1914
  157. package/dist/evaluation/axis-checks/index.js.map +1 -1
  158. package/dist/evaluation/axis-checks/registry.d.ts +3 -2
  159. package/dist/evaluation/axis-checks/registry.js +3 -1844
  160. package/dist/evaluation/axis-checks/registry.js.map +1 -1
  161. package/dist/evaluation/index.d.ts +49 -132
  162. package/dist/evaluation/index.js +302 -6466
  163. package/dist/evaluation/index.js.map +1 -1
  164. package/dist/evaluation/types.d.ts +3 -2
  165. package/dist/evaluation/types.js +2 -5
  166. package/dist/evaluation/types.js.map +1 -1
  167. package/dist/fragments/index.js +2 -338
  168. package/dist/fragments/index.js.map +1 -1
  169. package/dist/{generate-tSO_shQ0.d.ts → generate-DQ4ci90s.d.ts} +1 -1
  170. package/dist/harness/check/runtime-render/index.d.ts +35 -15
  171. package/dist/harness/check/runtime-render/index.js +6 -2390
  172. package/dist/harness/check/runtime-render/index.js.map +1 -1
  173. package/dist/harness/check/runtime-render/render-check-worker.js +4 -1739
  174. package/dist/harness/check/runtime-render/render-check-worker.js.map +1 -1
  175. package/dist/harness/index.d.ts +3 -2
  176. package/dist/harness/index.js +23 -5126
  177. package/dist/harness/index.js.map +1 -1
  178. package/dist/harness/llm-trace-sink.js +2 -24
  179. package/dist/harness/llm-trace-sink.js.map +1 -1
  180. package/dist/harness/prompts.d.ts +2 -2
  181. package/dist/harness/prompts.js +8 -324
  182. package/dist/harness/prompts.js.map +1 -1
  183. package/dist/harness/result-types.d.ts +6 -5
  184. package/dist/harness/result-types.js +2 -0
  185. package/dist/harness/result-types.js.map +1 -1
  186. package/dist/harness/runtime.d.ts +22 -5
  187. package/dist/harness/runtime.js +10 -2313
  188. package/dist/harness/runtime.js.map +1 -1
  189. package/dist/harness/types-public.d.ts +3 -2
  190. package/dist/harness/types-public.js +16 -2954
  191. package/dist/harness/types-public.js.map +1 -1
  192. package/dist/harness/validator-trace-sink.d.ts +3 -2
  193. package/dist/harness/validator-trace-sink.js +2 -26
  194. package/dist/harness/validator-trace-sink.js.map +1 -1
  195. package/dist/hash.js +2 -39
  196. package/dist/hash.js.map +1 -1
  197. package/dist/hashline-5OKREIRM.js +4 -0
  198. package/dist/hashline-5OKREIRM.js.map +1 -0
  199. package/dist/index.d.ts +50 -11
  200. package/dist/index.js +57 -22015
  201. package/dist/index.js.map +1 -1
  202. package/dist/llm-evaluator-PN3WFCS4.js +653 -0
  203. package/dist/llm-evaluator-PN3WFCS4.js.map +1 -0
  204. package/dist/magic-string.es-2NZTC4GZ.js +1307 -0
  205. package/dist/magic-string.es-2NZTC4GZ.js.map +1 -0
  206. package/dist/patch.d.ts +3 -2
  207. package/dist/patch.js +2 -56
  208. package/dist/patch.js.map +1 -1
  209. package/dist/policy-VCYKGSAC.js +5 -0
  210. package/dist/policy-VCYKGSAC.js.map +1 -0
  211. package/dist/policy.js +2 -35
  212. package/dist/policy.js.map +1 -1
  213. package/dist/primitive-index-2OF6F4TZ.js +131 -0
  214. package/dist/primitive-index-2OF6F4TZ.js.map +1 -0
  215. package/dist/primitive-slice-WTMBLYFJ.js +235 -0
  216. package/dist/primitive-slice-WTMBLYFJ.js.map +1 -0
  217. package/dist/{prompts-BhNUuRoZ.d.ts → prompts-CLZGywMP.d.ts} +1 -1
  218. package/dist/provider-adapter-contract.js +10407 -14204
  219. package/dist/provider-adapter-contract.js.map +1 -1
  220. package/dist/provider-adapter.js +2 -44
  221. package/dist/provider-adapter.js.map +1 -1
  222. package/dist/providers/index.d.ts +89 -1
  223. package/dist/providers/index.js +115 -44
  224. package/dist/providers/index.js.map +1 -1
  225. package/dist/raw-C6KBH5I3.js +141 -0
  226. package/dist/raw-C6KBH5I3.js.map +1 -0
  227. package/dist/raw-FXSBXQTZ.js +7 -0
  228. package/dist/raw-FXSBXQTZ.js.map +1 -0
  229. package/dist/raw-MURDUPGK.js +8 -0
  230. package/dist/raw-MURDUPGK.js.map +1 -0
  231. package/dist/raw-T3GW3UVX.js +8 -0
  232. package/dist/raw-T3GW3UVX.js.map +1 -0
  233. package/dist/render-check-host-ZNIS6BJ5.js +5 -0
  234. package/dist/render-check-host-ZNIS6BJ5.js.map +1 -0
  235. package/dist/sdk-4JNSDNSR.js +6 -0
  236. package/dist/sdk-4JNSDNSR.js.map +1 -0
  237. package/dist/sdk-DIVJMHCX.js +7 -0
  238. package/dist/sdk-DIVJMHCX.js.map +1 -0
  239. package/dist/sdk-QRJOCRTS.js +7 -0
  240. package/dist/sdk-QRJOCRTS.js.map +1 -0
  241. package/dist/tag-balance-CTHCTRJ7.js +123 -0
  242. package/dist/tag-balance-CTHCTRJ7.js.map +1 -0
  243. package/dist/tools/get-primitives-ts.d.ts +1 -1
  244. package/dist/tools/get-primitives-ts.js +3 -1
  245. package/dist/tools/get-primitives-ts.js.map +1 -1
  246. package/dist/tools/render-check-worker.js +3 -40
  247. package/dist/tools/render-check-worker.js.map +1 -1
  248. package/dist/{types-public-h8IMnYuh.d.ts → types-public-hYlrerZh.d.ts} +35 -2
  249. package/dist/validation/index.d.ts +2 -2
  250. package/dist/validation/index.js +3 -498
  251. package/dist/validation/index.js.map +1 -1
  252. package/dist/{visual-evaluator-C2strxqD.d.ts → visual-evaluator-KskajxD5.d.ts} +14 -4
  253. package/dist/visual-evaluator-TGEXYQTP.js +12 -0
  254. package/dist/visual-evaluator-TGEXYQTP.js.map +1 -0
  255. package/dist/workflows.d.ts +3 -2
  256. package/dist/workflows.js +2 -151
  257. package/dist/workflows.js.map +1 -1
  258. package/package.json +20 -16
  259. package/src/adapters/claude/sdk.ts +4 -2
  260. package/src/adapters/claude/tool-bridge.ts +2 -1
  261. package/src/adapters/generation-dispatch.ts +9 -0
  262. package/src/adapters/openai/raw.ts +4 -0
  263. package/src/adapters/openai/sdk.ts +6 -1
  264. package/src/adapters/openai/tokens.ts +21 -7
  265. package/src/adapters/tool-bridge.ts +1 -1
  266. package/src/adapters/tools.ts +1 -1
  267. package/src/advanced/feedback.ts +1 -2
  268. package/src/advanced/generator.ts +4 -3
  269. package/src/boilerplate/free-design-prompt.ts +7 -0
  270. package/src/boilerplate/generate.ts +18 -5
  271. package/src/boilerplate/hard-sections.ts +8 -3
  272. package/src/boilerplate/react-hooks.ts +56 -0
  273. package/src/boilerplate/system-prompt.ts +12 -3
  274. package/src/check/run-tier0.ts +233 -8
  275. package/src/check/type-checker.ts +128 -16
  276. package/src/coding-agent/tools.ts +26 -3
  277. package/src/design-mode.ts +4 -9
  278. package/src/evaluation/axis-checks/checks/state-merge.ts +2 -4
  279. package/src/evaluation/axis-checks/checks/state-payload.ts +1 -28
  280. package/src/evaluation/axis-checks/checks/tint.ts +197 -0
  281. package/src/evaluation/axis-checks/helpers.ts +121 -0
  282. package/src/evaluation/axis-checks/registry.ts +2 -0
  283. package/src/evaluation/criteria/__fixtures__/edge-v2-draw2.json +4629 -0
  284. package/src/evaluation/criteria/bank.ts +1 -1
  285. package/src/evaluation/criteria/edge-instruments.ts +14 -0
  286. package/src/evaluation/criteria/edge-probe-v2.ts +352 -0
  287. package/src/evaluation/criteria/edge-v2.ts +242 -0
  288. package/src/evaluation/criteria/resolve.ts +24 -5
  289. package/src/evaluation/index.ts +3 -5
  290. package/src/evaluation/mcp-server.ts +0 -50
  291. package/src/evaluation/types-public.ts +6 -1
  292. package/src/evaluation/visual-evaluator.ts +161 -30
  293. package/src/harness/check/runtime-render/index.ts +28 -4
  294. package/src/harness/check/runtime-render/render-check.ts +20 -21
  295. package/src/harness/claude-agent-sdk-loader.ts +93 -0
  296. package/src/harness/claude-code-login-query.ts +1 -1
  297. package/src/harness/coding/generate-task-runner.ts +1 -0
  298. package/src/harness/coding/run-coding-turn.ts +3 -0
  299. package/src/harness/coding/run-eval-round.ts +9 -0
  300. package/src/harness/llm-router.ts +50 -2
  301. package/src/harness/runtime.ts +17 -0
  302. package/src/index.ts +9 -0
  303. package/src/providers/anthropic-tool-call.ts +263 -0
  304. package/src/providers/index.ts +13 -0
  305. package/src/tools/get-primitives-ts.ts +1 -1
  306. package/src/tools/render-check.ts +4 -4
  307. package/src/validation/primitives.ts +2 -1
  308. package/src/evaluation/loop.ts +0 -218
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/run-workflow.ts","../src/run-check.ts","../src/run-harness.ts","../src/tools.ts","../src/harness-tool-names.ts","../src/create-harness.ts"],"names":["result","endedAt"],"mappings":";;;;;;;;;;;;;AAiEA,IAAM,iBAAA,GAAuC,OAAO,IAAA,KAAS,IAAA,CAAK,EAAA;AAOlE,eAAsB,YAAY,KAAA,EAAqD;AACrF,EAAA,MAAM,EAAE,OAAA,EAAS,MAAA,EAAQ,UAAU,WAAA,EAAa,aAAA,EAAe,gBAAe,GAAI,KAAA;AAClF,EAAA,MAAM,QAAA,GAAqB,QAAQ,OAAA,CAAQ,QAAA;AAE3C,EAAA,MAAM,UAAA,GAAa,KAAK,GAAA,EAAI;AAC5B,EAAA,MAAM,YAAA,GAA0C,EAAE,GAAI,cAAA,IAAkB,EAAC,EAAG;AAC5E,EAAA,MAAM,eAAiC,EAAC;AACxC,EAAA,MAAM,OAAA,GAAU,eAAe,EAAC;AAChC,EAAA,MAAM,WAAW,aAAA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AA,EAAU,GAAG,CAAA,GACjC,EAAE,GAAG,QAAA,EAAU,GAAI,mBAAA,IAAuB,EAAC,EAAG;AACpD,MAAA,IAAI,YAAA,CAAa,WAAA,IAAe,YAAA,CAAa,WAAA,CAAY,SAAS,CAAA,EAAG;AACnE,QAAA,OAAO,EAAE,GAAG,YAAA,EAAc,WAAA,EAAa,aAAa,WAAA,EAAY;AAAA,MAClE;AACA,MAAA,OAAO,YAAA;AAAA,IACT,CAAA;AACA,IAAA,eAAA,GAAkB,EAAE,GAAG,eAAA,EAAiB,IAAA,EAAM,WAAA,EAAY;AAAA,EAC5D;AAEA,EAAA,OAAO,aAAA,CAAc;AAAA,IACnB,GAAG,aAAA;AAAA,IACH,cAAA,EAAgB,QAAA,CAAS,cAAA,IAAkB,IAAA,CAAK,cAAA;AAAA,IAChD,SAAA,EAAW;AAAA,GACZ,CAAA;AACH","file":"chunk-WEOXFEVE.js","sourcesContent":["// packages/ui-gen/src/run-workflow.ts\n//\n// Workflow executor. Runs phases sequentially; within a phase, tasks run in\n// parallel (Promise.all). Each task produces a named output that downstream\n// tasks can read from context.priorResults.\n//\n// Generic DAG executor — zero LLM coupling, zero environment/profile\n// gating. Re-exported via `@ggui-ai/ui-gen/harness` alongside the\n// Harness type vocabulary.\n//\n// Scope:\n// - Generic execution machinery — drives the DAG, doesn't know how to\n// run individual tasks. Task handlers are pluggable via the taskRunners\n// parameter, keyed by task.id (or a fallback).\n// - Single-pass / staged / staged-concurrent all work under one executor.\n// - No LLM coupling here — that belongs to the specific task runners the\n// caller registers.\n//\n// Failure semantics:\n// - If any task in a phase throws, the phase is aborted and the error\n// propagates out of runWorkflow. The caller owns the retry policy.\n// - If any task returns { error }, the phase completes but the workflow\n// result carries the error; the caller decides whether to continue.\n\nimport type { DataContract, JsonValue } from \"@ggui-ai/protocol\";\nimport type { Harness, Task, TaskContext, Workflow } from \"./harness/types-public.js\";\n\n/** Called by the executor to run a single task. One of these per task.id. */\nexport type TaskRunner = (task: Task, ctx: TaskContext) => Promise<JsonValue>;\n\n/** Fallback runner used when no task-specific runner is registered. */\nexport type DefaultTaskRunner = (task: Task, ctx: TaskContext) => Promise<JsonValue>;\n\nexport interface RunWorkflowInput {\n readonly harness: Harness;\n readonly prompt: string;\n readonly contract: DataContract;\n /** Task runners by task.id. Fallback to defaultRunner for unregistered ids. */\n readonly taskRunners?: Readonly<Record<string, TaskRunner>>;\n /** Runner invoked when no task.id-specific runner is registered. */\n readonly defaultRunner?: DefaultTaskRunner;\n /** Initial context (rarely used — mostly for resume/recovery). */\n readonly initialResults?: Readonly<Record<string, JsonValue>>;\n}\n\nexport interface PhaseRunResult {\n readonly phaseId: string;\n readonly taskResults: ReadonlyArray<{\n readonly taskId: string;\n readonly outputName: string;\n readonly output: JsonValue;\n readonly durationMs: number;\n }>;\n readonly durationMs: number;\n}\n\nexport interface WorkflowRunResult {\n readonly workflowId: string;\n readonly phases: readonly PhaseRunResult[];\n /** Final merged results map — task outputs keyed by outputName. */\n readonly results: Readonly<Record<string, JsonValue>>;\n readonly durationMs: number;\n}\n\n/** No-op default runner — returns the task id as its output. Tests can swap. */\nconst noopDefaultRunner: DefaultTaskRunner = async (task) => task.id;\n\n/**\n * Execute a workflow. Phases run sequentially; tasks within a phase run in\n * parallel via Promise.all. Task outputs accumulate into priorResults and\n * are passed to subsequent phases via the TaskContext.\n */\nexport async function runWorkflow(input: RunWorkflowInput): Promise<WorkflowRunResult> {\n const { harness, prompt, contract, taskRunners, defaultRunner, initialResults } = input;\n const workflow: Workflow = harness.process.workflow;\n\n const startTotal = Date.now();\n const priorResults: Record<string, JsonValue> = { ...(initialResults ?? {}) };\n const phaseResults: PhaseRunResult[] = [];\n const runners = taskRunners ?? {};\n const fallback = defaultRunner ?? noopDefaultRunner;\n\n for (const phase of workflow.phases) {\n const phaseStart = Date.now();\n\n const ctx: TaskContext = {\n harness,\n priorResults: { ...priorResults },\n classification: harness.classification,\n prompt,\n contract,\n };\n\n const taskPromises = phase.tasks.map(async (task) => {\n const taskStart = Date.now();\n const runner = runners[task.id] ?? fallback;\n const output = await runner(task, ctx);\n return {\n taskId: task.id,\n outputName: task.outputName,\n output,\n durationMs: Date.now() - taskStart,\n };\n });\n\n const taskResults = await Promise.all(taskPromises);\n\n // Merge outputs into priorResults for the next phase.\n for (const tr of taskResults) {\n priorResults[tr.outputName] = tr.output;\n }\n\n phaseResults.push({\n phaseId: phase.id,\n taskResults,\n durationMs: Date.now() - phaseStart,\n });\n }\n\n return {\n workflowId: workflow.id,\n phases: phaseResults,\n results: { ...priorResults },\n durationMs: Date.now() - startTotal,\n };\n}\n","// packages/ui-gen/src/run-check.ts\n//\n// Post-workflow evaluation stage. Runs every check registered on a harness's\n// CheckLeg against produced source and returns a flat issue list.\n//\n// Pure orchestration — iterates the harness's CheckLeg and runs each\n// check. Check BODIES (axis-check registry entries, tier-0 checks, LLM\n// evaluator, runtime-render adapter) are injected at harness\n// construction.\n//\n// Scope:\n// - Runs axisChecks (already-filtered at createHarness time).\n// - Runs tierChecks (deterministic, no LLM).\n// - Delegates LLM evaluation to harness.check.llmEvaluator when present.\n// - Delegates runtime-render to harness.check.runtimeRender when present.\n\nimport type { DataContract, JsonObject } from \"@ggui-ai/protocol\";\nimport type { EvalIssue, AxisCheckInput } from \"./evaluation/types-public.js\";\nimport type { CheckLeg, Harness } from \"./harness/types-public.js\";\nimport {\n emitValidatorTraceEvent,\n newValidatorTraceId,\n truncateSourceForTrace,\n} from \"./harness/validator-trace-sink.js\";\nimport { runGatedAxisChecks, traceAxisChecksSkipped } from \"./evaluation/axis-checks/dispatch.js\";\n\nexport interface RunCheckInput {\n readonly sourceCode: string;\n readonly compiledCode: string | null;\n readonly contract?: DataContract;\n readonly prompt: string;\n readonly harness: Harness;\n /**\n * Optional fixture props (e.g., from a benchmark commit's `props` field).\n * Forwarded to runtimeRender for schema-first mockup synthesis.\n */\n readonly fixtureProps?: JsonObject;\n /**\n * When true, skip the runtime-render probe even if the harness has one.\n * Used by the eval-round runner to keep the probe (~500ms-2s) off the\n * per-turn hot path; the runner runs the probe ONCE at exit-decision\n * time via `harness.check.runtimeRender.run` directly.\n */\n readonly skipRuntimeRender?: boolean;\n}\n\nexport interface CheckResult {\n readonly issues: readonly EvalIssue[];\n readonly axisIssueCount: number;\n readonly tierIssueCount: number;\n readonly llmIssueCount: number;\n readonly runtimeRenderIssueCount: number;\n readonly firedCheckIds: readonly string[];\n}\n\n/**\n * Run every check on a CheckLeg against produced source. Returns all issues\n * with per-source counts for telemetry.\n *\n * Pre-filtering invariant: `check.axisChecks` already only contains checks\n * whose `matches()` gate passed at createHarness time, so this function\n * does no re-matching — it just iterates and runs.\n */\nexport async function runCheck(input: RunCheckInput): Promise<CheckResult> {\n const { harness, sourceCode, compiledCode, contract, prompt } = input;\n const check: CheckLeg = harness.check;\n const startedAt = Date.now();\n\n if (compiledCode === null) {\n traceAxisChecksSkipped(\n { sourceCode, contract, originalPrompt: prompt, classification: harness.classification, designMode: harness.designMode },\n \"compiledCode null — no check ran\",\n );\n const result: CheckResult = {\n issues: [],\n axisIssueCount: 0,\n tierIssueCount: 0,\n llmIssueCount: 0,\n runtimeRenderIssueCount: 0,\n firedCheckIds: [],\n };\n // Emit a trace event even for the no-compile short-circuit so the\n // devtools UI sees the call ran (and can show \"compile failed →\n // checks skipped\").\n const endedAt = Date.now();\n emitValidatorTraceEvent({\n id: newValidatorTraceId(),\n at: startedAt,\n endedAt,\n durationMs: endedAt - startedAt,\n harnessId: harness.id,\n classification: harness.classification,\n workflowId: harness.process.workflow.id,\n hadCompiledCode: false,\n skippedRuntimeRender: input.skipRuntimeRender ?? false,\n summary: {\n totalIssues: 0,\n axisIssues: 0,\n tierIssues: 0,\n llmIssues: 0,\n runtimeRenderIssues: 0,\n firedCheckIds: [],\n },\n issues: [],\n sourceCode: truncateSourceForTrace(sourceCode),\n prompt,\n });\n return result;\n }\n\n const issues: EvalIssue[] = [];\n const firedIds: string[] = [];\n\n // ── Axis checks (deterministic, pre-gated on harness) ─────────────────\n const axisInput: AxisCheckInput = {\n sourceCode,\n compiledCode,\n contract: contract,\n originalPrompt: prompt,\n classification: harness.classification,\n designMode: harness.designMode,\n // ggui#1117: the canvas the harness was built for, when it has one — never a default.\n ...(harness.canvas !== undefined ? { canvas: harness.canvas } : {}),\n // ggui#1285: the props the probe and judge rendered with — the fixture-echo check reads them.\n ...(input.fixtureProps !== undefined ? { fixtureProps: input.fixtureProps } : {}),\n };\n // The one runner `runAxisChecks` shares (ggui#1046 trace prints here, on the served path).\n const axisRun = runGatedAxisChecks(check.axisChecks, axisInput);\n issues.push(...axisRun.issues);\n firedIds.push(...axisRun.firedIds);\n const axisIssueCount = axisRun.issues.length;\n\n // ── Tier checks (deterministic, harness-owned) ────────────────────────\n let tierIssueCount = 0;\n for (const tierCheck of check.tierChecks) {\n firedIds.push(tierCheck.id);\n const tierIssues = await tierCheck.run({ sourceCode, compiledCode });\n issues.push(...tierIssues);\n tierIssueCount += tierIssues.length;\n }\n\n // ── Runtime render check (deterministic, ~50-1000ms warm/cold) ────────\n // 2026-04-27: probe runs ONLY when prior cheap checks (axis + tier)\n // produced no tier-0 failures. Rationale: probe is the \"does this\n // actually work at runtime\" gate — wasting ~50-1000ms probing a\n // component the deterministic checks already rejected adds latency\n // with no signal (the LLM is going to fix self-check first anyway,\n // and probe issues on broken-self-check code are noise, not\n // actionable feedback).\n //\n // When axis/tier are clean and probe finds wiring bugs (action not\n // wired, useStream subscribed but never read, prop never rendered),\n // those issues feed back through the same `issues` channel as\n // self-check failures — coding agent gets one more turn with the\n // probe diagnostic. Goal: 0 probe failures on success path.\n let runtimeRenderIssueCount = 0;\n if (check.runtimeRender && !input.skipRuntimeRender) {\n const cheapTier0Failures = issues.filter(\n i => i.result === \"fail\" && (i.tier === 0 || i.tier === undefined),\n ).length;\n if (cheapTier0Failures === 0) {\n const outcome = await check.runtimeRender.run({\n sourceCode,\n compiledCode,\n contract,\n fixtureProps: input.fixtureProps,\n });\n // Only a probe that actually executed counts as a fired check —\n // an infra-skipped / not-applicable outcome carries no evidence\n // and must not appear in `firedCheckIds` as if it gated anything.\n if (outcome.status === \"ran\") {\n firedIds.push(check.runtimeRender.id);\n issues.push(...outcome.issues);\n runtimeRenderIssueCount = outcome.issues.length;\n }\n }\n }\n\n // ── LLM evaluator (optional, async) ───────────────────────────────────\n let llmIssueCount = 0;\n if (check.llmEvaluator && contract) {\n firedIds.push(check.llmEvaluator.id);\n const llmIssues = await check.llmEvaluator.run({\n sourceCode,\n compiledCode,\n contract,\n prompt,\n });\n issues.push(...llmIssues);\n llmIssueCount = llmIssues.length;\n }\n\n const result: CheckResult = {\n issues,\n axisIssueCount,\n tierIssueCount,\n llmIssueCount,\n runtimeRenderIssueCount,\n firedCheckIds: firedIds,\n };\n\n // Emit one validator-trace event capturing the full per-tier\n // breakdown. Devtools-only — no-op when no sink registered (see\n // validator-trace-sink.ts).\n const endedAt = Date.now();\n emitValidatorTraceEvent({\n id: newValidatorTraceId(),\n at: startedAt,\n endedAt,\n durationMs: endedAt - startedAt,\n harnessId: harness.id,\n classification: harness.classification,\n workflowId: harness.process.workflow.id,\n hadCompiledCode: true,\n skippedRuntimeRender: input.skipRuntimeRender ?? false,\n summary: {\n totalIssues: issues.length,\n axisIssues: axisIssueCount,\n tierIssues: tierIssueCount,\n llmIssues: llmIssueCount,\n runtimeRenderIssues: runtimeRenderIssueCount,\n firedCheckIds: firedIds,\n },\n issues,\n sourceCode: truncateSourceForTrace(sourceCode),\n prompt,\n });\n\n return result;\n}\n","// packages/ui-gen/src/run-harness.ts\n//\n// End-to-end orchestration: run a harness's workflow to produce source,\n// then run the check leg on the result. Owns retry policy (derive new\n// harness + re-run on failure, up to harness.process.retry.maxIterations).\n//\n// Combines runWorkflow + runCheck + the derive loop — the top of the\n// orchestration spine. Re-exported via `@ggui-ai/ui-gen/harness`\n// alongside runWorkflow + runCheck.\n//\n// Shape:\n// for iteration in 1..maxIterations:\n// workflowResult = await runWorkflow(harness, ctx, taskRunners)\n// source = workflowResult.results.source\n// if !source: return { ok: false, reason: \"no source produced\" }\n// checkResult = await runCheck(harness, source)\n// if passingThreshold(checkResult): return { ok: true, source, ... }\n// harness = harness.derive(decideRevision(harness, checkResult))\n\nimport type { DataContract } from \"@ggui-ai/protocol\";\nimport type { Harness } from \"./harness/types-public.js\";\nimport { runWorkflow, type TaskRunner, type WorkflowRunResult } from \"./run-workflow.js\";\nimport { runCheck, type CheckResult } from \"./run-check.js\";\n\nexport interface RunHarnessInput {\n readonly harness: Harness;\n readonly prompt: string;\n readonly contract: DataContract;\n readonly taskRunners: Readonly<Record<string, TaskRunner>>;\n readonly compile?: (source: string) => Promise<string | null>;\n readonly passes?: (result: CheckResult) => boolean;\n readonly maxIterations?: number;\n /**\n * Skip runCheck() entirely — for callers that have already evaluated\n * the source themselves and don't want the duplicate work. When true,\n * the iteration record's checkResult is empty and `passes` is not\n * consulted; the iteration is treated as passed unconditionally.\n *\n * Used by dispatchGeneration during the runHarness migration: the\n * closure-based generate runner does its own multi-round eval inside\n * the workflow, so re-running runCheck here would re-fire LLM + visual\n * eval needlessly (~5s wasted per generation).\n */\n readonly skipCheck?: boolean;\n}\n\nexport type RunHarnessReason =\n | \"passed\"\n | \"no-source\"\n | \"compile-failed\"\n | \"max-iterations\";\n\nexport interface IterationRecord {\n readonly iteration: number;\n readonly harnessId: string;\n readonly workflowId: string;\n readonly source: string | null;\n readonly compiled: string | null;\n readonly workflowDurationMs: number;\n readonly checkDurationMs: number;\n readonly issueCount: number;\n readonly firedCheckIds: readonly string[];\n}\n\nexport interface RunHarnessResult {\n readonly ok: boolean;\n readonly reason: RunHarnessReason;\n readonly finalHarness: Harness;\n readonly finalSource: string | null;\n readonly finalCompiled: string | null;\n readonly finalCheck: CheckResult | null;\n readonly iterations: readonly IterationRecord[];\n readonly durationMs: number;\n}\n\nconst defaultPasses = (r: CheckResult): boolean =>\n r.issues.every((i) => i.result !== \"fail\");\n\n/**\n * Run harness end-to-end: workflow → compile → check → derive-on-fail.\n *\n * Caller must supply taskRunners — at minimum, a runner for each task in\n * the workflow's phases. The `generate` task (single_pass) should return\n * the produced source as a string.\n */\nexport async function runHarness(input: RunHarnessInput): Promise<RunHarnessResult> {\n const {\n harness: initialHarness,\n prompt,\n contract,\n taskRunners,\n compile,\n passes = defaultPasses,\n maxIterations: explicitMax,\n skipCheck = false,\n } = input;\n\n const maxIterations = explicitMax ?? initialHarness.process.retry.maxIterations;\n const start = Date.now();\n const iterations: IterationRecord[] = [];\n\n let harness = initialHarness;\n let lastSource: string | null = null;\n let lastCompiled: string | null = null;\n let lastCheck: CheckResult | null = null;\n\n for (let i = 1; i <= maxIterations; i++) {\n const workflowResult: WorkflowRunResult = await runWorkflow({\n harness,\n prompt,\n contract,\n taskRunners,\n });\n\n const source = (workflowResult.results.source ?? null) as string | null;\n let compiled: string | null = null;\n if (source && compile) {\n compiled = await compile(source);\n } else if (source && !compile) {\n compiled = source;\n }\n\n // Compile failure is a hard fail. We must NOT fall through to runCheck()\n // — its compile-null branch returns an empty issue set, which the default\n // pass predicate would happily accept as \"no failures = passed\". Bail out\n // explicitly so the iteration record reflects the actual failure mode.\n const compileFailed = source !== null && compile !== undefined && compiled === null;\n\n const checkStart = Date.now();\n const checkResult = source && !compileFailed && !skipCheck\n ? await runCheck({ harness, sourceCode: source, compiledCode: compiled, contract, prompt })\n : { issues: [], axisIssueCount: 0, tierIssueCount: 0, llmIssueCount: 0, runtimeRenderIssueCount: 0, firedCheckIds: [] };\n const checkDurationMs = Date.now() - checkStart;\n\n iterations.push({\n iteration: i,\n harnessId: harness.id,\n workflowId: harness.process.workflow.id,\n source,\n compiled,\n workflowDurationMs: workflowResult.durationMs,\n checkDurationMs,\n issueCount: checkResult.issues.length,\n firedCheckIds: checkResult.firedCheckIds,\n });\n\n lastSource = source;\n lastCompiled = compiled;\n lastCheck = checkResult;\n\n if (!source) {\n return buildResult({\n ok: false,\n reason: \"no-source\",\n finalHarness: harness,\n finalSource: null,\n finalCompiled: null,\n finalCheck: checkResult,\n iterations,\n start,\n });\n }\n\n if (compileFailed) {\n // Don't keep iterating on a compile failure unless the harness has a\n // derive policy that would change codegen — for now, treat it as a\n // terminal signal, the same way no-source is terminal. A future PR can\n // make this iteration-aware once derive policies exist that target it.\n return buildResult({\n ok: false,\n reason: \"compile-failed\",\n finalHarness: harness,\n finalSource: source,\n finalCompiled: null,\n finalCheck: checkResult,\n iterations,\n start,\n });\n }\n\n if (passes(checkResult)) {\n return buildResult({\n ok: true,\n reason: \"passed\",\n finalHarness: harness,\n finalSource: source,\n finalCompiled: compiled,\n finalCheck: checkResult,\n iterations,\n start,\n });\n }\n\n if (i < maxIterations) {\n // Default revision: re-run same harness. Real deriders (planner,\n // runtime fallback, classification swap) plug in via harness.process.retry\n // or an explicit revision function (future API).\n harness = harness.derive({});\n }\n }\n\n return buildResult({\n ok: false,\n reason: \"max-iterations\",\n finalHarness: harness,\n finalSource: lastSource,\n finalCompiled: lastCompiled,\n finalCheck: lastCheck,\n iterations,\n start,\n });\n}\n\nfunction buildResult(args: {\n ok: boolean;\n reason: RunHarnessReason;\n finalHarness: Harness;\n finalSource: string | null;\n finalCompiled: string | null;\n finalCheck: CheckResult | null;\n iterations: IterationRecord[];\n start: number;\n}): RunHarnessResult {\n return {\n ok: args.ok,\n reason: args.reason,\n finalHarness: args.finalHarness,\n finalSource: args.finalSource,\n finalCompiled: args.finalCompiled,\n finalCheck: args.finalCheck,\n iterations: args.iterations,\n durationMs: Date.now() - args.start,\n };\n}\n","// packages/ui-gen/src/tools.ts\n//\n// LLM tool grammars used by the generation stage. Primary tool =\n// `apply_changes` (multi-range patch). Scoped fallback =\n// `apply_changes` with `maxItems=1` for transport-error recovery\n// (malformed_tool_call retries). Plus:\n// - hashline variants (`APPLY_CHANGES_HASHLINE_TOOL[_FLAT]`) used\n// when the `hashline: \"v2\"` policy profile selects them;\n// - flat-code variant (`APPLY_CHANGES_TOOL_FLAT`) — the shipped\n// default;\n// - helper tools (`GET_ICONS_TOOL`, `GET_COMPONENTS_INFO_TOOL`,\n// `WRITE_PLAN_TOOL`, `REWRITE_TOOL`) wired into the\n// `selectTurnTools` path.\n//\n// Harness `what.codingTools` can override with any subset; alternate\n// patch grammars swap in by replacing the tool list + a matching\n// `applyPatch` implementation.\n//\n// The tool definitions in this file are static JSON schemas + prompt\n// text. The decision logic (which profile picks which tool,\n// model-registry overrides, environment gating) lives in\n// `./harness/policy.ts` + `run-coding-turn.ts::selectTurnTools` —\n// nothing in this file reads a profile or an env var; these are data.\n\nimport type { LLMToolDef } from \"./llm.js\";\nexport type { LLMToolDef };\n\n/** Standard multi-range patch tool — surgical edits. */\nexport const APPLY_CHANGES_TOOL: LLMToolDef = {\n name: \"apply_changes\",\n description:\n \"Surgical edit: replace line ranges in ui.tsx with new code. Use line numbers from the Current File (shown as N│). Preferred for targeted changes — fixing one hook, renaming a prop, swapping a component, closing a missing tag. The patch is ALWAYS applied to the workspace even if the resulting file has syntax errors — the error location is returned as guidance so you can iterate. If the file is in a tangled state and patches aren't converging cleanly, use `write` to rewrite from scratch.\",\n parameters: {\n type: \"object\",\n properties: {\n changes: {\n type: \"array\",\n description:\n \"Array of changes. Each replaces lines startLine through endLine (inclusive) with the new code lines. Applied bottom-to-top to preserve line numbers.\",\n items: {\n type: \"object\",\n properties: {\n startLine: {\n type: \"number\",\n description: \"First line to replace (from the N│ numbers in Current File)\",\n },\n endLine: { type: \"number\", description: \"Last line to replace (inclusive)\" },\n code: {\n type: \"array\",\n items: { type: \"string\" },\n description:\n \"New code lines. One source line per array element. Avoid embedding newlines inside an element. For long JSX blocks, split at statement boundaries across multiple changes.\",\n },\n description: { type: \"string\", description: \"What this change does (< 10 words)\" },\n },\n required: [\"startLine\", \"endLine\", \"code\", \"description\"],\n },\n },\n commit_message: { type: \"string\", description: \"Short summary of all changes\" },\n allowBroken: {\n type: \"boolean\",\n description:\n \"Opt-in: commit the patch even if the resulting file fails syntax preflight. Use when you want to iterate across multiple turns and accept a broken intermediate state (e.g., split a big JSX refactor into 2 patches). Default false (strict preflight).\",\n },\n },\n required: [\"changes\", \"commit_message\"],\n },\n};\n\n/**\n * Scoped fallback variant for transport-error retries. Used by the LLM\n * router when `malformed_tool_call` exhausts the standard retry budget —\n * forces a single small change (≤20 lines) so the payload fits within the\n * provider's JSON-emission ceiling. Universal signal; only Gemini hits this\n * path today, but the handler is not provider-gated.\n */\nexport const APPLY_CHANGES_TOOL_SCOPED: LLMToolDef = {\n name: \"apply_changes\",\n description:\n \"Replace ONE small line range in ui.tsx. Narrow schema for transport-error recovery: emit a single change covering at most 20 lines.\",\n parameters: {\n type: \"object\",\n properties: {\n changes: {\n type: \"array\",\n minItems: 1,\n maxItems: 1,\n description: \"Single change. endLine - startLine ≤ 20.\",\n items: {\n type: \"object\",\n properties: {\n startLine: { type: \"number\", description: \"First line to replace\" },\n endLine: {\n type: \"number\",\n description: \"Last line (inclusive). Keep endLine - startLine ≤ 20.\",\n },\n code: {\n type: \"array\",\n items: { type: \"string\" },\n description:\n \"New code lines (one source line per element, no embedded newlines). ≤ 20 elements.\",\n },\n description: { type: \"string\", description: \"What this change does (< 10 words)\" },\n },\n required: [\"startLine\", \"endLine\", \"code\", \"description\"],\n },\n },\n commit_message: { type: \"string\", description: \"Short summary\" },\n },\n required: [\"changes\", \"commit_message\"],\n },\n};\n\n/** Hashline variant of APPLY_CHANGES_TOOL.\n * When the `hashline-v2` policy profile is active, this tool is\n * advertised in place of the standard numeric-line APPLY_CHANGES_TOOL.\n * The `startLine` and `endLine` fields are STRINGS in `\"N:hh\"` format\n * (e.g., `\"47:a3\"`) — where `hh` is the 2-char content hash shown in\n * the `## Current File` block. The handler validates the hash against\n * the current file; if it mismatches, the edit is rejected with\n * HASHLINE_STALE so the LLM re-reads before patching. */\nexport const APPLY_CHANGES_HASHLINE_TOOL: LLMToolDef = {\n name: \"apply_changes\",\n description:\n \"Surgical edit with line-hash verification. Replace line ranges in ui.tsx. Line refs use the format `N:hh` from the Current File block (e.g., `47:a3`) — the 2-char hash anchors your view so the edit is rejected if the file drifted under you. Always use the exact hashes shown in the latest Current File view. The patch is applied even if the resulting file has syntax errors (the error location is returned as guidance); but edits with mismatched hashes are rejected BEFORE apply.\",\n parameters: {\n type: \"object\",\n properties: {\n changes: {\n type: \"array\",\n description:\n \"Array of changes. Each replaces `startLine` through `endLine` (inclusive) with the new code lines. Line refs use the `N:hh` format.\",\n items: {\n type: \"object\",\n properties: {\n startLine: {\n type: \"string\",\n pattern: \"^\\\\d+:[0-9a-f]{2}$\",\n description:\n \"First line to replace, as `N:hh` (e.g., `47:a3`). The hash MUST match the line's hash in the latest Current File view. Format is line-number, colon, 2 lowercase hex chars — enforced by JSON schema pattern.\",\n },\n endLine: {\n type: \"string\",\n pattern: \"^\\\\d+:[0-9a-f]{2}$\",\n description:\n \"Last line to replace, as `N:hh` (e.g., `83:b1`). Hash MUST match. Format: line-number, colon, 2 lowercase hex chars.\",\n },\n code: {\n type: \"array\",\n items: { type: \"string\" },\n description:\n \"New code lines. One source line per array element. No embedded newlines.\",\n },\n description: { type: \"string\", description: \"What this change does (< 10 words)\" },\n },\n required: [\"startLine\", \"endLine\", \"code\", \"description\"],\n },\n },\n commit_message: { type: \"string\", description: \"Short summary of all changes\" },\n },\n required: [\"changes\", \"commit_message\"],\n },\n};\n\n/**\n * Flat-code variant of APPLY_CHANGES_TOOL.\n *\n * Identical to APPLY_CHANGES_TOOL except `code` is a single string with\n * `\\n`-separated lines instead of an array. One level of JSON nesting\n * shallower — a deeply-nested schema can trip some model decoders. The\n * handler in `coding-agent/tools.ts` accepts both shapes.\n */\nexport const APPLY_CHANGES_TOOL_FLAT: LLMToolDef = {\n name: \"apply_changes\",\n description:\n \"Surgical edit: replace line ranges in ui.tsx with new code. Use line numbers from the Current File (shown as N│). Preferred for targeted changes. The `code` field is a single string with newlines (`\\\\n`) between lines. The patch is ALWAYS applied even if the resulting file has syntax errors — the error is returned as guidance. For a full rewrite, use `rewrite`.\",\n parameters: {\n type: \"object\",\n properties: {\n changes: {\n type: \"array\",\n description:\n \"Array of changes. Each replaces lines startLine through endLine (inclusive). Applied bottom-to-top.\",\n items: {\n type: \"object\",\n properties: {\n startLine: {\n type: \"number\",\n description: \"First line to replace (from the N│ numbers in Current File)\",\n },\n endLine: { type: \"number\", description: \"Last line to replace (inclusive)\" },\n code: {\n type: \"string\",\n description:\n \"New code as a single string. Separate lines with `\\\\n`. Preserve leading indentation inside the string.\",\n },\n description: { type: \"string\", description: \"What this change does (< 10 words)\" },\n },\n required: [\"startLine\", \"endLine\", \"code\", \"description\"],\n },\n },\n commit_message: { type: \"string\", description: \"Short summary of all changes\" },\n allowBroken: {\n type: \"boolean\",\n description:\n \"Opt-in: commit the patch even if the resulting file fails syntax preflight.\",\n },\n },\n required: [\"changes\", \"commit_message\"],\n },\n};\n\n/**\n * Flat-code + hashline variant.\n * Combines `code: string` flatness with `N:hh` hash-verified line refs\n * from hashline-v2.\n */\nexport const APPLY_CHANGES_HASHLINE_TOOL_FLAT: LLMToolDef = {\n name: \"apply_changes\",\n description:\n \"Surgical edit with line-hash verification. Replace line ranges in ui.tsx using `N:hh` references from the Current File (e.g. `47:a3`). The `code` field is a single string with newlines between lines. Edits with mismatched hashes are rejected before apply.\",\n parameters: {\n type: \"object\",\n properties: {\n changes: {\n type: \"array\",\n description: \"Array of changes. Line refs use `N:hh` format.\",\n items: {\n type: \"object\",\n properties: {\n startLine: {\n type: \"string\",\n pattern: \"^\\\\d+:[0-9a-f]{2}$\",\n description:\n \"First line to replace, as `N:hh` (e.g., `47:a3`). Hash MUST match the latest Current File view. Format: line-number, colon, 2 lowercase hex chars.\",\n },\n endLine: {\n type: \"string\",\n pattern: \"^\\\\d+:[0-9a-f]{2}$\",\n description:\n \"Last line to replace, as `N:hh` (e.g., `83:b1`). Hash MUST match.\",\n },\n code: {\n type: \"string\",\n description:\n \"New code as a single string. Separate lines with `\\\\n`. Preserve leading indentation.\",\n },\n description: { type: \"string\", description: \"What this change does (< 10 words)\" },\n },\n required: [\"startLine\", \"endLine\", \"code\", \"description\"],\n },\n },\n commit_message: { type: \"string\", description: \"Short summary of all changes\" },\n },\n required: [\"changes\", \"commit_message\"],\n },\n};\n\n/**\n * What to do when the name you wanted is not in the icon list (ggui#1183): the\n * list is complete and constant, so a second call is the same exchange — and\n * three of those end the run (`SAME_EXCHANGE_BREAK_AT`). Said ONCE, on the\n * tool's description and appended to every result, because the model that\n * looped had never been told the list would not change.\n */\nexport const ICON_LIST_NO_MATCH_GUIDANCE =\n \"This list is complete and constant — calling again returns exactly it. If the name you wanted is not here, pick the nearest listed name (or a neutral one such as `circle`) and continue with apply_changes; never call this tool twice.\";\n/** Helper icon-lookup tool — not a patch grammar, attached to the same LLM turn. */\nexport const GET_ICONS_TOOL: LLMToolDef = {\n name: \"get_available_icons\",\n description:\n 'List every Lucide icon name the <Icon name=\"...\"> component renders (kebab-case). A name outside this list renders nothing — check before choosing. ' +\n ICON_LIST_NO_MATCH_GUIDANCE,\n parameters: { type: \"object\", properties: {} },\n};\n\n/**\n * Component-docs fetch tool (tool-driven primitive docs). Advertised\n * alongside `apply_changes` when `ContextPolicy.primitiveIndex` is\n * active (a compact name+description index replaces the full ~130KB\n * primitives doc in the system prompt; the LLM fetches the full\n * per-component API on demand).\n *\n * The handler lives in `coding-agent/tools.ts` under the\n * `get_components_info` case.\n */\nexport const GET_COMPONENTS_INFO_TOOL: LLMToolDef = {\n name: \"get_components_info\",\n description:\n \"Fetch full prop API + example + variant mappings for one or more design-system components. Use when the compact index doesn't give you enough detail to write correct JSX (e.g., you need to know the exact prop values for `variant` or the shape of an options array). Batch names in one call — cheaper than multiple fetches.\",\n parameters: {\n type: \"object\",\n properties: {\n names: {\n type: \"array\",\n items: { type: \"string\" },\n description:\n \"Component names to fetch (e.g., ['Card', 'Stack', 'Input']). Names must match the index entries exactly.\",\n },\n },\n required: [\"names\"],\n },\n};\n\n/**\n * Plan-commitment tool.\n *\n * Forced on turn 2 when the harness runs the `fetch → plan → write`\n * pipeline. After turn-1 fetching, the LLM must produce a short\n * structured plan before any apply_changes is allowed. The plan\n * echoes back in the tool result so turn 3+ patches can reference it —\n * this breaks fetch-loops where the model over-fetches without\n * committing to a structure.\n */\nexport const WRITE_PLAN_TOOL: LLMToolDef = {\n name: \"write_plan\",\n description:\n \"Commit to a concrete plan before writing code. Produce a short structured outline: which components you'll use, rough JSX structure, and wiring (state/actions/streams). After this call, on the next turn you'll be able to write code with `apply_changes`. Keep it brief — this is a commitment, not a design doc.\",\n parameters: {\n type: \"object\",\n properties: {\n components: {\n type: \"array\",\n items: { type: \"string\" },\n description:\n \"Primitive/component names you'll use in the final JSX (e.g., ['Card', 'Stack', 'Input', 'Button']).\",\n },\n structure: {\n type: \"string\",\n description:\n \"Brief JSX structure outline — a few lines of pseudocode showing nesting. Example: 'Card > Stack > [Heading, Input x3, Button].'\",\n },\n wiring: {\n type: \"string\",\n description:\n \"Brief note on state/actions/streams you'll wire. Example: 'useState for form payload; invokeAction(submit) on Button click.'\",\n },\n },\n required: [\"components\", \"structure\", \"wiring\"],\n },\n};\n\n/**\n * Full-file write tool. Flat JSON payload (two top-level strings) — much\n * easier for brittle tool-call serializers (e.g., Google Gemini Flash-Lite)\n * than `apply_changes`' nested array-of-objects-of-arrays-of-strings.\n *\n * Offered alongside `apply_changes` on turn 1 so the LLM can pick whichever\n * shape it emits more reliably. On patch-repair turns, `apply_changes` is\n * preferred (minimal diff, preserves session), but turn-1 has no existing\n * scaffold state to preserve — write is equivalent semantically.\n *\n * Implementation note: `executeTool` in `coding-agent/tools.ts`\n * already handles the `write` case; the harness just needs to\n * advertise it to the LLM.\n */\nexport const REWRITE_TOOL: LLMToolDef = {\n name: \"rewrite\",\n description:\n \"Escape hatch: rewrite the entire ui.tsx file in one call. Use only when surgical `apply_changes` patches have accumulated into a tangled broken state and you need to reset the file to a clean implementation. Single-string payload; auto-compiles + validates. Prefer `apply_changes` for normal edits.\",\n parameters: {\n type: \"object\",\n properties: {\n code: {\n type: \"string\",\n description: \"Complete TSX component source — the whole file.\",\n },\n commit_message: {\n type: \"string\",\n description: \"Short description (< 10 words)\",\n },\n },\n required: [\"code\", \"commit_message\"],\n },\n};\n","/**\n * The coding loop's tool set — the ONE list `createHarness` builds its\n * coding and scoped tools from, and the identity a build stamp names it\n * by.\n *\n * `harnessToolNames(mode)` returns one entry per tool definition,\n * `<name>@<digest>`: the tool's own (unprefixed) name and the first 8 hex\n * of sha256 over `JSON.stringify` of its definition — so a change to a\n * tool's schema OR its description (prompt text, as output-changing as a\n * template) moves the entry, and two definitions that share a name (a\n * scoped variant keeps the name and narrows the grammar) are two entries.\n * Coding and scoped alike, since the scoped set runs on the\n * duplicate-fingerprint escape; sorted, de-duplicated, a fresh array. It\n * reads the same constants the harness is assembled from, so the list can\n * never drift from what runs; the pin beside it holds the two equal for\n * every design mode. The design mode is part of the signature because the\n * tool set is keyed by the harness a mode builds, even while both modes\n * declare the same tools.\n */\nimport { createHash } from 'node:crypto';\nimport type { LLMToolDef } from './llm.js';\nimport type { DesignMode } from './design-mode.js';\nimport { APPLY_CHANGES_TOOL, APPLY_CHANGES_TOOL_SCOPED } from './tools.js';\n\n/** The coding tools every harness declares (`what.codingTools`). */\nexport const HARNESS_CODING_TOOLS: readonly LLMToolDef[] = [APPLY_CHANGES_TOOL];\n/** The scoped fallback the runtime promotes into `codingTools` on a duplicate-fingerprint escape. */\nexport const HARNESS_SCOPED_TOOLS: readonly LLMToolDef[] = [APPLY_CHANGES_TOOL_SCOPED];\n\n/** One tool's entry: `<name>@<first 8 hex of sha256(JSON.stringify(def))>`. */\nexport function harnessToolEntry(def: LLMToolDef): string {\n return `${def.name}@${createHash('sha256').update(JSON.stringify(def), 'utf8').digest('hex').slice(0, 8)}`;\n}\n\nexport function harnessToolNames(designMode: DesignMode): string[] {\n void designMode; // one tool set for every mode today; the mode keys the harness, so it stays on the signature\n return [...new Set([...HARNESS_CODING_TOOLS, ...HARNESS_SCOPED_TOOLS].map(harnessToolEntry))].sort();\n}\n","// packages/ui-gen/src/create-harness.ts\n//\n// Deterministic Harness factory — the skeleton constructor. Given a\n// classification + contract + prompt (+ optional caller-injected\n// defaults for policy / system-prompt builder / axis-checks /\n// runtime-render / overrides), assemble all four legs and return an\n// immutable Harness object ready to drive generation.\n//\n// This is a SKELETON: it has four injection seams (policy,\n// systemPromptBuilder, axisChecks, runtimeRender). The hosted runtime\n// supplies the production content for those seams from\n// `adapters/generation-dispatch.ts` at the dispatch boundary; callers\n// that omit them get minimal defaults.\n\nimport { hasProfile } from \"./boilerplate/styling-profile.js\";\nimport type { CacheTier } from \"./fragments/index.js\";\nimport { compose } from \"./compose.js\";\nimport { buildSystemPrompt, generateBoilerplate } from \"./boilerplate.js\";\nimport { HARNESS_CODING_TOOLS, HARNESS_SCOPED_TOOLS } from \"./harness-tool-names.js\";\nimport { defaultApplyPatch } from \"./patch.js\";\nimport { computeHarnessId, computeHarnessName, hashClassification } from \"./hash.js\";\nimport { pickWorkflow } from \"./workflows.js\";\nimport { DEFAULT_HARNESS_POLICY, isDefaultHarnessPolicy } from \"./policy.js\";\nimport { DEFAULT_DESIGN_MODE } from \"./design-mode.js\";\nimport type {\n CreateHarnessInput,\n Harness,\n HarnessConstructionContext,\n HarnessOverrides,\n HarnessRevision,\n HowLeg,\n WhatLeg,\n CheckLeg,\n ProcessLeg,\n HarnessMeta,\n PatchFn,\n SystemPromptBuilder,\n} from \"./harness/types-public.js\";\n\n// Version tags — bump when semantics change.\nconst HARNESS_VERSION = \"harness@1\";\nconst HOW_VERSION = \"how@1\";\nconst WHAT_VERSION = \"what@1\";\nconst CHECK_VERSION = \"check@1\";\nconst PROCESS_VERSION = \"process@1\";\n\n// Default patch function — pure line-range application (mirrors apply_changes).\n// Variants can override via HarnessOverrides.what.\nconst defaultPatchFn: PatchFn = defaultApplyPatch;\n\nfunction applyLegOverride<L>(\n base: L,\n ovr: Partial<L> | ((base: L, ctx: HarnessConstructionContext) => L) | undefined,\n ctx: HarnessConstructionContext,\n): L {\n if (!ovr) return base;\n if (typeof ovr === \"function\") return (ovr as (b: L, c: HarnessConstructionContext) => L)(base, ctx);\n return { ...base, ...ovr };\n}\n\nfunction countCacheTiers(fragments: readonly { cacheTier: CacheTier }[]): Record<CacheTier, number> {\n const counts: Record<CacheTier, number> = { stable: 0, axisDelta: 0, volatile: 0 };\n for (const f of fragments) counts[f.cacheTier]++;\n return counts;\n}\n\n/**\n * Build a Harness from classification + inputs. Idempotent: same inputs\n * produce a Harness with the same id.\n */\nexport function createHarness(input: CreateHarnessInput): Harness {\n const { classification, contract, prompt, shellType, screen, overrides } = input;\n const ctx: HarnessConstructionContext = { classification, contract, prompt };\n // Which triad to materialise — reaches the HOW leg (prompt), the WHAT\n // leg (boilerplate) and, via `harness.designMode`, every CHECK consumer.\n const designMode = input.designMode ?? DEFAULT_DESIGN_MODE;\n\n // ── Compose fragments from classification ────────────────────────────────\n const composed = compose(classification);\n\n // ── HOW leg ──────────────────────────────────────────────────────────────\n // System-prompt builder seam. The default is the skeleton builder\n // with empty content blocks; callers inject a fully-populated builder\n // to add pitfalls + design-system docs + primitives + wire content.\n const systemPromptBuilder: SystemPromptBuilder =\n input.systemPromptBuilder ?? buildSystemPrompt;\n const systemPrompt = systemPromptBuilder({\n userRequest: prompt,\n shellType,\n screen,\n axisDelta: composed.promptText,\n designMode,\n ...(input.canvas !== undefined ? { canvas: input.canvas } : {}),\n ...(input.profile !== undefined ? { profile: input.profile } : {}),\n });\n const howFragments = composed.fragments.filter(\n (f) => f.promptText && f.promptText.trim().length > 0,\n );\n const baseHow: HowLeg = {\n systemPrompt,\n implPrompt: \"\",\n fragments: howFragments,\n version: HOW_VERSION,\n };\n const how = applyLegOverride(baseHow, overrides?.how, ctx);\n\n // ── WHAT leg ─────────────────────────────────────────────────────────────\n // `appGadgets` reaches the boilerplate generator so thin contract\n // refs (`{hook: 'useLeafletMap'}` without a per-binding `package`)\n // resolve their import specifier from the operator-registered\n // descriptor's `package` field. Without this thread, the LLM's\n // starter file shows\n // `import { useLeafletMap } from '@ggui-ai/gadgets'` —\n // which doesn't export operator-registered wrapper hooks — and the\n // LLM removes the hook with a \"not available\" comment.\n const boilerplate = generateBoilerplate(\n prompt,\n contract as Parameters<typeof generateBoilerplate>[1],\n shellType,\n screen,\n composed.boilerplateSections,\n input.appGadgets,\n designMode,\n );\n const whatFragments = composed.fragments.filter(\n (f) => f.boilerplateMarker && f.boilerplateMarker.trim().length > 0,\n );\n const baseWhat: WhatLeg = {\n boilerplate,\n fragments: whatFragments,\n codingTools: [...HARNESS_CODING_TOOLS],\n scopedTools: [...HARNESS_SCOPED_TOOLS],\n applyPatch: defaultPatchFn,\n // Registered gadget catalog — drives the system prompt's gadget\n // table + the boilerplate's direct-import emission. Omitted when no\n // gadgets registered.\n ...(input.appGadgets !== undefined ? { appGadgets: input.appGadgets } : {}),\n // Third-party wrapper `.d.ts` map — autoCommit's typecheck overlays\n // the real wrapper declarations so a generated direct gadget import\n // gets strict hook types.\n ...(input.gadgetTypes !== undefined\n ? { gadgetTypes: input.gadgetTypes }\n : {}),\n version: WHAT_VERSION,\n };\n const what = applyLegOverride(baseWhat, overrides?.what, ctx);\n\n // ── CHECK leg ────────────────────────────────────────────────────────────\n // Axis-check registry seam. The caller supplies pre-filtered\n // axisChecks; the skeleton default is [].\n // Runtime-render seam. The skeleton default is undefined.\n const axisChecks = input.axisChecks ?? [];\n const baseCheck: CheckLeg = {\n axisChecks,\n tierChecks: [],\n runtimeRender: input.runtimeRender,\n llmEvaluator: undefined,\n version: CHECK_VERSION,\n };\n const check = applyLegOverride(baseCheck, overrides?.check, ctx);\n\n // ── Policy ───────────────────────────────────────────────────────────────\n // Policy injection seam. The caller pre-resolves; the skeleton\n // default is DEFAULT_HARNESS_POLICY.\n const policy = input.policy ?? DEFAULT_HARNESS_POLICY;\n\n // ── Process leg ──────────────────────────────────────────────────────────\n const workflow = pickWorkflow(classification);\n const baseProcess: ProcessLeg = {\n mode: policy.processMode ?? \"single_pass\",\n workflow,\n planner: undefined,\n retry: { maxIterations: 30 },\n version: PROCESS_VERSION,\n };\n const processLeg = applyLegOverride(baseProcess, overrides?.process, ctx);\n\n // ── Meta + id ────────────────────────────────────────────────────────────\n const classificationHash = hashClassification(classification);\n const fragmentIds = composed.fragments.map((f) => `${f.axis}=${f.value}`);\n const cacheTierBreakdown = countCacheTiers(composed.fragments);\n const overrideLabels: string[] = [];\n if (overrides?.how) overrideLabels.push(\"how\");\n if (overrides?.what) overrideLabels.push(\"what\");\n if (overrides?.check) overrideLabels.push(\"check\");\n if (overrides?.process) overrideLabels.push(\"process\");\n if (overrides?.label) overrideLabels.push(`label:${overrides.label}`);\n // Only non-default policies contribute to the harness id — preserves\n // byte-identical id across default-policy runs.\n if (!isDefaultHarnessPolicy(policy)) overrideLabels.push(\"policy\");\n // Only a non-default design mode contributes — the constrained id is\n // byte-identical to the pre-`designMode` harness.\n if (designMode !== DEFAULT_DESIGN_MODE) overrideLabels.push(`designMode:${designMode}`);\n if (hasProfile(input.profile)) overrideLabels.push(\"profile\");\n\n const id = computeHarnessId({\n classificationHash,\n howVersion: how.version,\n whatVersion: what.version,\n checkVersion: check.version,\n processVersion: processLeg.version,\n workflowId: workflow.id,\n fragmentIds,\n overrides: overrideLabels,\n });\n\n const name = computeHarnessName({\n classification,\n workflowName: workflow.name,\n version: HARNESS_VERSION,\n });\n\n const meta: HarnessMeta = {\n classificationHash,\n fragmentIds,\n cacheTierBreakdown,\n overrides: overrideLabels,\n createdAt: new Date().toISOString(),\n harnessVersion: HARNESS_VERSION,\n };\n\n const harness: Harness = {\n id,\n name,\n classification,\n designMode,\n ...(input.canvas !== undefined ? { canvas: input.canvas } : {}),\n ...(input.profile !== undefined ? { profile: input.profile } : {}),\n how,\n what,\n check,\n process: processLeg,\n policy,\n meta,\n derive(revision: HarnessRevision): Harness {\n return deriveHarness(this, revision, input);\n },\n };\n\n return harness;\n}\n\n/**\n * Produce a derived Harness for a subsequent iteration. Called when the\n * planner reclassifies or a runtime signal demands a topology swap.\n */\nfunction deriveHarness(\n base: Harness,\n revision: HarnessRevision,\n originalInput: CreateHarnessInput,\n): Harness {\n let mergedOverrides: HarnessOverrides = {\n ...originalInput.overrides,\n ...(revision.overrides ?? {}),\n };\n\n // If the revision names a new workflow explicitly, override the process leg.\n if (revision.workflow) {\n const currentProcessOverride = mergedOverrides.process;\n const processBuilder = (baseProcess: ProcessLeg, ctx: HarnessConstructionContext): ProcessLeg => {\n const withOverride =\n typeof currentProcessOverride === \"function\"\n ? currentProcessOverride(baseProcess, ctx)\n : { ...baseProcess, ...(currentProcessOverride ?? {}) };\n return { ...withOverride, workflow: revision.workflow! };\n };\n mergedOverrides = { ...mergedOverrides, process: processBuilder };\n }\n\n // Runtime fallback: promote scopedTools → codingTools.\n if (revision.useFallbackTools) {\n const currentWhatOverride = mergedOverrides.what;\n const whatBuilder = (baseWhat: WhatLeg, ctx: HarnessConstructionContext): WhatLeg => {\n const withOverride =\n typeof currentWhatOverride === \"function\"\n ? currentWhatOverride(baseWhat, ctx)\n : { ...baseWhat, ...(currentWhatOverride ?? {}) };\n if (withOverride.scopedTools && withOverride.scopedTools.length > 0) {\n return { ...withOverride, codingTools: withOverride.scopedTools };\n }\n return withOverride;\n };\n mergedOverrides = { ...mergedOverrides, what: whatBuilder };\n }\n\n return createHarness({\n ...originalInput,\n classification: revision.classification ?? base.classification,\n overrides: mergedOverrides,\n });\n}\n"]}
@@ -0,0 +1,28 @@
1
+ // src/harness/validator-trace-sink.ts
2
+ var activeSink = null;
3
+ function setValidatorTraceSink(sink) {
4
+ activeSink = sink;
5
+ }
6
+ function getValidatorTraceSink() {
7
+ return activeSink;
8
+ }
9
+ function emitValidatorTraceEvent(event) {
10
+ const sink = activeSink;
11
+ if (!sink) return;
12
+ try {
13
+ sink.emit(event);
14
+ } catch {
15
+ }
16
+ }
17
+ function truncateSourceForTrace(source) {
18
+ const cap = 16 * 1024;
19
+ if (source.length <= cap) return source;
20
+ return source.slice(0, cap) + "\n\n/* \u2026 truncated for devtools trace \u2026 */";
21
+ }
22
+ function newValidatorTraceId() {
23
+ return Date.now().toString(36) + Math.random().toString(36).slice(2, 10);
24
+ }
25
+
26
+ export { emitValidatorTraceEvent, getValidatorTraceSink, newValidatorTraceId, setValidatorTraceSink, truncateSourceForTrace };
27
+ //# sourceMappingURL=chunk-WYHP46LT.js.map
28
+ //# sourceMappingURL=chunk-WYHP46LT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/harness/validator-trace-sink.ts"],"names":[],"mappings":";AAgGA,IAAI,UAAA,GAAwC,IAAA;AAMrC,SAAS,sBAAsB,IAAA,EAAuC;AAC3E,EAAA,UAAA,GAAa,IAAA;AACf;AAGO,SAAS,qBAAA,GAAmD;AACjE,EAAA,OAAO,UAAA;AACT;AAOO,SAAS,wBAAwB,KAAA,EAAkC;AACxE,EAAA,MAAM,IAAA,GAAO,UAAA;AACb,EAAA,IAAI,CAAC,IAAA,EAAM;AACX,EAAA,IAAI;AACF,IAAA,IAAA,CAAK,KAAK,KAAK,CAAA;AAAA,EACjB,CAAA,CAAA,MAAQ;AAAA,EAER;AACF;AAMO,SAAS,uBAAuB,MAAA,EAAwB;AAC7D,EAAA,MAAM,MAAM,EAAA,GAAK,IAAA;AACjB,EAAA,IAAI,MAAA,CAAO,MAAA,IAAU,GAAA,EAAK,OAAO,MAAA;AACjC,EAAA,OAAO,MAAA,CAAO,KAAA,CAAM,CAAA,EAAG,GAAG,CAAA,GAAI,sDAAA;AAChC;AAMO,SAAS,mBAAA,GAA8B;AAC5C,EAAA,OACE,IAAA,CAAK,GAAA,EAAI,CAAE,QAAA,CAAS,EAAE,CAAA,GACtB,IAAA,CAAK,MAAA,EAAO,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,KAAA,CAAM,GAAG,EAAE,CAAA;AAE1C","file":"chunk-WYHP46LT.js","sourcesContent":["/**\n * Live validator-tier trace sink — devtools introspection of every\n * `runCheck()` invocation the harness performs.\n *\n * **Distinct from {@link LlmTraceSink}, {@link TelemetrySink}, and\n * {@link AuditSink}.**\n * - **LLM trace** (sibling) = devtools-only ring buffer of LLM call\n * payloads (system + user prompt, tools, completion, tokens).\n * Answers \"what did the LLM see / say?\".\n * - **Telemetry** (mcp-server-core) = ops signals (`pair.completed`,\n * `render.duration_ms`). Lossy. Flat scalars.\n * - **Audit** (mcp-server-core) = compliance log of privileged\n * mutations. Durable.\n * - **Validator trace** (this) = devtools-only ring buffer of every\n * `runCheck()` call's full validator-tier breakdown — which axis /\n * tier / runtime-render / LLM checks fired, what each returned\n * (pass/fail/warn issues with description, fix, line, severity).\n * Answers \"which check failed, and what did the LLM emit?\".\n *\n * **Why module-level registry instead of constructor injection.** Same\n * argument as the LLM trace sink — `runCheck()` is called from multiple\n * orchestrator entrypoints (`runHarness`, `run-eval-round`) across the\n * harness package; threading a sink through every call site for a\n * devtools-only surface isn't worth the churn. The ggui server is\n * single-process per CLI invocation; a hosted runtime isolates per\n * request via a process pool.\n *\n * **Default = no sink.** When unset, `runCheck` emits nothing and spends\n * no CPU formatting events. Passing `null` removes a previously\n * registered sink.\n */\nimport type { Classification } from \"../classifier/axes.js\";\nimport type { EvalIssue } from \"../evaluation/types-public.js\";\n\n/**\n * One `runCheck()` invocation. Emitted **after** all tiers complete\n * (success or partial — even when one tier throws, the others ran and\n * we surface what we have). Single event per call.\n */\nexport interface ValidatorTraceEvent {\n /** Random per-event ID. */\n readonly id: string;\n /** Epoch ms when `runCheck` was entered. */\n readonly at: number;\n /** Epoch ms when `runCheck` returned. */\n readonly endedAt: number;\n /** `endedAt - at` — convenience. */\n readonly durationMs: number;\n /** Harness fingerprint that drove these checks. */\n readonly harnessId: string;\n /** Classification axes that produced the harness — useful when the\n * operator asks \"why did this axis-check fire?\". */\n readonly classification: Classification;\n /** Workflow that produced the source-under-check. */\n readonly workflowId: string;\n /** Was a non-null compiledCode fed in? When false, runCheck short-\n * circuits to an empty result — surfaced for transparency. */\n readonly hadCompiledCode: boolean;\n /** Was the runtime-render probe deliberately skipped? Mirrors the\n * `skipRuntimeRender` input flag. */\n readonly skippedRuntimeRender: boolean;\n /** Per-tier issue counts and which check ids fired. */\n readonly summary: {\n readonly totalIssues: number;\n readonly axisIssues: number;\n readonly tierIssues: number;\n readonly llmIssues: number;\n readonly runtimeRenderIssues: number;\n readonly firedCheckIds: readonly string[];\n };\n /** Every issue emitted across all tiers. Carries description + fix +\n * line + severity + tier + category — the full per-issue payload the\n * validator UI renders into a per-tier breakdown. */\n readonly issues: readonly EvalIssue[];\n /** Source under check — capped at ~16KB. Operators expanding a card\n * want to see what failed; longer sources are truncated with a\n * trailing marker so the UI shows the truncation honestly. */\n readonly sourceCode?: string;\n /** Original prompt — useful when \"this passed eval but doesn't match\n * the request\" comes up in operator triage. */\n readonly prompt?: string;\n /** Set when `runCheck` itself threw before completing. The event is\n * still emitted (devtools want to see partial / failed runs). */\n readonly error?: { readonly message: string };\n}\n\n/**\n * Sink that receives one event per `runCheck()` invocation. Same\n * contract as {@link LlmTraceSink} — implementations MUST be sync +\n * non-throwing. Buffer + drop or fan out to a queue inside the\n * implementation.\n */\nexport interface ValidatorTraceSink {\n emit(event: ValidatorTraceEvent): void;\n}\n\nlet activeSink: ValidatorTraceSink | null = null;\n\n/**\n * Register the active sink. Pass `null` to remove. Subsequent\n * {@link emitValidatorTraceEvent} calls dispatch to this sink.\n */\nexport function setValidatorTraceSink(sink: ValidatorTraceSink | null): void {\n activeSink = sink;\n}\n\n/** Read the active sink. Mostly for tests. */\nexport function getValidatorTraceSink(): ValidatorTraceSink | null {\n return activeSink;\n}\n\n/**\n * Internal — used by `runCheck`. No-op when no sink is registered.\n * Swallows sink-thrown errors (a broken devtools sink must not break\n * generation).\n */\nexport function emitValidatorTraceEvent(event: ValidatorTraceEvent): void {\n const sink = activeSink;\n if (!sink) return;\n try {\n sink.emit(event);\n } catch {\n // Devtools sink is allowed to be buggy — generation must not die.\n }\n}\n\n/**\n * Truncate a source string to ~16KB so a runaway component doesn't\n * blow the per-event memory budget. Adds a visible truncation marker.\n */\nexport function truncateSourceForTrace(source: string): string {\n const cap = 16 * 1024;\n if (source.length <= cap) return source;\n return source.slice(0, cap) + \"\\n\\n/* … truncated for devtools trace … */\";\n}\n\n/**\n * Crockford-style random ID. Same approach as the LLM trace sink —\n * dep-free for any runtime the harness might run in.\n */\nexport function newValidatorTraceId(): string {\n return (\n Date.now().toString(36) +\n Math.random().toString(36).slice(2, 10)\n );\n}\n"]}
@@ -0,0 +1,274 @@
1
+ import { GeneratorAdapter, hasCredentials } from './chunk-XRBCRKA2.js';
2
+ import { sourceCodeFromToolUse } from './chunk-GAJI7Y3P.js';
3
+ import { loadClaudeAgentSdk, loginChildEnv, createToolMcpServer, claudeCodeLoginQueryOptions } from './chunk-JDH5EGNZ.js';
4
+
5
+ // src/adapters/claude/message-parser.ts
6
+ function createArtifacts() {
7
+ return {
8
+ compiledCode: "",
9
+ sourceCode: void 0,
10
+ stream: void 0,
11
+ generatorMeta: void 0,
12
+ sdkSessionId: void 0,
13
+ turnCount: 0,
14
+ inputTokens: 0,
15
+ outputTokens: 0,
16
+ cacheCreationTokens: 0,
17
+ cacheReadTokens: 0,
18
+ estimatedCostUsd: void 0,
19
+ subagentsUsed: []
20
+ };
21
+ }
22
+ function processMessage(message, artifacts, onProgress, maxTurns) {
23
+ extractSessionId(message, artifacts);
24
+ trackTurns(message, artifacts, onProgress, maxTurns);
25
+ trackTokenUsage(message, artifacts);
26
+ extractCompiledCode(message, artifacts, onProgress);
27
+ extractSourceCode(message, artifacts);
28
+ extractStreamSpec(message, artifacts);
29
+ extractGeneratorMeta(message, artifacts);
30
+ }
31
+ function extractSessionId(message, artifacts) {
32
+ if (message.type !== "system") return;
33
+ const systemMsg = message;
34
+ if (systemMsg.subtype === "init") {
35
+ artifacts.sdkSessionId = systemMsg.session_id;
36
+ }
37
+ }
38
+ function trackTurns(message, artifacts, onProgress, maxTurns) {
39
+ if (message.type !== "assistant") return;
40
+ const assistantMsg = message;
41
+ artifacts.turnCount++;
42
+ const contentBlocks = assistantMsg.message?.content;
43
+ if (Array.isArray(contentBlocks)) {
44
+ for (const block of contentBlocks) {
45
+ if (block.type === "tool_use") {
46
+ onProgress?.({ type: "tool_call", tool: block.name || "unknown" });
47
+ }
48
+ }
49
+ }
50
+ onProgress?.({ type: "turn", turn: artifacts.turnCount, maxTurns: maxTurns ?? 0 });
51
+ }
52
+ function trackTokenUsage(message, artifacts) {
53
+ if (message.type !== "result") return;
54
+ const resultMsg = message;
55
+ if (resultMsg.subtype === "success") {
56
+ const usage = resultMsg.usage;
57
+ artifacts.inputTokens = usage.input_tokens || 0;
58
+ artifacts.cacheCreationTokens = usage.cache_creation_input_tokens || 0;
59
+ artifacts.cacheReadTokens = usage.cache_read_input_tokens || 0;
60
+ artifacts.outputTokens = usage.output_tokens || 0;
61
+ artifacts.estimatedCostUsd = resultMsg.total_cost_usd;
62
+ }
63
+ }
64
+ function extractCompiledCode(message, artifacts, onProgress) {
65
+ if (artifacts.compiledCode) return;
66
+ const msgStr = JSON.stringify(message);
67
+ if (!msgStr.includes("compiledCode")) return;
68
+ const match = msgStr.match(/"compiledCode"\s*:\s*"([^"\\]*(\\.[^"\\]*)*)"/);
69
+ if (match) {
70
+ try {
71
+ artifacts.compiledCode = JSON.parse(`"${match[1]}"`);
72
+ onProgress?.({ type: "compiled", bytes: artifacts.compiledCode.length });
73
+ return;
74
+ } catch {
75
+ }
76
+ }
77
+ if (message.type === "user") {
78
+ const userMsg = message;
79
+ const code = extractFromToolResults(userMsg);
80
+ if (code) artifacts.compiledCode = code;
81
+ }
82
+ }
83
+ function extractFromToolResults(message) {
84
+ const content = message.message?.content;
85
+ if (!Array.isArray(content)) return void 0;
86
+ for (const item of content) {
87
+ if (typeof item === "object" && item !== null && "type" in item && item.type === "tool_result") {
88
+ const toolResultItem = item;
89
+ const code = parseCompiledCodeFromContent(toolResultItem.content);
90
+ if (code) return code;
91
+ }
92
+ }
93
+ return void 0;
94
+ }
95
+ function parseCompiledCodeFromContent(content) {
96
+ if (Array.isArray(content)) {
97
+ for (const item of content) {
98
+ const textItem = item;
99
+ if (textItem.type === "text" && textItem.text?.includes("compiledCode")) {
100
+ const code = tryParseCompiledCode(textItem.text);
101
+ if (code) return code;
102
+ }
103
+ }
104
+ }
105
+ if (typeof content === "string" && content.includes("compiledCode")) {
106
+ return tryParseCompiledCode(content);
107
+ }
108
+ return void 0;
109
+ }
110
+ function tryParseCompiledCode(text) {
111
+ try {
112
+ const parsed = JSON.parse(text);
113
+ if (parsed.success && parsed.compiledCode) return parsed.compiledCode;
114
+ } catch {
115
+ }
116
+ return void 0;
117
+ }
118
+ function extractSourceCode(message, artifacts) {
119
+ if (message.type !== "assistant") return;
120
+ const assistantMsg = message;
121
+ const content = assistantMsg.message?.content;
122
+ if (!Array.isArray(content)) return;
123
+ for (const block of content) {
124
+ if (block.type !== "tool_use") continue;
125
+ const value = sourceCodeFromToolUse(block.name, block.input);
126
+ if (value !== void 0) artifacts.sourceCode = value;
127
+ }
128
+ }
129
+ function unescapeJsonString(s) {
130
+ return s.replace(/\\n/g, "\n").replace(/\\"/g, '"').replace(/\\\\/g, "\\");
131
+ }
132
+ function extractMarker(msgStr, startMarker, endMarker) {
133
+ if (!msgStr.includes(startMarker)) return void 0;
134
+ const match = msgStr.match(new RegExp(`${startMarker}\\s*([\\s\\S]*?)\\s*${endMarker}`));
135
+ return match?.[1];
136
+ }
137
+ function extractStreamSpec(message, artifacts) {
138
+ if (artifacts.stream) return;
139
+ const raw = extractMarker(JSON.stringify(message), "__GGUI_STREAM_SPEC__", "__GGUI_STREAM_SPEC_END__");
140
+ if (!raw) return;
141
+ try {
142
+ artifacts.stream = JSON.parse(unescapeJsonString(raw));
143
+ } catch {
144
+ }
145
+ }
146
+ function extractGeneratorMeta(message, artifacts) {
147
+ if (artifacts.generatorMeta) return;
148
+ const raw = extractMarker(JSON.stringify(message), "__GGUI_META__", "__GGUI_META_END__");
149
+ if (!raw) return;
150
+ try {
151
+ const stripped = raw.replace(/```(?:json)?\s*/g, "").trim();
152
+ const parsed = JSON.parse(unescapeJsonString(stripped));
153
+ if (parsed.category) {
154
+ artifacts.generatorMeta = {
155
+ category: parsed.category,
156
+ description: parsed.description ?? ""
157
+ };
158
+ }
159
+ } catch {
160
+ }
161
+ }
162
+
163
+ // src/adapters/claude/sdk-tool-pins.ts
164
+ function sdkToolPins(input) {
165
+ const builtins = [...input.builtinTools ?? []];
166
+ const approved = input.allowedTools !== void 0 ? [...input.allowedTools] : Object.keys(input.mcpServers ?? {}).map((name) => `mcp__${name}`);
167
+ return { tools: builtins, settingSources: [], allowedTools: [...approved, ...builtins] };
168
+ }
169
+
170
+ // src/adapters/claude/sdk.ts
171
+ var ClaudeSdkAdapter = class extends GeneratorAdapter {
172
+ provider = "claude";
173
+ mode = "sdk";
174
+ displayName = "Claude (Agent SDK)";
175
+ constructor(config = {}) {
176
+ super(config);
177
+ }
178
+ /** Narrowed config access for Claude SDK-specific fields. */
179
+ get sdkConfig() {
180
+ return this.config;
181
+ }
182
+ isAvailable() {
183
+ return hasCredentials(this.config, "ANTHROPIC_API_KEY");
184
+ }
185
+ async generate(params) {
186
+ const startTime = Date.now();
187
+ const cfg = this.sdkConfig;
188
+ const { query } = await loadClaudeAgentSdk();
189
+ const login = cfg.claudeCodeLogin === true;
190
+ const env = login ? loginChildEnv(buildEnv(cfg.env)) : buildEnv(cfg.env);
191
+ const artifacts = createArtifacts();
192
+ const onProgress = cfg.onProgress;
193
+ let mcpServers = cfg.mcpServers;
194
+ let allowedTools = cfg.allowedTools;
195
+ if (!mcpServers && params.tools.length > 0) {
196
+ const bridge = await createToolMcpServer(params.tools);
197
+ mcpServers = { ggui: bridge.server };
198
+ allowedTools = bridge.allowedToolNames;
199
+ }
200
+ for await (const message of query({
201
+ prompt: params.userPrompt,
202
+ options: {
203
+ cwd: cfg.cwd,
204
+ env,
205
+ model: params.model,
206
+ maxTurns: params.maxTurns,
207
+ systemPrompt: params.systemPrompt,
208
+ ...mcpServers && { mcpServers },
209
+ ...cfg.agents && { agents: cfg.agents },
210
+ // ggui#1714 — no CLI built-ins unless asked for, no host settings, no permission bypass.
211
+ ...sdkToolPins({ mcpServers, allowedTools, builtinTools: cfg.builtinTools }),
212
+ ...cfg.cliPath && { pathToClaudeCodeExecutable: cfg.cliPath },
213
+ ...cfg.stderr && { stderr: cfg.stderr },
214
+ // ggui#1185 — tool-less, config-less, non-bare; the model is pinned above.
215
+ ...login ? claudeCodeLoginQueryOptions() : {}
216
+ }
217
+ })) {
218
+ processMessage(
219
+ message,
220
+ artifacts,
221
+ onProgress,
222
+ params.maxTurns
223
+ );
224
+ }
225
+ const generationTimeMs = Date.now() - startTime;
226
+ const totalCacheIn = artifacts.inputTokens + artifacts.cacheCreationTokens + artifacts.cacheReadTokens;
227
+ const cacheReadPct = totalCacheIn > 0 ? Math.round(artifacts.cacheReadTokens / totalCacheIn * 100) : 0;
228
+ console.log(
229
+ `[claude-sdk] cache: created=${artifacts.cacheCreationTokens} read=${artifacts.cacheReadTokens} input=${artifacts.inputTokens} output=${artifacts.outputTokens} turns=${artifacts.turnCount} cache-read-pct=${cacheReadPct}%`
230
+ );
231
+ if (!artifacts.compiledCode) {
232
+ const wasExhausted = artifacts.turnCount >= params.maxTurns;
233
+ throw new Error(
234
+ wasExhausted ? `Generation used all ${params.maxTurns} turns without producing compiled code.` : "Generation completed without compiled code"
235
+ );
236
+ }
237
+ return {
238
+ compiledCode: artifacts.compiledCode,
239
+ sourceCode: artifacts.sourceCode,
240
+ tokens: {
241
+ input: artifacts.inputTokens,
242
+ output: artifacts.outputTokens,
243
+ total: artifacts.inputTokens + artifacts.cacheCreationTokens + artifacts.cacheReadTokens + artifacts.outputTokens
244
+ },
245
+ generationTimeMs,
246
+ turnsUsed: artifacts.turnCount,
247
+ rawCostUsd: artifacts.estimatedCostUsd,
248
+ stream: artifacts.stream,
249
+ generatorMeta: artifacts.generatorMeta,
250
+ subagentsUsed: artifacts.subagentsUsed,
251
+ cacheCreationTokens: artifacts.cacheCreationTokens,
252
+ cacheReadTokens: artifacts.cacheReadTokens,
253
+ sdkSessionId: artifacts.sdkSessionId
254
+ };
255
+ }
256
+ };
257
+ function buildEnv(configEnv) {
258
+ if (configEnv) return sanitizeEnv({ ...configEnv });
259
+ const env = {};
260
+ for (const [key, value] of Object.entries(process.env)) {
261
+ if (value !== void 0) env[key] = value;
262
+ }
263
+ return sanitizeEnv(env);
264
+ }
265
+ function sanitizeEnv(env) {
266
+ if (env.ANTHROPIC_BASE_URL?.includes("localhost")) {
267
+ delete env.ANTHROPIC_BASE_URL;
268
+ }
269
+ return env;
270
+ }
271
+
272
+ export { ClaudeSdkAdapter };
273
+ //# sourceMappingURL=chunk-XGLO5LGG.js.map
274
+ //# sourceMappingURL=chunk-XGLO5LGG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/adapters/claude/message-parser.ts","../src/adapters/claude/sdk-tool-pins.ts","../src/adapters/claude/sdk.ts"],"names":[],"mappings":";;;;;AAmCO,SAAS,eAAA,GAAoC;AAClD,EAAA,OAAO;AAAA,IACL,YAAA,EAAc,EAAA;AAAA,IACd,UAAA,EAAY,MAAA;AAAA,IACZ,MAAA,EAAQ,MAAA;AAAA,IACR,aAAA,EAAe,MAAA;AAAA,IACf,YAAA,EAAc,MAAA;AAAA,IACd,SAAA,EAAW,CAAA;AAAA,IACX,WAAA,EAAa,CAAA;AAAA,IACb,YAAA,EAAc,CAAA;AAAA,IACd,mBAAA,EAAqB,CAAA;AAAA,IACrB,eAAA,EAAiB,CAAA;AAAA,IACjB,gBAAA,EAAkB,MAAA;AAAA,IAClB,eAAe;AAAC,GAClB;AACF;AAQO,SAAS,cAAA,CACd,OAAA,EACA,SAAA,EACA,UAAA,EACA,QAAA,EACM;AACN,EAAA,gBAAA,CAAiB,SAAS,SAAS,CAAA;AACnC,EAAA,UAAA,CAAW,OAAA,EAAS,SAAA,EAAW,UAAA,EAAY,QAAQ,CAAA;AACnD,EAAA,eAAA,CAAgB,SAAS,SAAS,CAAA;AAClC,EAAA,mBAAA,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AU;AAAA,KAC1B;AAAA,EACF;AACF;AAEA,SAAS,SAAS,SAAA,EAA4D;AAC5E,EAAA,IAAI,WAAW,OAAO,WAAA,CAAY,EAAE,GAAG,WAAW,CAAA;AAElD,EAAA,MAAM,MAA8B,EAAC;AACrC,EAAA,KAAA,MAAW,CAAC,KAAK,KAAK,CAAA,IAAK,OAAO,OAAA,CAAQ,OAAA,CAAQ,GAAG,CAAA,EAAG;AACtD,IAAA,IAAI,KAAA,KAAU,MAAA,EAAW,GAAA,CAAI,GAAG,CAAA,GAAI,KAAA;AAAA,EACtC;AACA,EAAA,OAAO,YAAY,GAAG,CAAA;AACxB;AAMA,SAAS,YAAY,GAAA,EAAqD;AAGxE,EAAA,IAAI,GAAA,CAAI,kBAAA,EAAoB,QAAA,CAAS,WAAW,CAAA,EAAG;AACjD,IAAA,OAAO,GAAA,CAAI,kBAAA;AAAA,EACb;AACA,EAAA,OAAO,GAAA;AACT","file":"chunk-XGLO5LGG.js","sourcesContent":["// packages/ui-gen/src/adapters/claude/message-parser.ts\n//\n// Focused helpers for extracting artifacts from Claude Agent SDK messages.\n// Each function handles one extraction concern, keeping the main loop clean.\n//\n// Uses proper discriminated union narrowing on SDKMessage variants.\n\nimport type {\n SDKMessage,\n SDKAssistantMessage,\n SDKResultMessage,\n SDKSystemMessage,\n SDKUserMessage,\n} from '@anthropic-ai/claude-agent-sdk';\nimport type { JsonObject } from '@ggui-ai/protocol';\nimport { sourceCodeFromToolUse } from './source-capture';\n\n/**\n * Mutable accumulator for artifacts extracted from the SDK message stream.\n */\nexport interface MessageArtifacts {\n compiledCode: string;\n sourceCode: string | undefined;\n stream: JsonObject | undefined;\n generatorMeta: { category: string; description: string } | undefined;\n sdkSessionId: string | undefined;\n turnCount: number;\n inputTokens: number;\n outputTokens: number;\n cacheCreationTokens: number;\n cacheReadTokens: number;\n estimatedCostUsd: number | undefined;\n subagentsUsed: string[];\n}\n\nexport function createArtifacts(): MessageArtifacts {\n return {\n compiledCode: '',\n sourceCode: undefined,\n stream: undefined,\n generatorMeta: undefined,\n sdkSessionId: undefined,\n turnCount: 0,\n inputTokens: 0,\n outputTokens: 0,\n cacheCreationTokens: 0,\n cacheReadTokens: 0,\n estimatedCostUsd: undefined,\n subagentsUsed: [],\n };\n}\n\n/** Progress event emitted during generation. */\nexport type ProgressEvent = { type: string; [key: string]: string | number | boolean | undefined };\n\n/**\n * Process a single SDK message and update artifacts accordingly.\n */\nexport function processMessage(\n message: SDKMessage,\n artifacts: MessageArtifacts,\n onProgress?: (event: ProgressEvent) => void,\n maxTurns?: number,\n): void {\n extractSessionId(message, artifacts);\n trackTurns(message, artifacts, onProgress, maxTurns);\n trackTokenUsage(message, artifacts);\n extractCompiledCode(message, artifacts, onProgress);\n extractSourceCode(message, artifacts);\n extractStreamSpec(message, artifacts);\n extractGeneratorMeta(message, artifacts);\n}\n\n// ── Individual extractors ────────────────────────────────────────────\n\nfunction extractSessionId(message: SDKMessage, artifacts: MessageArtifacts): void {\n if (message.type !== 'system') return;\n const systemMsg = message as SDKSystemMessage;\n if (systemMsg.subtype === 'init') {\n artifacts.sdkSessionId = systemMsg.session_id;\n }\n}\n\nfunction trackTurns(\n message: SDKMessage,\n artifacts: MessageArtifacts,\n onProgress?: (event: ProgressEvent) => void,\n maxTurns?: number,\n): void {\n if (message.type !== 'assistant') return;\n const assistantMsg = message as SDKAssistantMessage;\n artifacts.turnCount++;\n\n const contentBlocks = assistantMsg.message?.content;\n if (Array.isArray(contentBlocks)) {\n for (const block of contentBlocks) {\n if (block.type === 'tool_use') {\n onProgress?.({ type: 'tool_call', tool: block.name || 'unknown' });\n }\n }\n }\n onProgress?.({ type: 'turn', turn: artifacts.turnCount, maxTurns: maxTurns ?? 0 });\n}\n\nfunction trackTokenUsage(message: SDKMessage, artifacts: MessageArtifacts): void {\n if (message.type !== 'result') return;\n const resultMsg = message as SDKResultMessage;\n\n if (resultMsg.subtype === 'success') {\n const usage = resultMsg.usage;\n artifacts.inputTokens = usage.input_tokens || 0;\n artifacts.cacheCreationTokens = usage.cache_creation_input_tokens || 0;\n artifacts.cacheReadTokens = usage.cache_read_input_tokens || 0;\n artifacts.outputTokens = usage.output_tokens || 0;\n artifacts.estimatedCostUsd = resultMsg.total_cost_usd;\n }\n}\n\nfunction extractCompiledCode(\n message: SDKMessage,\n artifacts: MessageArtifacts,\n onProgress?: (event: ProgressEvent) => void,\n): void {\n if (artifacts.compiledCode) return; // Already found\n\n const msgStr = JSON.stringify(message);\n if (!msgStr.includes('compiledCode')) return;\n\n // Strategy 1: regex extraction from anywhere in the message\n const match = msgStr.match(/\"compiledCode\"\\s*:\\s*\"([^\"\\\\]*(\\\\.[^\"\\\\]*)*)\"/);\n if (match) {\n try {\n artifacts.compiledCode = JSON.parse(`\"${match[1]}\"`);\n onProgress?.({ type: 'compiled', bytes: artifacts.compiledCode.length });\n return;\n } catch {\n // Fall through to structured extraction\n }\n }\n\n // Strategy 2: structured extraction from tool_result content\n if (message.type === 'user') {\n const userMsg = message as SDKUserMessage;\n const code = extractFromToolResults(userMsg);\n if (code) artifacts.compiledCode = code;\n }\n}\n\n/**\n * Walk the nested tool_result structures to find compiledCode.\n */\nfunction extractFromToolResults(message: SDKUserMessage): string | undefined {\n const content = message.message?.content;\n if (!Array.isArray(content)) return undefined;\n\n for (const item of content) {\n if (typeof item === 'object' && item !== null && 'type' in item && item.type === 'tool_result') {\n const toolResultItem = item as { type: 'tool_result'; content?: unknown };\n const code = parseCompiledCodeFromContent(toolResultItem.content);\n if (code) return code;\n }\n }\n\n return undefined;\n}\n\nfunction parseCompiledCodeFromContent(content: unknown): string | undefined {\n if (Array.isArray(content)) {\n for (const item of content) {\n const textItem = item as { type?: string; text?: string };\n if (textItem.type === 'text' && textItem.text?.includes('compiledCode')) {\n const code = tryParseCompiledCode(textItem.text);\n if (code) return code;\n }\n }\n }\n if (typeof content === 'string' && content.includes('compiledCode')) {\n return tryParseCompiledCode(content);\n }\n return undefined;\n}\n\nfunction tryParseCompiledCode(text: string): string | undefined {\n try {\n const parsed = JSON.parse(text);\n if (parsed.success && parsed.compiledCode) return parsed.compiledCode;\n } catch {\n // Not valid JSON\n }\n return undefined;\n}\n\nfunction extractSourceCode(message: SDKMessage, artifacts: MessageArtifacts): void {\n if (message.type !== 'assistant') return;\n const assistantMsg = message as SDKAssistantMessage;\n\n const content = assistantMsg.message?.content;\n if (!Array.isArray(content)) return;\n\n for (const block of content) {\n if (block.type !== 'tool_use') continue;\n // ggui#1714 — the rule lives in source-capture.ts, shared with the evaluation loop.\n const value = sourceCodeFromToolUse(block.name, block.input);\n if (value !== undefined) artifacts.sourceCode = value;\n }\n}\n\n/**\n * Unescape a JSON string that was double-escaped inside another JSON string.\n */\nfunction unescapeJsonString(s: string): string {\n return s.replace(/\\\\n/g, '\\n').replace(/\\\\\"/g, '\"').replace(/\\\\\\\\/g, '\\\\');\n}\n\n/**\n * Extract a delimited marker from a JSON-stringified message.\n * Returns the raw content between START and END markers, or undefined.\n */\nfunction extractMarker(msgStr: string, startMarker: string, endMarker: string): string | undefined {\n if (!msgStr.includes(startMarker)) return undefined;\n const match = msgStr.match(new RegExp(`${startMarker}\\\\s*([\\\\s\\\\S]*?)\\\\s*${endMarker}`));\n return match?.[1];\n}\n\nfunction extractStreamSpec(message: SDKMessage, artifacts: MessageArtifacts): void {\n if (artifacts.stream) return;\n\n const raw = extractMarker(JSON.stringify(message), '__GGUI_STREAM_SPEC__', '__GGUI_STREAM_SPEC_END__');\n if (!raw) return;\n\n try {\n artifacts.stream = JSON.parse(unescapeJsonString(raw));\n } catch {\n // Failed to parse\n }\n}\n\nfunction extractGeneratorMeta(message: SDKMessage, artifacts: MessageArtifacts): void {\n if (artifacts.generatorMeta) return;\n\n const raw = extractMarker(JSON.stringify(message), '__GGUI_META__', '__GGUI_META_END__');\n if (!raw) return;\n\n try {\n const stripped = raw.replace(/```(?:json)?\\s*/g, '').trim();\n const parsed = JSON.parse(unescapeJsonString(stripped)) as { category?: string; description?: string };\n if (parsed.category) {\n artifacts.generatorMeta = {\n category: parsed.category,\n description: parsed.description ?? '',\n };\n }\n } catch {\n // Failed to parse\n }\n}\n","// packages/ui-gen/src/adapters/claude/sdk-tool-pins.ts\n//\n// ggui#1714 — the tool surface of every Agent SDK `query()` this package runs.\n//\n// Left to its defaults, a `query()` session offers the model the CLI's whole\n// built-in set (Bash, Edit, Read, Write, WebFetch, Task, …) and loads the host\n// user's own Claude configuration (plugins, MCP servers from `~/.claude`).\n// `allowedTools` does not narrow that: it only approves the names it lists.\n// Measured on SDK 0.3.229 from the session's `system`/`init` message:\n//\n// as before this file → every built-in + the caller's tools\n// `tools: []` alone → the caller's tools + a user-level plugin server\n// `tools: []` + `settingSources: []` → the caller's tools only\n//\n// So the pins are both, on every path. With them in place no permission\n// bypass is needed: a tool named in `allowedTools` runs, and a server-level\n// entry (`mcp__<server>`) approves every tool of that server (both measured\n// on a live turn; with no entry the call is denied and the run reports it).\n\nimport type { McpServerConfig, Options } from '@anthropic-ai/claude-agent-sdk';\n\nexport type SdkToolPins = Required<Pick<Options, 'tools' | 'settingSources' | 'allowedTools'>>;\n\nexport interface SdkToolPinInput {\n /** The MCP servers the session gets, keyed by name. */\n readonly mcpServers?: Record<string, McpServerConfig>;\n /** Tool names to approve. Absent → every tool of every server in `mcpServers`. */\n readonly allowedTools?: readonly string[];\n /**\n * The CLI built-ins to offer (e.g. `['Write']`) — an explicit opt-in.\n * Each one is also approved, so it runs without a prompt; a built-in that\n * writes or executes acts on the host with the session's permissions.\n */\n readonly builtinTools?: readonly string[];\n}\n\nexport function sdkToolPins(input: SdkToolPinInput): SdkToolPins {\n const builtins = [...(input.builtinTools ?? [])];\n const approved =\n input.allowedTools !== undefined\n ? [...input.allowedTools]\n : Object.keys(input.mcpServers ?? {}).map((name) => `mcp__${name}`);\n return { tools: builtins, settingSources: [], allowedTools: [...approved, ...builtins] };\n}\n","// packages/ui-gen/src/adapters/claude/sdk.ts\n//\n// Claude adapter using the Claude Agent SDK (@anthropic-ai/claude-agent-sdk).\n// Uses query() async iterator with MCP servers for tool execution.\n//\n// Two modes:\n// 1. Pre-configured MCP servers (production) — pass mcpServers in ClaudeSdkConfig\n// 2. Direct tools (benchmark) — ToolDefinition[] auto-bridged to in-process MCP server\n\nimport type { McpServerConfig } from '@anthropic-ai/claude-agent-sdk';\nimport { GeneratorAdapter, hasCredentials } from '../base';\nimport type { ClaudeSdkConfig, GenerateParams } from '../base';\nimport type { AdapterResult, ProviderName, AdapterMode } from '../types';\nimport { createArtifacts, processMessage } from './message-parser';\nimport { createToolMcpServer } from './tool-bridge';\nimport { claudeCodeLoginQueryOptions, loginChildEnv } from './claude-code-login';\nimport { sdkToolPins } from './sdk-tool-pins';\nimport { loadClaudeAgentSdk } from '../../harness/claude-agent-sdk-loader';\n\nexport class ClaudeSdkAdapter extends GeneratorAdapter {\n readonly provider: ProviderName = 'claude';\n readonly mode: AdapterMode = 'sdk';\n readonly displayName = 'Claude (Agent SDK)';\n\n constructor(config: ClaudeSdkConfig = {}) {\n super(config);\n }\n\n /** Narrowed config access for Claude SDK-specific fields. */\n private get sdkConfig(): ClaudeSdkConfig {\n return this.config as ClaudeSdkConfig;\n }\n\n isAvailable(): boolean {\n return hasCredentials(this.config, 'ANTHROPIC_API_KEY');\n }\n\n async generate(params: GenerateParams): Promise<AdapterResult> {\n const startTime = Date.now();\n const cfg = this.sdkConfig;\n\n // The SDK is an optional peer (ggui#1951): loaded on first use, and a\n // missing one fails with the install line.\n const { query } = await loadClaudeAgentSdk();\n\n // Build environment from config or process.env\n // ggui#1185/#1278 — on the login path the binary sees an allowlisted\n // env: no provider key (it prefers an env key over its login, so a stale\n // one would take the run off this path without a word), and nothing\n // else the parent merely holds.\n const login = cfg.claudeCodeLogin === true;\n const env = login ? loginChildEnv(buildEnv(cfg.env)) : buildEnv(cfg.env);\n\n const artifacts = createArtifacts();\n const onProgress = cfg.onProgress;\n\n // Determine MCP servers — use config's servers or bridge from tools\n let mcpServers: Record<string, McpServerConfig> | undefined = cfg.mcpServers;\n let allowedTools: string[] | undefined = cfg.allowedTools;\n\n if (!mcpServers && params.tools.length > 0) {\n // Bridge ToolDefinition[] to in-process MCP server\n const bridge = await createToolMcpServer(params.tools);\n mcpServers = { ggui: bridge.server };\n allowedTools = bridge.allowedToolNames;\n }\n\n // Run SDK query — message parsing is handled by processMessage()\n for await (const message of query({\n prompt: params.userPrompt,\n options: {\n cwd: cfg.cwd,\n env,\n model: params.model,\n maxTurns: params.maxTurns,\n systemPrompt: params.systemPrompt,\n ...(mcpServers && { mcpServers }),\n ...(cfg.agents && { agents: cfg.agents }),\n // ggui#1714 — no CLI built-ins unless asked for, no host settings, no permission bypass.\n ...sdkToolPins({ mcpServers, allowedTools, builtinTools: cfg.builtinTools }),\n ...(cfg.cliPath && { pathToClaudeCodeExecutable: cfg.cliPath }),\n ...(cfg.stderr && { stderr: cfg.stderr }),\n // ggui#1185 — tool-less, config-less, non-bare; the model is pinned above.\n ...(login ? claudeCodeLoginQueryOptions() : {}),\n },\n })) {\n processMessage(\n message,\n artifacts,\n onProgress,\n params.maxTurns,\n );\n }\n\n const generationTimeMs = Date.now() - startTime;\n\n // Cache audit telemetry. Track whether the Claude Agent SDK is\n // actually caching the system prompt\n // across turns. `read > 0` on turn 2+ means the SDK's internal\n // cache_control is firing. `read = 0` across all turns = we're\n // paying full input cost every turn; explicit cache_control needed.\n const totalCacheIn = artifacts.inputTokens + artifacts.cacheCreationTokens + artifacts.cacheReadTokens;\n const cacheReadPct = totalCacheIn > 0\n ? Math.round((artifacts.cacheReadTokens / totalCacheIn) * 100)\n : 0;\n console.log(\n `[claude-sdk] cache: created=${artifacts.cacheCreationTokens} read=${artifacts.cacheReadTokens} input=${artifacts.inputTokens} output=${artifacts.outputTokens} turns=${artifacts.turnCount} cache-read-pct=${cacheReadPct}%`,\n );\n\n if (!artifacts.compiledCode) {\n const wasExhausted = artifacts.turnCount >= params.maxTurns;\n throw new Error(\n wasExhausted\n ? `Generation used all ${params.maxTurns} turns without producing compiled code.`\n : 'Generation completed without compiled code',\n );\n }\n\n return {\n compiledCode: artifacts.compiledCode,\n sourceCode: artifacts.sourceCode,\n tokens: {\n input: artifacts.inputTokens,\n output: artifacts.outputTokens,\n total:\n artifacts.inputTokens +\n artifacts.cacheCreationTokens +\n artifacts.cacheReadTokens +\n artifacts.outputTokens,\n },\n generationTimeMs,\n turnsUsed: artifacts.turnCount,\n rawCostUsd: artifacts.estimatedCostUsd,\n stream: artifacts.stream,\n generatorMeta: artifacts.generatorMeta,\n subagentsUsed: artifacts.subagentsUsed,\n cacheCreationTokens: artifacts.cacheCreationTokens,\n cacheReadTokens: artifacts.cacheReadTokens,\n sdkSessionId: artifacts.sdkSessionId,\n };\n }\n}\n\nfunction buildEnv(configEnv?: Record<string, string>): Record<string, string> {\n if (configEnv) return sanitizeEnv({ ...configEnv });\n\n const env: Record<string, string> = {};\n for (const [key, value] of Object.entries(process.env)) {\n if (value !== undefined) env[key] = value;\n }\n return sanitizeEnv(env);\n}\n\n/**\n * Remove env vars that would redirect the SDK subprocess to a non-running proxy.\n * The SDK subprocess must connect to the real Anthropic API.\n */\nfunction sanitizeEnv(env: Record<string, string>): Record<string, string> {\n // Strip ANTHROPIC_BASE_URL if it points to localhost (LiteLLM proxy)\n // — the SDK subprocess should always use the real Anthropic API\n if (env.ANTHROPIC_BASE_URL?.includes('localhost')) {\n delete env.ANTHROPIC_BASE_URL;\n }\n return env;\n}\n"]}
@@ -0,0 +1,29 @@
1
+ // src/adapters/base.ts
2
+ var GeneratorAdapter = class {
3
+ constructor(config) {
4
+ this.config = config;
5
+ }
6
+ config;
7
+ /**
8
+ * Map a LiteLLM-format model ID to this SDK's native format.
9
+ * Default: strips the provider prefix (e.g., 'anthropic/claude-sonnet-4-6' -> 'claude-sonnet-4-6').
10
+ * Override only if the prefix convention differs.
11
+ */
12
+ resolveModelId(litellmModelId) {
13
+ return stripModelPrefix(litellmModelId);
14
+ }
15
+ };
16
+ function stripModelPrefix(modelId) {
17
+ const slashIndex = modelId.indexOf("/");
18
+ return slashIndex >= 0 ? modelId.slice(slashIndex + 1) : modelId;
19
+ }
20
+ function hasCredentials(config, ...envVarNames) {
21
+ if (config.apiKey) return true;
22
+ if (config.useBedrock) return true;
23
+ if (config.claudeCodeLogin) return true;
24
+ return envVarNames.some((name) => !!process.env[name]);
25
+ }
26
+
27
+ export { GeneratorAdapter, hasCredentials };
28
+ //# sourceMappingURL=chunk-XRBCRKA2.js.map
29
+ //# sourceMappingURL=chunk-XRBCRKA2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/adapters/base.ts"],"names":[],"mappings":";AAgGO,IAAe,mBAAf,MAAgC;AAAA,EAKrC,YAA+B,MAAA,EAA0B;AAA1B,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAA2B;AAAA,EAA3B,MAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiB/B,eAAe,cAAA,EAAgC;AAC7C,IAAA,OAAO,iBAAiB,cAAc,CAAA;AAAA,EACxC;AACF;AAQA,SAAS,iBAAiB,OAAA,EAAyB;AACjD,EAAA,MAAM,UAAA,GAAa,OAAA,CAAQ,OAAA,CAAQ,GAAG,CAAA;AACtC,EAAA,OAAO,cAAc,CAAA,GAAI,OAAA,CAAQ,KAAA,CAAM,UAAA,GAAa,CAAC,CAAA,GAAI,OAAA;AAC3D;AAKO,SAAS,cAAA,CACd,WACG,WAAA,EACM;AACT,EAAA,IAAI,MAAA,CAAO,QAAQ,OAAO,IAAA;AAC1B,EAAA,IAAI,MAAA,CAAO,YAAY,OAAO,IAAA;AAC9B,EAAA,IAAI,MAAA,CAAO,iBAAiB,OAAO,IAAA;AACnC,EAAA,OAAO,WAAA,CAAY,KAAK,CAAC,IAAA,KAAS,CAAC,CAAC,OAAA,CAAQ,GAAA,CAAI,IAAI,CAAC,CAAA;AACvD","file":"chunk-XRBCRKA2.js","sourcesContent":["// packages/ui-gen/src/adapters/base.ts\n//\n// Abstract base class for all generator adapters.\n\nimport type { McpServerConfig, AgentDefinition } from '@anthropic-ai/claude-agent-sdk';\nimport type { JsonObject } from '@ggui-ai/protocol';\nimport type { AdapterResult, ToolDefinition, ProviderName, AdapterMode } from './types';\n\n/**\n * Core configuration shared by all adapters.\n */\nexport interface AdapterConfig {\n /** API key for the provider (BYOK) */\n apiKey?: string;\n /** Use Bedrock instead of direct API (Claude only) */\n useBedrock?: boolean;\n /**\n * ggui#1185 — run on the machine's own Claude Code login instead of a key.\n * Claude SDK adapter only. The adapter strips every provider key from the\n * spawned env and pins the run tool-less, config-less and non-bare (see\n * `claude/claude-code-login.ts`). Opt-in; absent ⇒ key-based auth.\n */\n claudeCodeLogin?: boolean;\n /**\n * Thinking level for models with extended thinking (Gemini 3.x Flash\n * via the Interactions API). Mirrors the API's `thinking_level` enum —\n * `'minimal'` is the floor (the API has NO true off), then `'low'` /\n * `'medium'` / `'high'`. Omitted → provider default, and Gemini 3.5\n * Flash defaults thinking ON with no cap — the dominant latency cost\n * in contract-bounded UI generation. Only the Google adapter consumes\n * this today.\n */\n thinkingLevel?: 'minimal' | 'low' | 'medium' | 'high';\n}\n\n/**\n * Extended configuration for Claude Agent SDK adapter.\n * Separated from AdapterConfig to avoid polluting the base interface\n * with provider-specific concerns.\n */\nexport interface ClaudeSdkConfig extends AdapterConfig {\n /** Working directory for SDK subprocess */\n cwd?: string;\n /** Environment variables for SDK subprocess */\n env?: Record<string, string>;\n /** MCP server configs for Claude Agent SDK (keyed by name) */\n mcpServers?: Record<string, McpServerConfig>;\n /** Tool names to approve. Absent → every tool of every server in `mcpServers` (ggui#1714). */\n allowedTools?: string[];\n /**\n * CLI built-in tools to offer the model (e.g. `['Write']`). Default: none.\n * An explicit opt-in: a built-in that writes or executes acts on the host (ggui#1714).\n */\n builtinTools?: readonly string[];\n /** Subagent definitions for Claude Agent SDK */\n agents?: Record<string, AgentDefinition>;\n /** Custom CLI path for Docker deployments */\n cliPath?: string;\n /** stderr callback for debug logging */\n stderr?: (data: string) => void;\n /** Progress callback */\n onProgress?: (event: { type: string; [key: string]: unknown }) => void;\n}\n\n/**\n * Union config type — adapters accept their specific config\n * but the registry uses this union so callers can pass any config.\n */\nexport type AnyAdapterConfig = AdapterConfig | ClaudeSdkConfig;\n\n/**\n * Parameters for a single generation run.\n */\nexport interface GenerateParams {\n /** System prompt (HOW to build — shared across all SDKs) */\n systemPrompt: string;\n /** User prompt (WHAT to build — the specific request) */\n userPrompt: string;\n /** Model identifier (provider-native format, e.g., 'claude-sonnet-4-6') */\n model: string;\n /** SDK-agnostic tool definitions */\n tools: ToolDefinition[];\n /** Maximum agentic loop turns */\n maxTurns: number;\n /** Model-specific options (e.g., speed_priority for Claude fast mode) */\n modelOptions?: JsonObject;\n}\n\n/**\n * Abstract base class for generator adapters.\n *\n * Each adapter wraps a specific provider SDK (Claude, OpenAI, Google)\n * in either raw API mode or agent SDK mode, and implements the tool-use\n * loop using the SDK's native API. All adapters produce the same\n * output format (AdapterResult).\n */\nexport abstract class GeneratorAdapter {\n abstract readonly provider: ProviderName;\n abstract readonly mode: AdapterMode;\n abstract readonly displayName: string;\n\n constructor(protected readonly config: AnyAdapterConfig) {}\n\n /**\n * Run UI generation with the given tools, prompt, and model.\n */\n abstract generate(params: GenerateParams): Promise<AdapterResult>;\n\n /**\n * Check if this adapter can run (SDK installed, credentials available).\n */\n abstract isAvailable(): boolean;\n\n /**\n * Map a LiteLLM-format model ID to this SDK's native format.\n * Default: strips the provider prefix (e.g., 'anthropic/claude-sonnet-4-6' -> 'claude-sonnet-4-6').\n * Override only if the prefix convention differs.\n */\n resolveModelId(litellmModelId: string): string {\n return stripModelPrefix(litellmModelId);\n }\n}\n\n/**\n * Strip provider prefix from LiteLLM-format model IDs.\n * 'anthropic/claude-sonnet-4-6' -> 'claude-sonnet-4-6'\n * 'openai/gpt-5.3-codex' -> 'gpt-5.3-codex'\n * 'gemini/gemini-3-flash-preview' -> 'gemini-3-flash-preview'\n */\nfunction stripModelPrefix(modelId: string): string {\n const slashIndex = modelId.indexOf('/');\n return slashIndex >= 0 ? modelId.slice(slashIndex + 1) : modelId;\n}\n\n/**\n * Check if credentials are available from config or environment variables.\n */\nexport function hasCredentials(\n config: AdapterConfig,\n ...envVarNames: string[]\n): boolean {\n if (config.apiKey) return true;\n if (config.useBedrock) return true;\n if (config.claudeCodeLogin) return true;\n return envVarNames.some((name) => !!process.env[name]);\n}\n"]}