@aglyn/plugins-ai 1.0.0-beta.230 → 1.0.0-beta.232

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 (305) hide show
  1. package/package.json +17 -17
  2. package/src/lib/activity/ai-activity-actions.js +8 -4
  3. package/src/lib/activity/ai-activity-actions.js.map +1 -1
  4. package/src/lib/components/ai-assist-provider-on-host.component.d.ts +66 -0
  5. package/src/lib/components/ai-assist-provider-on-host.component.js +78 -0
  6. package/src/lib/components/ai-assist-provider-on-host.component.js.map +1 -0
  7. package/src/lib/components/ai-assist-provider.component.js +9 -10
  8. package/src/lib/components/ai-assist-provider.component.js.map +1 -1
  9. package/src/lib/components/ai-job-follow.component.js +1 -0
  10. package/src/lib/components/ai-job-follow.component.js.map +1 -1
  11. package/src/lib/components/ai-job-links.js +13 -0
  12. package/src/lib/components/ai-job-links.js.map +1 -1
  13. package/src/lib/components/ai-job-plan.component.js +3 -1
  14. package/src/lib/components/ai-job-plan.component.js.map +1 -1
  15. package/src/lib/components/ai-jobs-list-page.component.js +1 -0
  16. package/src/lib/components/ai-jobs-list-page.component.js.map +1 -1
  17. package/src/lib/components/ai-media-create.component.d.ts +20 -7
  18. package/src/lib/components/ai-media-create.component.js +107 -55
  19. package/src/lib/components/ai-media-create.component.js.map +1 -1
  20. package/src/lib/components/ai-permissions-on-host.component.d.ts +3 -46
  21. package/src/lib/components/ai-permissions-on-host.component.js +5 -53
  22. package/src/lib/components/ai-permissions-on-host.component.js.map +1 -1
  23. package/src/lib/components/ai-seo-fields-card.component.js +1 -0
  24. package/src/lib/components/ai-seo-fields-card.component.js.map +1 -1
  25. package/src/lib/components/ai-site-build-page.component.js +20 -8
  26. package/src/lib/components/ai-site-build-page.component.js.map +1 -1
  27. package/src/lib/components/ai-site-memory-card.component.d.ts +32 -0
  28. package/src/lib/components/ai-site-memory-card.component.js +187 -0
  29. package/src/lib/components/ai-site-memory-card.component.js.map +1 -0
  30. package/src/lib/components/ai-site-start-card.component.js +80 -77
  31. package/src/lib/components/ai-site-start-card.component.js.map +1 -1
  32. package/src/lib/components/ai-theme-proposal-card.component.js +4 -0
  33. package/src/lib/components/ai-theme-proposal-card.component.js.map +1 -1
  34. package/src/lib/components/ai-usage-strip.component.js +1 -0
  35. package/src/lib/components/ai-usage-strip.component.js.map +1 -1
  36. package/src/lib/components/assist-panel.component.d.ts +10 -0
  37. package/src/lib/components/assist-panel.component.js +119 -9
  38. package/src/lib/components/assist-panel.component.js.map +1 -1
  39. package/src/lib/components/assist-signals-page.component.js +2 -0
  40. package/src/lib/components/assist-signals-page.component.js.map +1 -1
  41. package/src/lib/components/billing-ai-allotments.component.js +3 -0
  42. package/src/lib/components/billing-ai-allotments.component.js.map +1 -1
  43. package/src/lib/components/billing-ai-top-users.component.js +1 -0
  44. package/src/lib/components/billing-ai-top-users.component.js.map +1 -1
  45. package/src/lib/components/billing-assist-overage-card.component.js +2 -0
  46. package/src/lib/components/billing-assist-overage-card.component.js.map +1 -1
  47. package/src/lib/components/member-ai-usage-card.component.js +10 -0
  48. package/src/lib/components/member-ai-usage-card.component.js.map +1 -1
  49. package/src/lib/components/staff-org-ai-card.component.js +1 -0
  50. package/src/lib/components/staff-org-ai-card.component.js.map +1 -1
  51. package/src/lib/components/staff-org-ai-conversations.component.d.ts +23 -0
  52. package/src/lib/components/staff-org-ai-conversations.component.js +346 -0
  53. package/src/lib/components/staff-org-ai-conversations.component.js.map +1 -0
  54. package/src/lib/jobs/ai-build-capabilities.d.ts +13 -1
  55. package/src/lib/jobs/ai-build-capabilities.js +101 -7
  56. package/src/lib/jobs/ai-build-capabilities.js.map +1 -1
  57. package/src/lib/jobs/ai-build-unit-outcome.js +4 -2
  58. package/src/lib/jobs/ai-build-unit-outcome.js.map +1 -1
  59. package/src/lib/jobs/ai-business-profile-prefill.d.ts +29 -0
  60. package/src/lib/jobs/ai-business-profile-prefill.js +85 -0
  61. package/src/lib/jobs/ai-business-profile-prefill.js.map +1 -0
  62. package/src/lib/jobs/ai-job-auto-confirm.d.ts +8 -0
  63. package/src/lib/jobs/ai-job-auto-confirm.js +30 -6
  64. package/src/lib/jobs/ai-job-auto-confirm.js.map +1 -1
  65. package/src/lib/jobs/ai-job-build-step.js +14 -1
  66. package/src/lib/jobs/ai-job-build-step.js.map +1 -1
  67. package/src/lib/jobs/ai-job-edit-step.d.ts +225 -0
  68. package/src/lib/jobs/ai-job-edit-step.js +631 -0
  69. package/src/lib/jobs/ai-job-edit-step.js.map +1 -0
  70. package/src/lib/jobs/ai-job-generation.d.ts +8 -0
  71. package/src/lib/jobs/ai-job-generation.js +13 -2
  72. package/src/lib/jobs/ai-job-generation.js.map +1 -1
  73. package/src/lib/jobs/ai-job-insight-step.js +29 -5
  74. package/src/lib/jobs/ai-job-insight-step.js.map +1 -1
  75. package/src/lib/jobs/ai-job-layout-language.d.ts +78 -0
  76. package/src/lib/jobs/ai-job-layout-language.js +200 -0
  77. package/src/lib/jobs/ai-job-layout-language.js.map +1 -0
  78. package/src/lib/jobs/ai-job-layout-site-pages.d.ts +13 -2
  79. package/src/lib/jobs/ai-job-layout-site-pages.js +18 -2
  80. package/src/lib/jobs/ai-job-layout-site-pages.js.map +1 -1
  81. package/src/lib/jobs/ai-job-layout-step.d.ts +5 -0
  82. package/src/lib/jobs/ai-job-layout-step.js +107 -6
  83. package/src/lib/jobs/ai-job-layout-step.js.map +1 -1
  84. package/src/lib/jobs/ai-job-logic-step.d.ts +20 -0
  85. package/src/lib/jobs/ai-job-logic-step.js +87 -6
  86. package/src/lib/jobs/ai-job-logic-step.js.map +1 -1
  87. package/src/lib/jobs/ai-job-page-language.d.ts +194 -0
  88. package/src/lib/jobs/ai-job-page-language.js +418 -0
  89. package/src/lib/jobs/ai-job-page-language.js.map +1 -0
  90. package/src/lib/jobs/ai-job-page-sections.d.ts +37 -1
  91. package/src/lib/jobs/ai-job-page-sections.js +93 -11
  92. package/src/lib/jobs/ai-job-page-sections.js.map +1 -1
  93. package/src/lib/jobs/ai-job-page-step.d.ts +4 -4
  94. package/src/lib/jobs/ai-job-page-step.js +115 -14
  95. package/src/lib/jobs/ai-job-page-step.js.map +1 -1
  96. package/src/lib/jobs/ai-job-plan-step.d.ts +20 -6
  97. package/src/lib/jobs/ai-job-plan-step.js +62 -22
  98. package/src/lib/jobs/ai-job-plan-step.js.map +1 -1
  99. package/src/lib/jobs/ai-job-site-content.d.ts +163 -0
  100. package/src/lib/jobs/ai-job-site-content.js +443 -0
  101. package/src/lib/jobs/ai-job-site-content.js.map +1 -0
  102. package/src/lib/jobs/ai-job-site-look.d.ts +112 -0
  103. package/src/lib/jobs/ai-job-site-look.js +322 -0
  104. package/src/lib/jobs/ai-job-site-look.js.map +1 -0
  105. package/src/lib/jobs/ai-job-site-step.d.ts +30 -5
  106. package/src/lib/jobs/ai-job-site-step.js +183 -27
  107. package/src/lib/jobs/ai-job-site-step.js.map +1 -1
  108. package/src/lib/jobs/ai-job-workflow-step.js +2 -2
  109. package/src/lib/jobs/ai-job-workflow-step.js.map +1 -1
  110. package/src/lib/jobs/ai-jobs-notify.d.ts +6 -1
  111. package/src/lib/jobs/ai-jobs-notify.js +15 -3
  112. package/src/lib/jobs/ai-jobs-notify.js.map +1 -1
  113. package/src/lib/jobs/ai-jobs.d.ts +1 -1
  114. package/src/lib/jobs/ai-jobs.js +17 -8
  115. package/src/lib/jobs/ai-jobs.js.map +1 -1
  116. package/src/lib/jobs/ai-layout-full-height.d.ts +40 -0
  117. package/src/lib/jobs/ai-layout-full-height.js +82 -0
  118. package/src/lib/jobs/ai-layout-full-height.js.map +1 -0
  119. package/src/lib/jobs/ai-layout-site-facts.d.ts +54 -0
  120. package/src/lib/jobs/ai-layout-site-facts.js +153 -0
  121. package/src/lib/jobs/ai-layout-site-facts.js.map +1 -0
  122. package/src/lib/layout-language/ai-layout-compiler.d.ts +154 -0
  123. package/src/lib/layout-language/ai-layout-compiler.js +1235 -0
  124. package/src/lib/layout-language/ai-layout-compiler.js.map +1 -0
  125. package/src/lib/layout-language/ai-layout-copy.d.ts +73 -0
  126. package/src/lib/layout-language/ai-layout-copy.js +137 -0
  127. package/src/lib/layout-language/ai-layout-copy.js.map +1 -0
  128. package/src/lib/layout-language/ai-layout-frame.d.ts +52 -0
  129. package/src/lib/layout-language/ai-layout-frame.js +458 -0
  130. package/src/lib/layout-language/ai-layout-frame.js.map +1 -0
  131. package/src/lib/layout-language/ai-layout-gaps.d.ts +63 -0
  132. package/src/lib/layout-language/ai-layout-gaps.js +345 -0
  133. package/src/lib/layout-language/ai-layout-gaps.js.map +1 -0
  134. package/src/lib/layout-language/ai-layout-language.d.ts +168 -0
  135. package/src/lib/layout-language/ai-layout-language.js +529 -0
  136. package/src/lib/layout-language/ai-layout-language.js.map +1 -0
  137. package/src/lib/layout-language/ai-layout-links.d.ts +80 -0
  138. package/src/lib/layout-language/ai-layout-links.js +109 -0
  139. package/src/lib/layout-language/ai-layout-links.js.map +1 -0
  140. package/src/lib/layout-language/ai-layout-pictures.d.ts +144 -0
  141. package/src/lib/layout-language/ai-layout-pictures.js +214 -0
  142. package/src/lib/layout-language/ai-layout-pictures.js.map +1 -0
  143. package/src/lib/layout-language/ai-layout-store.d.ts +41 -0
  144. package/src/lib/layout-language/ai-layout-store.js +75 -0
  145. package/src/lib/layout-language/ai-layout-store.js.map +1 -0
  146. package/src/lib/layout-language/ai-layout-tree.d.ts +59 -0
  147. package/src/lib/layout-language/ai-layout-tree.js +84 -0
  148. package/src/lib/layout-language/ai-layout-tree.js.map +1 -0
  149. package/src/lib/lazy-widget.d.ts +45 -0
  150. package/src/lib/lazy-widget.js +53 -0
  151. package/src/lib/lazy-widget.js.map +1 -0
  152. package/src/lib/model/ai-build-job.js +2 -1
  153. package/src/lib/model/ai-build-job.js.map +1 -1
  154. package/src/lib/model/ai-build-progress.d.ts +20 -3
  155. package/src/lib/model/ai-build-progress.js +52 -7
  156. package/src/lib/model/ai-build-progress.js.map +1 -1
  157. package/src/lib/model/ai-edit-job.d.ts +109 -0
  158. package/src/lib/model/ai-edit-job.js +157 -0
  159. package/src/lib/model/ai-edit-job.js.map +1 -0
  160. package/src/lib/model/ai-host-publish-context.d.ts +51 -0
  161. package/src/lib/model/ai-host-publish-context.js +104 -0
  162. package/src/lib/model/ai-host-publish-context.js.map +1 -0
  163. package/src/lib/model/ai-job-activity.d.ts +22 -0
  164. package/src/lib/model/ai-job-activity.js +23 -1
  165. package/src/lib/model/ai-job-activity.js.map +1 -1
  166. package/src/lib/model/ai-job-failure-copy.d.ts +38 -1
  167. package/src/lib/model/ai-job-failure-copy.js +56 -1
  168. package/src/lib/model/ai-job-failure-copy.js.map +1 -1
  169. package/src/lib/model/ai-job-notice.d.ts +3 -1
  170. package/src/lib/model/ai-job-notice.js +31 -9
  171. package/src/lib/model/ai-job-notice.js.map +1 -1
  172. package/src/lib/model/ai-jobs.types.d.ts +22 -1
  173. package/src/lib/model/ai-jobs.types.js.map +1 -1
  174. package/src/lib/model/ai-logic-job.d.ts +18 -1
  175. package/src/lib/model/ai-logic-job.js +24 -3
  176. package/src/lib/model/ai-logic-job.js.map +1 -1
  177. package/src/lib/model/ai-media-credits.d.ts +8 -4
  178. package/src/lib/model/ai-media-credits.js +11 -4
  179. package/src/lib/model/ai-media-credits.js.map +1 -1
  180. package/src/lib/model/ai-media-kinds.d.ts +68 -0
  181. package/src/lib/model/ai-media-kinds.js +98 -0
  182. package/src/lib/model/ai-media-kinds.js.map +1 -0
  183. package/src/lib/model/ai-site-build-progress.d.ts +9 -1
  184. package/src/lib/model/ai-site-build-progress.js +54 -14
  185. package/src/lib/model/ai-site-build-progress.js.map +1 -1
  186. package/src/lib/model/ai-site-context.d.ts +111 -0
  187. package/src/lib/model/ai-site-context.js +222 -0
  188. package/src/lib/model/ai-site-context.js.map +1 -0
  189. package/src/lib/model/ai-site-job.d.ts +18 -2
  190. package/src/lib/model/ai-site-job.js +21 -5
  191. package/src/lib/model/ai-site-job.js.map +1 -1
  192. package/src/lib/model/ai-site-kinds.d.ts +164 -0
  193. package/src/lib/model/ai-site-kinds.js +1942 -0
  194. package/src/lib/model/ai-site-kinds.js.map +1 -0
  195. package/src/lib/model/ai-site-look.d.ts +150 -0
  196. package/src/lib/model/ai-site-look.js +1236 -0
  197. package/src/lib/model/ai-site-look.js.map +1 -0
  198. package/src/lib/model/ai-site-memory.d.ts +80 -0
  199. package/src/lib/model/ai-site-memory.js +171 -0
  200. package/src/lib/model/ai-site-memory.js.map +1 -0
  201. package/src/lib/model/ai-site-start-seo.d.ts +1 -1
  202. package/src/lib/model/ai-site-start.d.ts +15 -3
  203. package/src/lib/model/ai-site-start.js +21 -4
  204. package/src/lib/model/ai-site-start.js.map +1 -1
  205. package/src/lib/model/assist-follow-up.d.ts +92 -0
  206. package/src/lib/model/assist-follow-up.js +128 -0
  207. package/src/lib/model/assist-follow-up.js.map +1 -0
  208. package/src/lib/plugin-config.js +2 -0
  209. package/src/lib/plugin-config.js.map +1 -1
  210. package/src/lib/plugin.js +99 -48
  211. package/src/lib/plugin.js.map +1 -1
  212. package/src/lib/providers/anthropic.d.ts +9 -1
  213. package/src/lib/providers/anthropic.js +143 -9
  214. package/src/lib/providers/anthropic.js.map +1 -1
  215. package/src/lib/providers/catalog.d.ts +38 -8
  216. package/src/lib/providers/catalog.js +106 -14
  217. package/src/lib/providers/catalog.js.map +1 -1
  218. package/src/lib/providers/contract.d.ts +29 -0
  219. package/src/lib/providers/contract.js.map +1 -1
  220. package/src/lib/providers/image-contract.d.ts +22 -1
  221. package/src/lib/providers/image-contract.js +40 -1
  222. package/src/lib/providers/image-contract.js.map +1 -1
  223. package/src/lib/providers/image-endpoints.d.ts +24 -0
  224. package/src/lib/providers/image-endpoints.js +28 -0
  225. package/src/lib/providers/image-endpoints.js.map +1 -0
  226. package/src/lib/providers/model-choice.js +23 -2
  227. package/src/lib/providers/model-choice.js.map +1 -1
  228. package/src/lib/providers/routing.js +18 -0
  229. package/src/lib/providers/routing.js.map +1 -1
  230. package/src/lib/providers/vertex-image-endpoint.d.ts +48 -0
  231. package/src/lib/providers/vertex-image-endpoint.js +80 -0
  232. package/src/lib/providers/vertex-image-endpoint.js.map +1 -0
  233. package/src/lib/providers/vertex-image.d.ts +13 -27
  234. package/src/lib/providers/vertex-image.js +15 -42
  235. package/src/lib/providers/vertex-image.js.map +1 -1
  236. package/src/lib/runtime/ai-blog-post-generation.d.ts +62 -0
  237. package/src/lib/runtime/ai-blog-post-generation.js +89 -0
  238. package/src/lib/runtime/ai-blog-post-generation.js.map +1 -0
  239. package/src/lib/runtime/ai-dev-env.d.ts +53 -0
  240. package/src/lib/runtime/ai-dev-env.js +72 -0
  241. package/src/lib/runtime/ai-dev-env.js.map +1 -0
  242. package/src/lib/runtime/ai-dev-replay.d.ts +116 -0
  243. package/src/lib/runtime/ai-dev-replay.js +313 -0
  244. package/src/lib/runtime/ai-dev-replay.js.map +1 -0
  245. package/src/lib/runtime/ai-doctrine-validators.d.ts +82 -0
  246. package/src/lib/runtime/ai-doctrine-validators.js +436 -4
  247. package/src/lib/runtime/ai-doctrine-validators.js.map +1 -1
  248. package/src/lib/runtime/ai-doctrine.js +16 -3
  249. package/src/lib/runtime/ai-doctrine.js.map +1 -1
  250. package/src/lib/runtime/ai-eval-live.js +4 -0
  251. package/src/lib/runtime/ai-eval-live.js.map +1 -1
  252. package/src/lib/runtime/ai-eval.d.ts +13 -1
  253. package/src/lib/runtime/ai-eval.js +84 -1
  254. package/src/lib/runtime/ai-eval.js.map +1 -1
  255. package/src/lib/runtime/ai-icon-library.d.ts +257 -0
  256. package/src/lib/runtime/ai-icon-library.js +254 -0
  257. package/src/lib/runtime/ai-icon-library.js.map +1 -0
  258. package/src/lib/runtime/ai-live-batch.d.ts +45 -0
  259. package/src/lib/runtime/ai-live-batch.js +89 -0
  260. package/src/lib/runtime/ai-live-batch.js.map +1 -0
  261. package/src/lib/runtime/ai-node-tree.d.ts +9 -0
  262. package/src/lib/runtime/ai-node-tree.js +30 -4
  263. package/src/lib/runtime/ai-node-tree.js.map +1 -1
  264. package/src/lib/runtime/ai-palette.d.ts +6 -0
  265. package/src/lib/runtime/ai-palette.generated.js +70 -0
  266. package/src/lib/runtime/ai-palette.generated.js.map +1 -1
  267. package/src/lib/runtime/ai-palette.js.map +1 -1
  268. package/src/lib/runtime/ai-runtime.js +46 -2
  269. package/src/lib/runtime/ai-runtime.js.map +1 -1
  270. package/src/lib/runtime/site-context.d.ts +58 -0
  271. package/src/lib/runtime/site-context.js +127 -0
  272. package/src/lib/runtime/site-context.js.map +1 -0
  273. package/src/lib/server/ai-admin-conversations.d.ts +22 -0
  274. package/src/lib/server/ai-admin-conversations.js +197 -0
  275. package/src/lib/server/ai-admin-conversations.js.map +1 -0
  276. package/src/lib/server/ai-media-image.d.ts +5 -5
  277. package/src/lib/server/ai-media-image.js +25 -11
  278. package/src/lib/server/ai-media-image.js.map +1 -1
  279. package/src/lib/server/ai-media-raster-prompt.d.ts +34 -0
  280. package/src/lib/server/ai-media-raster-prompt.js +53 -0
  281. package/src/lib/server/ai-media-raster-prompt.js.map +1 -0
  282. package/src/lib/server/assist-chat.d.ts +11 -0
  283. package/src/lib/server/assist-chat.js +57 -18
  284. package/src/lib/server/assist-chat.js.map +1 -1
  285. package/src/lib/server/assist-edit-applied.js +16 -3
  286. package/src/lib/server/assist-edit-applied.js.map +1 -1
  287. package/src/lib/server/assist-view-context.d.ts +19 -1
  288. package/src/lib/server/assist-view-context.js +38 -1
  289. package/src/lib/server/assist-view-context.js.map +1 -1
  290. package/src/lib/server.js +10 -0
  291. package/src/lib/server.js.map +1 -1
  292. package/src/lib/subprocessors.js +17 -1
  293. package/src/lib/subprocessors.js.map +1 -1
  294. package/src/lib/tools/ai-blog-post-tool.d.ts +60 -0
  295. package/src/lib/tools/ai-blog-post-tool.js +175 -0
  296. package/src/lib/tools/ai-blog-post-tool.js.map +1 -0
  297. package/src/lib/tools/ai-workflow-tool.d.ts +6 -2
  298. package/src/lib/tools/ai-workflow-tool.js +16 -14
  299. package/src/lib/tools/ai-workflow-tool.js.map +1 -1
  300. package/src/lib/usage/assist-usage.d.ts +3 -0
  301. package/src/lib/usage/assist-usage.js +4 -2
  302. package/src/lib/usage/assist-usage.js.map +1 -1
  303. package/src/lib/usage/staff-org-ai-conversations.d.ts +103 -0
  304. package/src/lib/usage/staff-org-ai-conversations.js +152 -0
  305. package/src/lib/usage/staff-org-ai-conversations.js.map +1 -0
@@ -14,13 +14,14 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
14
14
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
- */ import { createHash } from "node:crypto";
17
+ */ import { aiSiteKindOfInputs } from "../model/ai-site-kinds.js";
18
+ import { createHash } from "node:crypto";
18
19
  import { AI_BUILD_PLAN_TOOL, aiBuildPlanToolFor, isAiPlanNewRef } from "../model/ai-build-plan.js";
19
20
  import { AI_TEMPLATE_SUBJECT_DEFINITIONS, aiTemplateShownTokens } from "../model/ai-template-subjects.js";
20
21
  import { AI_JOB_CREATE_KINDS, AI_JOB_CREATE_NOUNS } from "../model/ai-job-creations.js";
21
22
  import { AI_PAGE_CREATE_KINDS, aiPagePlanShapeRefusal } from "../model/ai-page-job.js";
22
23
  import { AI_PLAN_NO_FORM_SENTENCE, aiPlanCanPlaceForm, aiPlanCapabilitiesForJob, aiPlanCapabilityLines } from "../model/ai-plan-capabilities.js";
23
- import { AI_FREE_SITE_WORST_CASE_CREDITS, AI_SITE_CREATE_KINDS, AI_SITE_FREE_PAGES, AI_SITE_PLAN_MAX_TOKENS, aiFreeSiteSectionsWithin, aiSitePlanShapeRefusal } from "../model/ai-site-job.js";
24
+ import { AI_FREE_SITE_WORST_CASE_CREDITS, AI_SITE_CREATE_KINDS, AI_SITE_FREE_PAGES, AI_SITE_PLAN_MAX_TOKENS, aiFreeSiteSectionsWithin, aiSiteNameSentence, aiSitePlanShapeRefusal } from "../model/ai-site-job.js";
24
25
  import { aiPlanFailureCopy, aiPlanRetryRefusal } from "../model/ai-job-failure-copy.js";
25
26
  import { FREE_AI_TASTE_CREDITS_PER_MONTH } from "../plan-entitlements.js";
26
27
  import { aiDoctrineSystemBlocks, runValidatedGeneration } from "../runtime/ai-doctrine.js";
@@ -31,6 +32,8 @@ import { ASSIST_RETURNED_USD_FIELD, assistSpendAfterReturnsUsd } from "../usage/
31
32
  import { freeAccountUsageRef, freeAssistAccount } from "../usage/assist-free-taste.js";
32
33
  import { AI_ROUTING_TABLE, aiModelForStep } from "../providers/routing.js";
33
34
  import { readSiteInventory } from "../runtime/site-inventory.js";
35
+ import { readAiSiteContext } from "../runtime/site-context.js";
36
+ import { aiInstructionsWithSiteContext } from "../model/ai-site-context.js";
34
37
  import { AI_BUILD_CREATE_KINDS, AI_BUILD_STRUCTURAL_OPS, aiBuildPageLimit, aiBuildPlanShapeRefusal } from "../model/ai-build-job.js";
35
38
  import { aiBuildOpLines, aiBuildOps } from "./ai-build-capabilities.js";
36
39
  import { aiJobAdmissionRefusal } from "./ai-job-admission.js";
@@ -150,8 +153,13 @@ import { AI_JOBS_COLLECTION, registerAiJobPlanStep } from "./ai-jobs.js";
150
153
  * job's turn, whose length the Free page's wall is proven at.
151
154
  */ export function aiPlanSiteLines(job, inventory, capabilities) {
152
155
  var _ref;
156
+ var _job_inputs;
153
157
  if (job.kind !== 'site') return [];
154
158
  const lines = [];
159
+ // The business's own name, as the name to use (AGL-3596): the plan's search
160
+ // titles carry it, and an input line alone left the model free to coin one.
161
+ const name = (_job_inputs = job.inputs) == null ? void 0 : _job_inputs['businessName'];
162
+ if (typeof name === 'string' && name.trim()) lines.push(aiSiteNameSentence(name.trim()));
155
163
  const pages = ((_ref = inventory == null ? void 0 : inventory.screens) != null ? _ref : []).filter((screen)=>!screen.template);
156
164
  const starter = pages.find((screen)=>screen.replaceable);
157
165
  if (pages.length) {
@@ -172,6 +180,9 @@ import { AI_JOBS_COLLECTION, registerAiJobPlanStep } from "./ai-jobs.js";
172
180
  }, FREE_AI_TASTE_CREDITS_PER_MONTH);
173
181
  lines.push(`This is a Free workspace: plan at most ${cap} ${cap === 1 ? 'page' : 'pages'} — the home page at / and the one page the brief most needs, such as services, booking or contact — with at most ${sections} sections across them.${aiPlanCanPlaceForm(inventory, capabilities) ? ' Put the contact form on one of them.' : ''}`);
174
182
  }
183
+ // The kind of site the person picked (AGL-3660): the pages it usually has.
184
+ const kind = aiSiteKindOfInputs(job.inputs);
185
+ if (kind) lines.push(`This is a ${kind.label.toLowerCase()} site. ${kind.pages}`);
175
186
  lines.push("Keep the plan an outline: each page's title, address, a short search title and description, and its sections named in a few words. The build writes the copy.");
176
187
  return lines;
177
188
  }
@@ -412,6 +423,10 @@ function planMillis(plan) {
412
423
  hostId: job.hostId,
413
424
  org
414
425
  }) : null;
426
+ /** The reader the step uses in production: fail-soft, org-scoped, `null` for a job with no site. */ export const readAiJobSiteContext = ({ job, firestore })=>readAiSiteContext(firestore, {
427
+ orgId: job.orgId,
428
+ hostId: job.hostId
429
+ });
415
430
  /** The reader the step uses in production: the registry, gated for the job's site. */ export const readAiBuildOps = async ({ job, org, firestore, freeTaste })=>{
416
431
  var _data, _job_hostId;
417
432
  const host = job.hostId ? (_data = (await firestore.collection('hosts').doc(job.hostId).get()).data()) != null ? _data : null : null;
@@ -446,10 +461,11 @@ export function createAiJobPlanStep(deps = {}) {
446
461
  const readCapabilities = (_deps_readCapabilities = deps.readCapabilities) != null ? _deps_readCapabilities : readAiJobPlanCapabilities;
447
462
  const admissionRefusal = (_deps_admissionRefusal = deps.admissionRefusal) != null ? _deps_admissionRefusal : aiJobAdmissionRefusal;
448
463
  const readOps = (_deps_readOps = deps.readOps) != null ? _deps_readOps : readAiBuildOps;
464
+ const readContext = deps.readSiteContext === undefined ? readAiJobSiteContext : deps.readSiteContext;
449
465
  return async ({ job, now, signal, firestore, modelFor, org: orgDocument })=>{
450
466
  var _AI_JOB_PLAN_SCOPES_job_kind, _ref;
451
467
  const org = orgDocument != null ? orgDocument : null;
452
- const [inventory, workspace] = await Promise.all([
468
+ const [inventory, workspace, siteContext] = await Promise.all([
453
469
  job.hostId ? readInventory(job.orgId, job.hostId, {
454
470
  firestore
455
471
  }) : Promise.resolve(null),
@@ -457,8 +473,16 @@ export function createAiJobPlanStep(deps = {}) {
457
473
  job,
458
474
  org,
459
475
  firestore
460
- })
476
+ }),
477
+ job.hostId && readContext ? readContext({
478
+ job,
479
+ firestore
480
+ }) : Promise.resolve(null)
461
481
  ]);
482
+ // The site's profile, status and memory (AGL-3661), as a per-site cached
483
+ // block after the plan rules. The inventory block already lists what the
484
+ // site holds, so the context carries no index of its own here.
485
+ const instructions = aiInstructionsWithSiteContext(AI_JOB_PLAN_INSTRUCTIONS, siteContext);
462
486
  const scope = (_AI_JOB_PLAN_SCOPES_job_kind = AI_JOB_PLAN_SCOPES[job.kind]) != null ? _AI_JOB_PLAN_SCOPES_job_kind : null;
463
487
  const capabilities = aiSitePlanCapabilities(job, workspace ? aiPlanCapabilitiesForJob(workspace, scope) : null);
464
488
  const freeTaste = (capabilities == null ? void 0 : capabilities.freeTaste) === true;
@@ -528,7 +552,7 @@ export function createAiJobPlanStep(deps = {}) {
528
552
  prompt,
529
553
  model: resolved,
530
554
  system: aiDoctrineSystemBlocks(inventory, {
531
- instructions: AI_JOB_PLAN_INSTRUCTIONS
555
+ instructions
532
556
  }),
533
557
  tool
534
558
  });
@@ -563,7 +587,7 @@ export function createAiJobPlanStep(deps = {}) {
563
587
  }, model ? {
564
588
  model
565
589
  } : {}, {
566
- instructions: AI_JOB_PLAN_INSTRUCTIONS,
590
+ instructions,
567
591
  inventory,
568
592
  messages: [
569
593
  {
@@ -601,6 +625,7 @@ export function createAiJobPlanStep(deps = {}) {
601
625
  refused: true
602
626
  });
603
627
  if (result.status === 'needs_input') {
628
+ var _review_detail;
604
629
  // Refused by our own checks, after the one re-ask (AGL-3594): the member
605
630
  // reads a sentence and an action, staff the rules; the machine gives the
606
631
  // credits back (`uncredited`), and on the Free taste Try again says when
@@ -622,7 +647,7 @@ export function createAiJobPlanStep(deps = {}) {
622
647
  codes: result.violations.map((violation)=>violation.code),
623
648
  refunded: false
624
649
  }),
625
- detail: review.message
650
+ detail: (_review_detail = review.detail) != null ? _review_detail : review.message
626
651
  }, retryRefusal ? {
627
652
  retryRefusal
628
653
  } : {})
@@ -649,25 +674,40 @@ export function createAiJobPlanStep(deps = {}) {
649
674
  };
650
675
  }
651
676
  /**
652
- * A site job's capabilities on the Free taste (AGL-3594): its plan holds at
653
- * most the pages the member asked for within the Free band, which the Free
654
- * wall then holds it to, and it changes no theme — the site was born with
655
- * one (AGL-3497), and a palette pass is credits the two pages need. Every
656
- * other job's capabilities pass through.
677
+ * A site job's capabilities (AGL-3594, AGL-3660): it changes no theme in its
678
+ * plan — every scaffold designs its look first, in a unit of its own — and on
679
+ * the Free taste its plan holds at most the pages the member asked for within
680
+ * the Free band, which the Free wall then holds it to. Every other job's
681
+ * capabilities pass through.
657
682
  */ export function aiSitePlanCapabilities(job, capabilities) {
658
683
  var _job_inputs;
659
- if (job.kind !== 'site' || !(capabilities == null ? void 0 : capabilities.freeTaste)) return capabilities;
684
+ if (job.kind !== 'site' || !capabilities) return capabilities;
685
+ const create = _extends({}, capabilities.create, {
686
+ 'theme-change': {
687
+ allowed: false,
688
+ left: null,
689
+ reason: 'a site start designs its own look before its pages'
690
+ },
691
+ // A site start builds its look, one layout and one form, never a
692
+ // component (`AI_SITE_CREATE_KINDS`), so a paid workspace's plan draws
693
+ // repeated items in their sections, as a Free one's does. Held to rule 1
694
+ // instead, every paid plan was refused: for the component it left out,
695
+ // or, re-asked, for the one it could not build (AGL-3660).
696
+ component: {
697
+ allowed: false,
698
+ left: null,
699
+ reason: 'a site start draws its repeated items in their sections'
700
+ }
701
+ });
702
+ const site = _extends({}, capabilities, {
703
+ reusableComponents: false,
704
+ create
705
+ });
706
+ if (!capabilities.freeTaste) return site;
660
707
  const asked = Number(((_job_inputs = job.inputs) != null ? _job_inputs : {})['pages']);
661
708
  const pages = Number.isInteger(asked) && asked >= AI_SITE_FREE_PAGES.min ? Math.min(asked, AI_SITE_FREE_PAGES.max) : AI_SITE_FREE_PAGES.max;
662
- return _extends({}, capabilities, {
663
- freeSitePages: pages,
664
- create: _extends({}, capabilities.create, {
665
- 'theme-change': {
666
- allowed: false,
667
- left: null,
668
- reason: "a Free workspace's site start keeps the theme the site was created with"
669
- }
670
- })
709
+ return _extends({}, site, {
710
+ freeSitePages: pages
671
711
  });
672
712
  }
673
713
  /**
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-plan-step.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createHash } from 'node:crypto'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport {\n AI_BUILD_PLAN_TOOL,\n aiBuildPlanToolFor,\n isAiPlanNewRef,\n type AiBuildPlan,\n} from '../model/ai-build-plan'\nimport type { AiJob, AiJobKind, AiJobPlan, AiJobStatus } from '../model/ai-jobs.types'\nimport {\n AI_TEMPLATE_SUBJECT_DEFINITIONS,\n aiTemplateShownTokens,\n type AiTemplateSubject,\n} from '../model/ai-template-subjects'\nimport { AI_JOB_CREATE_KINDS, AI_JOB_CREATE_NOUNS } from '../model/ai-job-creations'\nimport { AI_PAGE_CREATE_KINDS, aiPagePlanShapeRefusal } from '../model/ai-page-job'\nimport {\n AI_PLAN_NO_FORM_SENTENCE,\n aiPlanCanPlaceForm,\n aiPlanCapabilitiesForJob,\n aiPlanCapabilityLines,\n type AiPlanCapabilities,\n type AiPlanJobScope,\n} from '../model/ai-plan-capabilities'\nimport type { AiSiteInventory } from '../model/ai-site-inventory'\nimport {\n AI_FREE_SITE_WORST_CASE_CREDITS,\n AI_SITE_CREATE_KINDS,\n AI_SITE_FREE_PAGES,\n AI_SITE_PLAN_MAX_TOKENS,\n aiFreeSiteSectionsWithin,\n aiSitePlanShapeRefusal,\n} from '../model/ai-site-job'\nimport { aiPlanFailureCopy, aiPlanRetryRefusal } from '../model/ai-job-failure-copy'\nimport { FREE_AI_TASTE_CREDITS_PER_MONTH } from '../plan-entitlements'\nimport { aiDoctrineSystemBlocks, runValidatedGeneration } from '../runtime/ai-doctrine'\nimport { AI_STEP_TIERS, aiCatalogEntry, aiDefaultModelFor } from '../providers/catalog'\nimport {\n AI_FREE_PAGE_WORST_CASE_CREDITS,\n aiPlanEmbedBriefViolations,\n type AiDoctrineViolation,\n} from '../runtime/ai-doctrine-validators'\nimport { assistCreditsFromUsd } from '../usage/assist-credits'\nimport { ASSIST_RETURNED_USD_FIELD, assistSpendAfterReturnsUsd } from '../usage/assist-credit-returns'\nimport { freeAccountUsageRef, freeAssistAccount, type AssistMeteredOrg } from '../usage/assist-free-taste'\nimport { AI_ROUTING_TABLE, aiModelForStep } from '../providers/routing'\nimport type { AiTool } from '../providers/contract'\nimport type { AiSystemBlock } from '../runtime/ai-runtime'\nimport { readSiteInventory } from '../runtime/site-inventory'\nimport {\n AI_BUILD_CREATE_KINDS,\n AI_BUILD_STRUCTURAL_OPS,\n aiBuildPageLimit,\n aiBuildPlanShapeRefusal,\n type AiBuildOps,\n} from '../model/ai-build-job'\nimport { aiBuildOpLines, aiBuildOps } from './ai-build-capabilities'\nimport { aiJobAdmissionRefusal } from './ai-job-admission'\nimport { readAiPlanCapabilities } from './ai-job-drafts'\nimport {\n AI_JOB_BRIEF_MAX_CHARS,\n type AiJobStepOutcome,\n type AiJobStepRunner,\n} from './ai-job-text-step'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { aiDoctrineReview, aiUnspentOutcome } from './ai-job-generation'\nimport { aiPlanWithDraftIds } from './ai-job-draft-ids'\nimport { AI_JOBS_COLLECTION, registerAiJobPlanStep } from './ai-jobs'\n\n/**\n * The plan step (AGL-2935): the first step of every job that builds site\n * structure. Before a node is generated, the model answers with a typed plan\n * — what the site already has that the job reuses, what it creates and why,\n * and the screens it builds from them — held to the doctrine's plan rules\n * against the site's inventory and re-asked once when it breaks one.\n *\n * A plan that passes is kept on the job, and the job stops for review: the\n * member reads what it will build before a credit is spent building it, and\n * confirms through the resume door. A plan that still breaks a rule on its\n * re-ask stops the job the same way, with the rules named. Either way the\n * step writes nothing itself; the machine records the plan, the spend and\n * the stop, as it records every step.\n *\n * ── Told what it may create, refused what it cannot build (AGL-3030) ─────\n *\n * Before it asks, the step reads what the job may create on its site: the\n * workspace's plan, the site's counts against its limits, and — for a kind\n * that builds only some plans — what the job builds itself. The user turn\n * states it, the plan rules refuse a creation outside it with the one re-ask,\n * and where the workspace keeps no reusable components they accept the page\n * built inline. A plan the confirm door would still refuse — the kind's own\n * admission, handed the plan, as the resume door hands it — is refused HERE,\n * before a member is shown a Confirm: the job fails with the door's sentence,\n * its plan is not kept, and it holds nothing.\n */\n\n/** The plan step's own instructions, cached after the doctrine. */\nexport const AI_JOB_PLAN_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text:\n 'You plan what a website builder job will build, before anything is built. You are given the kind of job and the brief from the person who owns the site. ' +\n 'Answer with submit_build_plan: what the site inventory already has that the job reuses, what it must create and why nothing listed will do, and each page it builds (the screens list) with its layout, template, slug, search title, search description and sections from top to bottom. ' +\n 'Refer to inventory records by id and to what the plan creates as new:<name>. Plan only what the brief asks for: a component, layout, template, form or email job plans no pages unless the brief asks for them, and a page job plans exactly one page.',\n },\n]\n\n/**\n * The plan step's time (AGL-3026, AGL-3036): its two inventory-lookup rounds,\n * its answer and its re-ask at the routing table's ceiling for `job.plan`, on\n * the tier that step kind is served from, with the step's reads and writes,\n * at the rates `ai-job-budget.ts` assumes — fitted to what a beat can give a\n * step, so the served tier asks a little under the routing ceiling.\n */\nexport const AI_JOB_PLAN_STEP_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS['job.plan'],\n maxTokens: AI_ROUTING_TABLE['job.plan'].maxTokens,\n})\n\n/**\n * The least time a plan needs before it starts. Registered with the step, so\n * an inline door never starts a plan. A plan thinks before it answers and\n * routinely runs past an inline door's budget, and a provider call that\n * budget cuts off is still generated and billed upstream while the meter\n * records nothing. The beat starts a plan only with this much of its own\n * budget left, and a spec holds it inside that budget.\n */\nexport const AI_JOB_PLAN_STEP_MINIMUM_MS = AI_JOB_PLAN_STEP_BUDGET.minimumMs\n\n/**\n * The plan's answer ceiling on the model a job runs: the most whose worst\n * case fits the least time the step registered, and never more than the\n * routing table's. A model the catalog does not know is planned at the\n * slowest.\n */\nexport function aiJobPlanMaxTokens(model: string): number {\n return AI_JOB_PLAN_STEP_BUDGET.maxTokens(model)\n}\n\n/** What the member reads while a plan waits for them. */\nexport const AI_JOB_PLAN_REVIEW_COPY =\n 'The plan is ready. Review what the job will reuse and create, then confirm it to build.'\n\n/**\n * The job as the plan step's user turn: its kind, its brief, its scalar\n * inputs and, where the job read them, what it may create on its site\n * (AGL-3030). Per workspace and per site, which is why they ride here and\n * never in a system block the platform's cache entry is keyed on.\n */\nexport function aiJobPlanPrompt(\n job: Pick<AiJob, 'kind' | 'brief' | 'inputs'>,\n capabilities: AiPlanCapabilities | null = null,\n inventory: AiSiteInventory | null = null,\n ops: AiBuildOps | null = null,\n): string {\n const lines = [`Job kind: ${job.kind}`, `Brief: ${job.brief.slice(0, AI_JOB_BRIEF_MAX_CHARS)}`]\n for (const [key, value] of Object.entries(job.inputs ?? {})) {\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n lines.push(`${key}: ${String(value)}`)\n }\n }\n if (capabilities) lines.push(...aiPlanCapabilityLines(capabilities))\n // A form is a saved form or none (AGL-3596): said where the site read has\n // none to place and the job may create none.\n if (capabilities && inventory && !aiPlanCanPlaceForm(inventory, capabilities)) {\n lines.push(AI_PLAN_NO_FORM_SENTENCE)\n }\n lines.push(...aiPlanTemplateTokenLines(job))\n lines.push(...aiPlanSiteLines(job, inventory, capabilities))\n lines.push(...aiPlanBuildLines(job, capabilities, ops))\n return lines.join('\\n')\n}\n\n/**\n * What a BUILD job's plan is told (AGL-3616): that one request becomes pages,\n * creations and items, how many pages it may hold, and the item operations\n * this site has with their arguments. On the job's own turn, never a cached\n * system block, because the operations are per site.\n */\nexport function aiPlanBuildLines(\n job: Pick<AiJob, 'kind'>,\n capabilities: AiPlanCapabilities | null,\n ops: AiBuildOps | null,\n): string[] {\n if (job.kind !== 'build') return []\n const pages = aiBuildPageLimit(capabilities?.freeTaste === true)\n return [\n `This is a build from one request: plan each page it asks for in screens (at most ${pages}), each new layout, form, component or email design in create, and anything else in items. Plan only what the request asks for; reuse what the site has.`,\n 'A page section that shows a form or an item places it: put its new:<name> in that section\\'s uses. An item built after another lists it in dependsOn.',\n ...(ops ? aiBuildOpLines(ops, AI_BUILD_STRUCTURAL_OPS) : []),\n ]\n}\n\n/**\n * What a SITE job's plan is told beside the inventory (AGL-3594): the pages\n * the site already has and that their addresses are taken, which one — the\n * untouched starter home — a planned home page at `/` replaces, the Free page\n * cap and its guidance, and that a plan is an outline.\n *\n * A site job only. A new site is born with a published home page at `/`\n * (AGL-3497), and a plan that did not know it could replace it planned its own\n * home there and was refused for the clash on every new site. Kept off a page\n * job's turn, whose length the Free page's wall is proven at.\n */\nexport function aiPlanSiteLines(\n job: Pick<AiJob, 'kind'>,\n inventory: AiSiteInventory | null,\n capabilities: AiPlanCapabilities | null,\n): string[] {\n if (job.kind !== 'site') return []\n const lines: string[] = []\n const pages = (inventory?.screens ?? []).filter((screen) => !screen.template)\n const starter = pages.find((screen) => screen.replaceable)\n if (pages.length) {\n lines.push('Pages the site already has; their addresses are taken unless a line says otherwise:')\n for (const page of pages) {\n lines.push(\n page.replaceable\n ? `- ${page.name} at ${page.slug}: the starter home page the site was created with. Plan this site's home page at / and it replaces this one.`\n : `- ${page.name} at ${page.slug}`,\n )\n }\n if (!starter && pages.some((page) => page.slug.trim() === '/' || page.slug.trim() === '')) {\n lines.push(\"The home page at / is the owner's own and stays: give every page you plan another address.\")\n }\n }\n const cap = capabilities?.freeSitePages\n if (cap !== undefined) {\n const sections = aiFreeSiteSectionsWithin(\n { layouts: (inventory?.layouts.length ?? 0) ? 0 : 1, pages: cap },\n FREE_AI_TASTE_CREDITS_PER_MONTH,\n )\n lines.push(\n `This is a Free workspace: plan at most ${cap} ${cap === 1 ? 'page' : 'pages'} — the home page at / and the one page the brief most needs, such as services, booking or contact — with at most ${sections} sections across them.${aiPlanCanPlaceForm(inventory, capabilities) ? ' Put the contact form on one of them.' : ''}`,\n )\n }\n lines.push(\n \"Keep the plan an outline: each page's title, address, a short search title and description, and its sections named in a few words. The build writes the copy.\",\n )\n return lines\n}\n\n/**\n * What a TEMPLATE job's plan is told its creation's `fields` are (AGL-3143\n * §11): the subject's binding tokens, listed so the planner promises only\n * what the page can fill and the build can be held to it\n * (`aiPlanTemplateTokenViolations`).\n *\n * ⛔ It rides the job's own turn and NOT the `fields` description in the plan\n * tool, which every kind's request caches. Written there it read better and\n * cost 40 tokens of the shared prefix — 2,980 to 3,020 — which is one credit\n * of the Free page's 300-credit wall, taking the room it keeps for a re-asked\n * section from 45 credits to 44 and breaking `ai-job-free-page.spec.ts`. A\n * page job must not pay for a sentence about templates.\n *\n * The list is the tokens a reader sees, never the whole catalog (AGL-3143\n * §16). Offered a slug and the publish timestamp, a live plan promised them,\n * and its build kept the promise the only way a slug can be kept: it printed\n * \"entry slug: {{entry.slug}}\" on every article.\n */\nexport function aiPlanTemplateTokenLines(job: Pick<AiJob, 'kind' | 'inputs'>): string[] {\n if (job.kind !== 'template') return []\n const subject = (job.inputs ?? {})['subject']\n const definition =\n typeof subject === 'string'\n ? AI_TEMPLATE_SUBJECT_DEFINITIONS[subject as AiTemplateSubject]\n : undefined\n if (!definition) return []\n return [\n `The template's fields are the binding tokens its page shows a reader, each one of: ${aiTemplateShownTokens(\n definition,\n ).join(', ')}. A link or picture token is shown by the link or picture holding it. Promise only what the page fills.`,\n ]\n}\n\n/** A kind that builds only some plans: the creations it makes, and the shapes it refuses. */\nexport interface AiJobPlanScope extends AiPlanJobScope {\n /** Why a job of the kind cannot build a plan of this shape; `null` when it can. Pure. */\n shapeRefusal: (plan: AiBuildPlan, options?: { freeTaste?: boolean }) => string | null\n}\n\n/**\n * The kinds whose confirm door builds only some plans (AGL-3030). A page job\n * builds one screen and a scaffold four to eight; each builds only the\n * creations its list names. A template, layout, component, form or email job\n * builds its own record and what that record places (AGL-3143 §15,\n * `AI_JOB_CREATE_KINDS`), and holds no plan to a shape.\n */\nexport const AI_JOB_PLAN_SCOPES: Readonly<Partial<Record<AiJobKind, AiJobPlanScope>>> = {\n page: { noun: 'a page job', creates: AI_PAGE_CREATE_KINDS, shapeRefusal: aiPagePlanShapeRefusal },\n // A build from one request (AGL-3616): its operations are judged against\n // the site's registry by the step, which reads it (`aiBuildPlanViolations`).\n build: {\n noun: 'a build',\n creates: AI_BUILD_CREATE_KINDS,\n shapeRefusal: (plan, options) => aiBuildPlanShapeRefusal(plan, { freeTaste: options?.freeTaste }),\n },\n site: { noun: 'a site scaffold', creates: AI_SITE_CREATE_KINDS, shapeRefusal: aiSitePlanShapeRefusal },\n ...Object.fromEntries(\n Object.entries(AI_JOB_CREATE_KINDS).map(([kind, creates]) => [\n kind,\n { noun: AI_JOB_CREATE_NOUNS[kind as AiJobKind] as string, creates, shapeRefusal: () => null },\n ]),\n ),\n}\n\n/**\n * What the plan step holds beyond the doctrine's plan rules, as the\n * violations the plan's one re-ask names: the players the plan lists against\n * the brief it answers (AGL-3433), which only this step reads beside the plan,\n * and a kind's shape refusal.\n */\nfunction planViolations(\n scope: AiJobPlanScope | null,\n brief: string,\n freeTaste = false,\n ops: AiBuildOps | null = null,\n): (plan: AiBuildPlan) => AiDoctrineViolation[] {\n return (plan) => {\n // A build's plan is held to the operations this site has (AGL-3616):\n // an unknown op, arguments its schema refuses, a cycle or a reference\n // nothing makes are re-asked once like every other plan rule.\n const message = ops\n ? aiBuildPlanShapeRefusal(plan, { freeTaste, ops })\n : (scope?.shapeRefusal(plan, { freeTaste }) ?? null)\n return [\n ...aiPlanEmbedBriefViolations(plan, brief),\n ...(message ? [{ rule: null, code: 'plan-job-shape', message }] : []),\n ]\n }\n}\n\n/**\n * The inventory names of every id the plan references, so the proposal reads\n * \"the Services layout\" rather than an id — kept on the plan because the\n * inventory is not read again when the member opens it.\n */\nexport function aiPlanLabels(\n plan: AiBuildPlan,\n inventory: AiSiteInventory | null,\n): Record<string, string> {\n const names = new Map<string, string>()\n for (const rows of [\n inventory?.components,\n inventory?.layouts,\n inventory?.templates,\n inventory?.forms,\n inventory?.datasets,\n inventory?.collections,\n inventory?.screens,\n ]) {\n for (const row of rows ?? []) names.set(row.id, row.name)\n }\n const refs = [\n ...plan.reuse.map((entry) => entry.id),\n ...plan.create.map((entry) => entry.duplicateOf),\n ...plan.screens.flatMap((screen) => [\n screen.layout,\n screen.template,\n screen.duplicateOf,\n ...screen.sections.flatMap((section) => section.uses),\n ]),\n ]\n const labels: Record<string, string> = {}\n for (const ref of refs) {\n if (!ref || isAiPlanNewRef(ref)) continue\n const name = names.get(ref)\n if (name) labels[ref] = name\n }\n return labels\n}\n\n/* ------------------------------------------------------------------------ *\n * Reusing an identical brief's plan\n * ------------------------------------------------------------------------ */\n\n/**\n * How long a plan may be reused for (AGL-2937).\n *\n * The window is what makes reuse safe rather than merely cheap. The key\n * already covers everything the request said — the brief, the inputs, the\n * model and the prompt as rendered, site inventory included — so a plan is\n * reused only when nothing the model was shown has changed. What the key\n * cannot see is the world outside the request: a page published, a component\n * renamed after the inventory was read, a member who meant something\n * different the second time. Fifteen minutes is short enough that the answer\n * is still the one the site would give, and long enough to cover what reuse\n * is actually for — the same brief run twice in a sitting, a job resubmitted\n * after a refused reservation, two members starting the same work.\n */\nexport const AI_PLAN_REUSE_WINDOW_MS = 15 * 60 * 1_000\n\n/** Jobs one lookup reads. More than one can share a key; the newest plan wins. */\nexport const AI_PLAN_REUSE_CANDIDATES = 5\n\n/** A job whose plan might be reused, as the finder reports it. */\nexport interface AiJobPlanCandidate {\n jobId: string\n status: AiJobStatus\n plan: AiJobPlan\n}\n\n/**\n * The digest a plan is reused by: the whole request, never the answer.\n *\n * It hashes what the model was asked and what it was shown — the job's kind\n * and site, the user turn (which carries the trimmed brief and every scalar\n * input), the model that would answer, every rendered system block including\n * the site inventory, and the tool's schema. Two requests that hash the same\n * would have been sent the same bytes to the same model, so the second can\n * keep the first's answer.\n *\n * The version tag is the escape hatch: anything that changes what a key\n * MEANS, rather than what it covers, bumps it and strands every old key\n * harmlessly, since a key nothing matches simply asks the model.\n */\nexport function aiJobPlanKey(input: {\n job: Pick<AiJob, 'kind' | 'hostId'>\n prompt: string\n model: string\n system: readonly AiSystemBlock[]\n /** The plan tool the request offers (AGL-3433); the plain one when absent. */\n tool?: AiTool\n}): string {\n const digest = createHash('sha256')\n for (const part of [\n 'plan.v1',\n input.job.kind,\n input.job.hostId ?? '',\n input.model,\n input.prompt,\n ...input.system.map((block) => block.text),\n JSON.stringify(input.tool ?? AI_BUILD_PLAN_TOOL),\n ]) {\n // Length-prefixed, so two different splits of the same characters cannot\n // collide by running into one another.\n digest.update(`${part.length}:${part}\\u0000`)\n }\n return digest.digest('hex')\n}\n\n/** A job that could not have produced a reusable plan, whatever its key says. */\nconst UNREUSABLE: readonly AiJobStatus[] = ['canceled', 'failed']\n\nfunction planMillis(plan: AiJobPlan): number | null {\n const at = plan.proposedAt as unknown\n if (at instanceof Date) return at.getTime()\n if (at && typeof (at as { toMillis?: unknown }).toMillis === 'function') {\n return (at as { toMillis(): number }).toMillis()\n }\n return null\n}\n\n/**\n * The newest plan worth reusing out of what the finder returned: another\n * job's, still proposed or already confirmed, on a job that was neither\n * canceled nor failed, proposed inside the window.\n *\n * A canceled or failed job is excluded even though its plan may be perfectly\n * good: those are the jobs a member walked away from, and handing their plan\n * to the next one would make a rejected answer look like a fresh one.\n */\nexport function aiReusablePlan(\n candidates: readonly AiJobPlanCandidate[],\n context: { jobId: string; now: Date },\n): AiJobPlanCandidate | null {\n const floor = context.now.getTime() - AI_PLAN_REUSE_WINDOW_MS\n let best: AiJobPlanCandidate | null = null\n let bestAt = -1\n for (const candidate of candidates) {\n if (candidate.jobId === context.jobId) continue\n if (UNREUSABLE.includes(candidate.status)) continue\n if (candidate.plan.status !== 'proposed' && candidate.plan.status !== 'confirmed') continue\n const at = planMillis(candidate.plan)\n if (at === null || at < floor || at > context.now.getTime()) continue\n if (at > bestAt) {\n best = candidate\n bestAt = at\n }\n }\n return best\n}\n\nexport type AiJobPlanFinder = (\n orgId: string,\n key: string,\n firestore?: FirebaseFirestore.Firestore,\n) => Promise<AiJobPlanCandidate[]>\n\n/**\n * The finder the step uses in production: an equality on `plan.key` inside\n * the org's own jobs.\n *\n * One equality on one field, with no ordering beside it, so Firestore's\n * automatic single-field index answers it and no composite index is deployed.\n * The window and the statuses are applied in memory instead, which is what\n * keeps it that way.\n */\nexport const findAiJobsByPlanKey: AiJobPlanFinder = async (orgId, key, firestore) => {\n if (!firestore) return []\n const snapshot = await firestore\n .collection('orgs')\n .doc(orgId)\n .collection(AI_JOBS_COLLECTION)\n .where('plan.key', '==', key)\n .limit(AI_PLAN_REUSE_CANDIDATES)\n .get()\n return snapshot.docs.flatMap((doc) => {\n const data = doc.data() as { status?: AiJobStatus; plan?: AiJobPlan | null }\n return data.plan\n ? [{ jobId: doc.id, status: data.status ?? 'queued', plan: data.plan }]\n : []\n })\n}\n\n/** What a job may create on its site, read for the plan step; `null` for no site. */\nexport type AiPlanCapabilitiesReader = (input: {\n job: AiJob\n org: Partial<AglynOrgBilling> | null\n firestore: FirebaseFirestore.Firestore\n}) => Promise<AiPlanCapabilities | null>\n\n/** The reader the step uses in production: the draft bands' own arithmetic, for the job's site. */\nexport const readAiJobPlanCapabilities: AiPlanCapabilitiesReader = async ({ job, org, firestore }) =>\n job.hostId ? readAiPlanCapabilities(firestore, { hostId: job.hostId, org }) : null\n\nexport interface AiJobPlanStepDeps {\n /** The inventory reader; specs hand in a fake. */\n readInventory?: typeof readSiteInventory\n /** The reuse lookup; specs hand in a fake, and `null` turns reuse off. */\n findPlansByKey?: AiJobPlanFinder | null\n /** What the job may create on its site (AGL-3030); specs and the eval recorder hand in their own. */\n readCapabilities?: AiPlanCapabilitiesReader\n /** The kind's admission, asked of a plan before it is kept; the registry's otherwise. */\n admissionRefusal?: typeof aiJobAdmissionRefusal\n /** A build's operations on its site (AGL-3616); the registry and its gates otherwise. */\n readOps?: AiBuildOpsReader\n}\n\n/** What a build may plan on its site (AGL-3616). */\nexport type AiBuildOpsReader = (input: {\n job: AiJob\n org: Partial<AglynOrgBilling> | null\n firestore: FirebaseFirestore.Firestore\n freeTaste: boolean\n}) => Promise<AiBuildOps>\n\n/** The reader the step uses in production: the registry, gated for the job's site. */\nexport const readAiBuildOps: AiBuildOpsReader = async ({ job, org, firestore, freeTaste }) => {\n const host = job.hostId\n ? (((await firestore.collection('hosts').doc(job.hostId).get()).data() ?? null) as Record<string, unknown> | null)\n : null\n return aiBuildOps({ orgId: job.orgId, hostId: job.hostId ?? null, org, host, freeTaste })\n}\n\n/**\n * A build plan's items with what each can cost (AGL-3616), from its\n * capability, recorded as the plan is kept so the console's estimate and the\n * confirm door read one figure without the registry.\n */\nexport function aiPlanWithItemCredits<T extends AiBuildPlan>(ops: AiBuildOps | null, plan: T): T {\n if (!ops || !plan.items?.length) return plan\n return {\n ...plan,\n items: plan.items.map((item) => {\n const capability = ops.get(item.op)\n return capability ? { ...item, credits: Math.max(0, Math.floor(capability.estimateCredits(item.args))) } : item\n }),\n }\n}\n\nexport function createAiJobPlanStep(deps: AiJobPlanStepDeps = {}): AiJobStepRunner {\n const readInventory = deps.readInventory ?? readSiteInventory\n const findPlansByKey =\n deps.findPlansByKey === undefined ? findAiJobsByPlanKey : deps.findPlansByKey\n const readCapabilities = deps.readCapabilities ?? readAiJobPlanCapabilities\n const admissionRefusal = deps.admissionRefusal ?? aiJobAdmissionRefusal\n const readOps = deps.readOps ?? readAiBuildOps\n return async ({ job, now, signal, firestore, modelFor, org: orgDocument }) => {\n const org = (orgDocument ?? null) as Partial<AglynOrgBilling> | null\n const [inventory, workspace] = await Promise.all([\n job.hostId ? readInventory(job.orgId, job.hostId, { firestore }) : Promise.resolve(null),\n readCapabilities({ job, org, firestore }),\n ])\n const scope = AI_JOB_PLAN_SCOPES[job.kind] ?? null\n const capabilities = aiSitePlanCapabilities(\n job,\n workspace ? aiPlanCapabilitiesForJob(workspace, scope) : null,\n )\n const freeTaste = capabilities?.freeTaste === true\n // A build's operations, as this site has them (AGL-3616).\n const ops = job.kind === 'build' ? await readOps({ job, org, firestore, freeTaste }) : null\n const site = job.kind === 'site'\n // The model switch's answer for this job (AGL-2942): the creator's pick\n // where the plan, the org restriction and the allotment allowlists allow\n // it, and Auto held to those same lists otherwise. Without a resolver the\n // doctrine asks the routing table itself. A Free site plans on its\n // provider's fast tier (AGL-3594), unless the creator picked a model.\n const model = aiSitePlanModel(job, modelFor?.('job.plan'), freeTaste)\n const route = AI_ROUTING_TABLE['job.plan']\n const prompt = aiJobPlanPrompt(job, capabilities, inventory, ops)\n\n /**\n * The confirm door's answer for this plan, asked before the plan is kept\n * (AGL-3030): the kind's own admission, handed the plan as the resume\n * door hands it. A refusal fails the job with the door's sentence; a door\n * that could not answer keeps the plan, since the resume door asks again\n * before anything is built.\n */\n const refusalOnKeep = async (plan: AiJobPlan, outcome: AiJobStepOutcome): Promise<AiJobStepOutcome | null> => {\n let refusal: Awaited<ReturnType<typeof aiJobAdmissionRefusal>> = null\n try {\n refusal = await admissionRefusal(job.kind, {\n firestore,\n orgId: job.orgId,\n hostId: job.hostId ?? null,\n inputs: job.inputs ?? {},\n org,\n plan,\n uid: job.createdBy,\n })\n } catch (error) {\n console.error('ai plan admission failed', { orgId: job.orgId, jobId: job.$id, error })\n }\n return refusal ? { ...outcome, failure: refusal.error } : null\n }\n\n // Reuse before asking (AGL-2937). The key covers the whole request, so a\n // hit is a request that would have been sent the same bytes to the same\n // model; the window covers what the key cannot see. A reused plan spends\n // nothing, so the machine's spent-nothing branch releases the reservation\n // and meters no credit, and the job still stops for the member to confirm\n // — this job's plan is proposed to this member, whatever the last one did\n // with theirs.\n const resolved = model ?? aiModelForStep('job.plan')\n // A brief that asks for a video is offered the plan's list of players\n // (AGL-3433), and a job that may bind a dataset a record template on\n // each screen (AGL-3475).\n const tool = aiBuildPlanToolFor(job.brief, {\n records: Boolean(inventory?.datasets.length) || capabilities?.create.dataset.allowed === true,\n items: job.kind === 'build',\n })\n const key = aiJobPlanKey({\n job,\n prompt,\n model: resolved,\n system: aiDoctrineSystemBlocks(inventory, { instructions: AI_JOB_PLAN_INSTRUCTIONS }),\n tool,\n })\n const reused = findPlansByKey\n ? aiReusablePlan(await findPlansByKey(job.orgId, key, firestore), {\n jobId: job.$id,\n now,\n })\n : null\n if (reused) {\n // The reused plan's draft ids name the other job's drafts; this job's are its own.\n const plan: AiJobPlan = aiPlanWithItemCredits(ops, aiPlanWithDraftIds(job.kind, {\n ...reused.plan,\n status: 'proposed',\n labels: aiPlanLabels(reused.plan, inventory),\n proposedAt: now as unknown as AiJobPlan['proposedAt'],\n confirmedAt: null,\n confirmedBy: null,\n key,\n reusedFrom: reused.jobId,\n }))\n const unspent = aiUnspentOutcome(resolved)\n return (\n (await refusalOnKeep(plan, unspent)) ?? {\n ...unspent,\n plan,\n review: { reason: 'plan', message: AI_JOB_PLAN_REVIEW_COPY, findings: [] },\n }\n )\n }\n\n const result = await runValidatedGeneration('plan', {\n step: 'job.plan',\n ...(model ? { model } : {}),\n instructions: AI_JOB_PLAN_INSTRUCTIONS,\n inventory,\n messages: [{ role: 'user', content: prompt }],\n tool,\n // The routing ceiling, lowered on a tier too slow to look records up,\n // answer and ask again inside the least time the step registered; a\n // scaffold's outline is held to its own, far lower ceiling (AGL-3594).\n maxTokens: aiSitePlanMaxTokens(job, resolved, freeTaste),\n // A scaffold plans an outline without thinking (AGL-3594): the thinking\n // was nearly all of the 13,491 tokens a Free site's plan spent.\n ...(site ? { thinking: 'off' as const } : route.thinking ? { thinking: route.thinking } : {}),\n ...(route.effort ? { effort: route.effort } : {}),\n ...(signal ? { signal } : {}),\n capabilities,\n extend: planViolations(scope, job.brief, freeTaste, ops),\n })\n const spent: AiJobStepOutcome = {\n outputs: [],\n usage: result.usage,\n estCostUsd: result.estCostUsd,\n model: result.model,\n stopReason: result.stopReason,\n ...(result.effort ? { effort: result.effort } : {}),\n }\n if (result.status === 'refused') return { ...spent, refused: true }\n if (result.status === 'needs_input') {\n // Refused by our own checks, after the one re-ask (AGL-3594): the member\n // reads a sentence and an action, staff the rules; the machine gives the\n // credits back (`uncredited`), and on the Free taste Try again says when\n // it cannot work. Whether the give-back was made is the job's to say\n // (`refundedCredits`), so this sentence does not promise it.\n const review = aiDoctrineReview(result)\n const retryRefusal = freeTaste\n ? await aiFreePlanRetryRefusal({ job, org, firestore, now, site })\n : null\n return {\n ...spent,\n uncredited: true,\n review: {\n ...review,\n message: aiPlanFailureCopy({\n kind: job.kind,\n codes: result.violations.map((violation) => violation.code),\n refunded: false,\n }),\n detail: review.message,\n ...(retryRefusal ? { retryRefusal } : {}),\n },\n }\n }\n // Each draft the plan decides is named as the plan is kept, before anything is built (AGL-3079).\n const plan: AiJobPlan = aiPlanWithItemCredits(ops, aiPlanWithDraftIds(job.kind, {\n ...result.value,\n status: 'proposed',\n labels: aiPlanLabels(result.value, inventory),\n // A Date the Admin SDK stores as a timestamp, like every instant the machine writes.\n proposedAt: now as unknown as AiJobPlan['proposedAt'],\n confirmedAt: null,\n confirmedBy: null,\n key,\n }))\n return (\n (await refusalOnKeep(plan, spent)) ?? {\n ...spent,\n plan,\n review: { reason: 'plan', message: AI_JOB_PLAN_REVIEW_COPY, findings: [] },\n }\n )\n }\n}\n\n/**\n * A site job's capabilities on the Free taste (AGL-3594): its plan holds at\n * most the pages the member asked for within the Free band, which the Free\n * wall then holds it to, and it changes no theme — the site was born with\n * one (AGL-3497), and a palette pass is credits the two pages need. Every\n * other job's capabilities pass through.\n */\nexport function aiSitePlanCapabilities(\n job: Pick<AiJob, 'kind' | 'inputs'>,\n capabilities: AiPlanCapabilities | null,\n): AiPlanCapabilities | null {\n if (job.kind !== 'site' || !capabilities?.freeTaste) return capabilities\n const asked = Number((job.inputs ?? {})['pages'])\n const pages =\n Number.isInteger(asked) && asked >= AI_SITE_FREE_PAGES.min\n ? Math.min(asked, AI_SITE_FREE_PAGES.max)\n : AI_SITE_FREE_PAGES.max\n return {\n ...capabilities,\n freeSitePages: pages,\n create: {\n ...capabilities.create,\n 'theme-change': {\n allowed: false,\n left: null,\n reason: \"a Free workspace's site start keeps the theme the site was created with\",\n },\n },\n }\n}\n\n/**\n * The model a plan runs on (AGL-3594): the resolved one, except a Free site\n * plans on its provider's fast tier — an outline the plan rules hold and\n * re-ask, at a fifth of the balanced tier's output rate. A model the creator\n * picked by name stays theirs.\n */\nexport function aiSitePlanModel(\n job: Pick<AiJob, 'kind' | 'model'>,\n resolved: string | undefined,\n freeTaste: boolean,\n): string | undefined {\n if (job.kind !== 'site' || !freeTaste) return resolved\n const picked = typeof job.model === 'string' ? job.model.trim() : ''\n if (picked && picked !== 'auto') return resolved\n const entry = aiCatalogEntry(resolved ?? aiModelForStep('job.plan'))\n return (entry ? aiDefaultModelFor(entry.provider, 'fast') : undefined) ?? resolved\n}\n\n/** The plan's answer ceiling: the step's own, and a scaffold's outline ceiling under it (AGL-3594). */\nexport function aiSitePlanMaxTokens(\n job: Pick<AiJob, 'kind'>,\n model: string,\n freeTaste: boolean,\n): number {\n const ceiling = aiJobPlanMaxTokens(model)\n if (job.kind !== 'site') return ceiling\n return Math.min(ceiling, freeTaste ? AI_SITE_PLAN_MAX_TOKENS.free : AI_SITE_PLAN_MAX_TOKENS.paid)\n}\n\n/**\n * Why trying a Free plan again cannot work this month, or `null` (AGL-3594):\n * the owner's Free allowance left, read off the account month the meter\n * writes net of give-backs, against what a plan of this kind costs at its\n * worst. Read before this step is metered, and the machine gives a refused\n * plan's credits back, so the figure read is the figure left. A read that fails\n * leaves the button on: the reservation still refuses at the wall.\n */\nasync function aiFreePlanRetryRefusal(input: {\n job: AiJob\n org: Partial<AglynOrgBilling> | null\n firestore: FirebaseFirestore.Firestore\n now: Date\n site: boolean\n}): Promise<string | null> {\n const account = freeAssistAccount(input.org as AssistMeteredOrg | null)\n if (!account?.accountUid) return null\n try {\n // The meter's month key, `YYYY-MM` in UTC (`assistUsageMonth`).\n const month = input.now.toISOString().slice(0, 7)\n const snapshot = await freeAccountUsageRef(input.firestore, account.accountUid, month).get()\n const spent = assistCreditsFromUsd(\n assistSpendAfterReturnsUsd(snapshot.get('estCostUsd'), snapshot.get(ASSIST_RETURNED_USD_FIELD)),\n )\n return aiPlanRetryRefusal({\n creditsLeft: FREE_AI_TASTE_CREDITS_PER_MONTH - spent,\n planCredits: input.site ? AI_FREE_SITE_WORST_CASE_CREDITS.plan : AI_FREE_PAGE_WORST_CASE_CREDITS.plan,\n })\n } catch (error) {\n console.error('ai plan retry allowance read failed', { orgId: input.job.orgId, jobId: input.job.$id, error })\n return null\n }\n}\n\nexport const runAiJobPlanStep = createAiJobPlanStep()\n\n/**\n * Registers the plan step every planned kind runs first, with the least time\n * a plan needs; the plugin's console surface calls it.\n */\nexport function registerAiJobPlan(): void {\n registerAiJobPlanStep(runAiJobPlanStep, { minimumMs: AI_JOB_PLAN_STEP_MINIMUM_MS })\n}\n"],"names":["createHash","AI_BUILD_PLAN_TOOL","aiBuildPlanToolFor","isAiPlanNewRef","AI_TEMPLATE_SUBJECT_DEFINITIONS","aiTemplateShownTokens","AI_JOB_CREATE_KINDS","AI_JOB_CREATE_NOUNS","AI_PAGE_CREATE_KINDS","aiPagePlanShapeRefusal","AI_PLAN_NO_FORM_SENTENCE","aiPlanCanPlaceForm","aiPlanCapabilitiesForJob","aiPlanCapabilityLines","AI_FREE_SITE_WORST_CASE_CREDITS","AI_SITE_CREATE_KINDS","AI_SITE_FREE_PAGES","AI_SITE_PLAN_MAX_TOKENS","aiFreeSiteSectionsWithin","aiSitePlanShapeRefusal","aiPlanFailureCopy","aiPlanRetryRefusal","FREE_AI_TASTE_CREDITS_PER_MONTH","aiDoctrineSystemBlocks","runValidatedGeneration","AI_STEP_TIERS","aiCatalogEntry","aiDefaultModelFor","AI_FREE_PAGE_WORST_CASE_CREDITS","aiPlanEmbedBriefViolations","assistCreditsFromUsd","ASSIST_RETURNED_USD_FIELD","assistSpendAfterReturnsUsd","freeAccountUsageRef","freeAssistAccount","AI_ROUTING_TABLE","aiModelForStep","readSiteInventory","AI_BUILD_CREATE_KINDS","AI_BUILD_STRUCTURAL_OPS","aiBuildPageLimit","aiBuildPlanShapeRefusal","aiBuildOpLines","aiBuildOps","aiJobAdmissionRefusal","readAiPlanCapabilities","AI_JOB_BRIEF_MAX_CHARS","aiJobStepBudget","aiDoctrineReview","aiUnspentOutcome","aiPlanWithDraftIds","AI_JOBS_COLLECTION","registerAiJobPlanStep","AI_JOB_PLAN_INSTRUCTIONS","text","AI_JOB_PLAN_STEP_BUDGET","tier","maxTokens","AI_JOB_PLAN_STEP_MINIMUM_MS","minimumMs","aiJobPlanMaxTokens","model","AI_JOB_PLAN_REVIEW_COPY","aiJobPlanPrompt","job","capabilities","inventory","ops","lines","kind","brief","slice","key","value","Object","entries","inputs","push","String","aiPlanTemplateTokenLines","aiPlanSiteLines","aiPlanBuildLines","join","pages","freeTaste","screens","filter","screen","template","starter","find","replaceable","length","page","name","slug","some","trim","cap","freeSitePages","undefined","sections","layouts","subject","definition","AI_JOB_PLAN_SCOPES","noun","creates","shapeRefusal","build","plan","options","site","fromEntries","map","planViolations","scope","message","rule","code","aiPlanLabels","names","Map","rows","components","templates","forms","datasets","collections","row","set","id","refs","reuse","entry","create","duplicateOf","flatMap","layout","section","uses","labels","ref","get","AI_PLAN_REUSE_WINDOW_MS","AI_PLAN_REUSE_CANDIDATES","aiJobPlanKey","input","digest","part","hostId","prompt","system","block","JSON","stringify","tool","update","UNREUSABLE","planMillis","at","proposedAt","Date","getTime","toMillis","aiReusablePlan","candidates","context","floor","now","best","bestAt","candidate","jobId","includes","status","findAiJobsByPlanKey","orgId","firestore","snapshot","collection","doc","where","limit","docs","data","readAiJobPlanCapabilities","org","readAiBuildOps","host","aiPlanWithItemCredits","items","item","capability","op","credits","Math","max","estimateCredits","args","createAiJobPlanStep","deps","readInventory","findPlansByKey","readCapabilities","admissionRefusal","readOps","signal","modelFor","orgDocument","workspace","Promise","all","resolve","aiSitePlanCapabilities","aiSitePlanModel","route","refusalOnKeep","outcome","refusal","uid","createdBy","error","console","$id","failure","resolved","records","Boolean","dataset","allowed","instructions","reused","confirmedAt","confirmedBy","reusedFrom","unspent","review","reason","findings","result","step","messages","role","content","aiSitePlanMaxTokens","thinking","effort","extend","spent","outputs","usage","estCostUsd","stopReason","refused","retryRefusal","aiFreePlanRetryRefusal","uncredited","codes","violations","violation","refunded","detail","asked","Number","isInteger","min","left","picked","provider","ceiling","free","paid","account","accountUid","month","toISOString","creditsLeft","planCredits","runAiJobPlanStep","registerAiJobPlan"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,cAAa;AAExC,SACEC,kBAAkB,EAClBC,kBAAkB,EAClBC,cAAc,QAET,4BAAwB;AAE/B,SACEC,+BAA+B,EAC/BC,qBAAqB,QAEhB,mCAA+B;AACtC,SAASC,mBAAmB,EAAEC,mBAAmB,QAAQ,+BAA2B;AACpF,SAASC,oBAAoB,EAAEC,sBAAsB,QAAQ,0BAAsB;AACnF,SACEC,wBAAwB,EACxBC,kBAAkB,EAClBC,wBAAwB,EACxBC,qBAAqB,QAGhB,mCAA+B;AAEtC,SACEC,+BAA+B,EAC/BC,oBAAoB,EACpBC,kBAAk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O,kBAAkBiH,MAAMwC,GAAG;IAC3C,IAAI,EAACsF,2BAAAA,QAASC,UAAU,GAAE,OAAO;IACjC,IAAI;QACF,gEAAgE;QAChE,MAAMC,QAAQhI,MAAMsB,GAAG,CAAC2G,WAAW,GAAG7M,KAAK,CAAC,GAAG;QAC/C,MAAM4G,WAAW,MAAMlJ,oBAAoBkH,MAAM+B,SAAS,EAAE+F,QAAQC,UAAU,EAAEC,OAAOpI,GAAG;QAC1F,MAAM0G,QAAQ3N,qBACZE,2BAA2BmJ,SAASpC,GAAG,CAAC,eAAeoC,SAASpC,GAAG,CAAChH;QAEtE,OAAOV,mBAAmB;YACxBgQ,aAAa/P,kCAAkCmO;YAC/C6B,aAAanI,MAAMnC,IAAI,GAAGlG,gCAAgCgG,IAAI,GAAGlF,gCAAgCkF,IAAI;QACvG;IACF,EAAE,OAAOgH,OAAO;QACdC,QAAQD,KAAK,CAAC,uCAAuC;YAAE7C,OAAO9B,MAAMnF,GAAG,CAACiH,KAAK;YAAEJ,OAAO1B,MAAMnF,GAAG,CAACgK,GAAG;YAAEF;QAAM;QAC3G,OAAO;IACT;AACF;AAEA,OAAO,MAAMyD,mBAAmB/E,sBAAqB;AAErD;;;CAGC,GACD,OAAO,SAASgF;IACdpO,sBAAsBmO,kBAAkB;QAAE5N,WAAWD;IAA4B;AACnF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-plan-step.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { aiSiteKindOfInputs } from '../model/ai-site-kinds'\nimport { createHash } from 'node:crypto'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport {\n AI_BUILD_PLAN_TOOL,\n aiBuildPlanToolFor,\n isAiPlanNewRef,\n type AiBuildPlan,\n} from '../model/ai-build-plan'\nimport type { AiJob, AiJobKind, AiJobPlan, AiJobStatus } from '../model/ai-jobs.types'\nimport {\n AI_TEMPLATE_SUBJECT_DEFINITIONS,\n aiTemplateShownTokens,\n type AiTemplateSubject,\n} from '../model/ai-template-subjects'\nimport { AI_JOB_CREATE_KINDS, AI_JOB_CREATE_NOUNS } from '../model/ai-job-creations'\nimport { AI_PAGE_CREATE_KINDS, aiPagePlanShapeRefusal } from '../model/ai-page-job'\nimport {\n AI_PLAN_NO_FORM_SENTENCE,\n aiPlanCanPlaceForm,\n aiPlanCapabilitiesForJob,\n aiPlanCapabilityLines,\n type AiPlanCapabilities,\n type AiPlanJobScope,\n} from '../model/ai-plan-capabilities'\nimport type { AiSiteInventory } from '../model/ai-site-inventory'\nimport {\n AI_FREE_SITE_WORST_CASE_CREDITS,\n AI_SITE_CREATE_KINDS,\n AI_SITE_FREE_PAGES,\n AI_SITE_PLAN_MAX_TOKENS,\n aiFreeSiteSectionsWithin,\n aiSiteNameSentence,\n aiSitePlanShapeRefusal,\n} from '../model/ai-site-job'\nimport { aiPlanFailureCopy, aiPlanRetryRefusal } from '../model/ai-job-failure-copy'\nimport { FREE_AI_TASTE_CREDITS_PER_MONTH } from '../plan-entitlements'\nimport { aiDoctrineSystemBlocks, runValidatedGeneration } from '../runtime/ai-doctrine'\nimport { AI_STEP_TIERS, aiCatalogEntry, aiDefaultModelFor } from '../providers/catalog'\nimport {\n AI_FREE_PAGE_WORST_CASE_CREDITS,\n aiPlanEmbedBriefViolations,\n type AiDoctrineViolation,\n} from '../runtime/ai-doctrine-validators'\nimport { assistCreditsFromUsd } from '../usage/assist-credits'\nimport { ASSIST_RETURNED_USD_FIELD, assistSpendAfterReturnsUsd } from '../usage/assist-credit-returns'\nimport { freeAccountUsageRef, freeAssistAccount, type AssistMeteredOrg } from '../usage/assist-free-taste'\nimport { AI_ROUTING_TABLE, aiModelForStep } from '../providers/routing'\nimport type { AiTool } from '../providers/contract'\nimport type { AiSystemBlock } from '../runtime/ai-runtime'\nimport { readSiteInventory } from '../runtime/site-inventory'\nimport { readAiSiteContext } from '../runtime/site-context'\nimport { aiInstructionsWithSiteContext, type AiSiteContextInput } from '../model/ai-site-context'\nimport {\n AI_BUILD_CREATE_KINDS,\n AI_BUILD_STRUCTURAL_OPS,\n aiBuildPageLimit,\n aiBuildPlanShapeRefusal,\n type AiBuildOps,\n} from '../model/ai-build-job'\nimport { aiBuildOpLines, aiBuildOps } from './ai-build-capabilities'\nimport { aiJobAdmissionRefusal } from './ai-job-admission'\nimport { readAiPlanCapabilities } from './ai-job-drafts'\nimport {\n AI_JOB_BRIEF_MAX_CHARS,\n type AiJobStepOutcome,\n type AiJobStepRunner,\n} from './ai-job-text-step'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { aiDoctrineReview, aiUnspentOutcome } from './ai-job-generation'\nimport { aiPlanWithDraftIds } from './ai-job-draft-ids'\nimport { AI_JOBS_COLLECTION, registerAiJobPlanStep } from './ai-jobs'\n\n/**\n * The plan step (AGL-2935): the first step of every job that builds site\n * structure. Before a node is generated, the model answers with a typed plan\n * — what the site already has that the job reuses, what it creates and why,\n * and the screens it builds from them — held to the doctrine's plan rules\n * against the site's inventory and re-asked once when it breaks one.\n *\n * A plan that passes is kept on the job, and the job stops for review: the\n * member reads what it will build before a credit is spent building it, and\n * confirms through the resume door. A plan that still breaks a rule on its\n * re-ask stops the job the same way, with the rules named. Either way the\n * step writes nothing itself; the machine records the plan, the spend and\n * the stop, as it records every step.\n *\n * ── Told what it may create, refused what it cannot build (AGL-3030) ─────\n *\n * Before it asks, the step reads what the job may create on its site: the\n * workspace's plan, the site's counts against its limits, and — for a kind\n * that builds only some plans — what the job builds itself. The user turn\n * states it, the plan rules refuse a creation outside it with the one re-ask,\n * and where the workspace keeps no reusable components they accept the page\n * built inline. A plan the confirm door would still refuse — the kind's own\n * admission, handed the plan, as the resume door hands it — is refused HERE,\n * before a member is shown a Confirm: the job fails with the door's sentence,\n * its plan is not kept, and it holds nothing.\n */\n\n/** The plan step's own instructions, cached after the doctrine. */\nexport const AI_JOB_PLAN_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text:\n 'You plan what a website builder job will build, before anything is built. You are given the kind of job and the brief from the person who owns the site. ' +\n 'Answer with submit_build_plan: what the site inventory already has that the job reuses, what it must create and why nothing listed will do, and each page it builds (the screens list) with its layout, template, slug, search title, search description and sections from top to bottom. ' +\n 'Refer to inventory records by id and to what the plan creates as new:<name>. Plan only what the brief asks for: a component, layout, template, form or email job plans no pages unless the brief asks for them, and a page job plans exactly one page.',\n },\n]\n\n/**\n * The plan step's time (AGL-3026, AGL-3036): its two inventory-lookup rounds,\n * its answer and its re-ask at the routing table's ceiling for `job.plan`, on\n * the tier that step kind is served from, with the step's reads and writes,\n * at the rates `ai-job-budget.ts` assumes — fitted to what a beat can give a\n * step, so the served tier asks a little under the routing ceiling.\n */\nexport const AI_JOB_PLAN_STEP_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS['job.plan'],\n maxTokens: AI_ROUTING_TABLE['job.plan'].maxTokens,\n})\n\n/**\n * The least time a plan needs before it starts. Registered with the step, so\n * an inline door never starts a plan. A plan thinks before it answers and\n * routinely runs past an inline door's budget, and a provider call that\n * budget cuts off is still generated and billed upstream while the meter\n * records nothing. The beat starts a plan only with this much of its own\n * budget left, and a spec holds it inside that budget.\n */\nexport const AI_JOB_PLAN_STEP_MINIMUM_MS = AI_JOB_PLAN_STEP_BUDGET.minimumMs\n\n/**\n * The plan's answer ceiling on the model a job runs: the most whose worst\n * case fits the least time the step registered, and never more than the\n * routing table's. A model the catalog does not know is planned at the\n * slowest.\n */\nexport function aiJobPlanMaxTokens(model: string): number {\n return AI_JOB_PLAN_STEP_BUDGET.maxTokens(model)\n}\n\n/** What the member reads while a plan waits for them. */\nexport const AI_JOB_PLAN_REVIEW_COPY =\n 'The plan is ready. Review what the job will reuse and create, then confirm it to build.'\n\n/**\n * The job as the plan step's user turn: its kind, its brief, its scalar\n * inputs and, where the job read them, what it may create on its site\n * (AGL-3030). Per workspace and per site, which is why they ride here and\n * never in a system block the platform's cache entry is keyed on.\n */\nexport function aiJobPlanPrompt(\n job: Pick<AiJob, 'kind' | 'brief' | 'inputs'>,\n capabilities: AiPlanCapabilities | null = null,\n inventory: AiSiteInventory | null = null,\n ops: AiBuildOps | null = null,\n): string {\n const lines = [`Job kind: ${job.kind}`, `Brief: ${job.brief.slice(0, AI_JOB_BRIEF_MAX_CHARS)}`]\n for (const [key, value] of Object.entries(job.inputs ?? {})) {\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n lines.push(`${key}: ${String(value)}`)\n }\n }\n if (capabilities) lines.push(...aiPlanCapabilityLines(capabilities))\n // A form is a saved form or none (AGL-3596): said where the site read has\n // none to place and the job may create none.\n if (capabilities && inventory && !aiPlanCanPlaceForm(inventory, capabilities)) {\n lines.push(AI_PLAN_NO_FORM_SENTENCE)\n }\n lines.push(...aiPlanTemplateTokenLines(job))\n lines.push(...aiPlanSiteLines(job, inventory, capabilities))\n lines.push(...aiPlanBuildLines(job, capabilities, ops))\n return lines.join('\\n')\n}\n\n/**\n * What a BUILD job's plan is told (AGL-3616): that one request becomes pages,\n * creations and items, how many pages it may hold, and the item operations\n * this site has with their arguments. On the job's own turn, never a cached\n * system block, because the operations are per site.\n */\nexport function aiPlanBuildLines(\n job: Pick<AiJob, 'kind'>,\n capabilities: AiPlanCapabilities | null,\n ops: AiBuildOps | null,\n): string[] {\n if (job.kind !== 'build') return []\n const pages = aiBuildPageLimit(capabilities?.freeTaste === true)\n return [\n `This is a build from one request: plan each page it asks for in screens (at most ${pages}), each new layout, form, component or email design in create, and anything else in items. Plan only what the request asks for; reuse what the site has.`,\n 'A page section that shows a form or an item places it: put its new:<name> in that section\\'s uses. An item built after another lists it in dependsOn.',\n ...(ops ? aiBuildOpLines(ops, AI_BUILD_STRUCTURAL_OPS) : []),\n ]\n}\n\n/**\n * What a SITE job's plan is told beside the inventory (AGL-3594): the pages\n * the site already has and that their addresses are taken, which one — the\n * untouched starter home — a planned home page at `/` replaces, the Free page\n * cap and its guidance, and that a plan is an outline.\n *\n * A site job only. A new site is born with a published home page at `/`\n * (AGL-3497), and a plan that did not know it could replace it planned its own\n * home there and was refused for the clash on every new site. Kept off a page\n * job's turn, whose length the Free page's wall is proven at.\n */\nexport function aiPlanSiteLines(\n job: Pick<AiJob, 'kind'> & Partial<Pick<AiJob, 'inputs'>>,\n inventory: AiSiteInventory | null,\n capabilities: AiPlanCapabilities | null,\n): string[] {\n if (job.kind !== 'site') return []\n const lines: string[] = []\n // The business's own name, as the name to use (AGL-3596): the plan's search\n // titles carry it, and an input line alone left the model free to coin one.\n const name = job.inputs?.['businessName']\n if (typeof name === 'string' && name.trim()) lines.push(aiSiteNameSentence(name.trim()))\n const pages = (inventory?.screens ?? []).filter((screen) => !screen.template)\n const starter = pages.find((screen) => screen.replaceable)\n if (pages.length) {\n lines.push('Pages the site already has; their addresses are taken unless a line says otherwise:')\n for (const page of pages) {\n lines.push(\n page.replaceable\n ? `- ${page.name} at ${page.slug}: the starter home page the site was created with. Plan this site's home page at / and it replaces this one.`\n : `- ${page.name} at ${page.slug}`,\n )\n }\n if (!starter && pages.some((page) => page.slug.trim() === '/' || page.slug.trim() === '')) {\n lines.push(\"The home page at / is the owner's own and stays: give every page you plan another address.\")\n }\n }\n const cap = capabilities?.freeSitePages\n if (cap !== undefined) {\n const sections = aiFreeSiteSectionsWithin(\n { layouts: (inventory?.layouts.length ?? 0) ? 0 : 1, pages: cap },\n FREE_AI_TASTE_CREDITS_PER_MONTH,\n )\n lines.push(\n `This is a Free workspace: plan at most ${cap} ${cap === 1 ? 'page' : 'pages'} — the home page at / and the one page the brief most needs, such as services, booking or contact — with at most ${sections} sections across them.${aiPlanCanPlaceForm(inventory, capabilities) ? ' Put the contact form on one of them.' : ''}`,\n )\n }\n // The kind of site the person picked (AGL-3660): the pages it usually has.\n const kind = aiSiteKindOfInputs(job.inputs)\n if (kind) lines.push(`This is a ${kind.label.toLowerCase()} site. ${kind.pages}`)\n lines.push(\n \"Keep the plan an outline: each page's title, address, a short search title and description, and its sections named in a few words. The build writes the copy.\",\n )\n return lines\n}\n\n/**\n * What a TEMPLATE job's plan is told its creation's `fields` are (AGL-3143\n * §11): the subject's binding tokens, listed so the planner promises only\n * what the page can fill and the build can be held to it\n * (`aiPlanTemplateTokenViolations`).\n *\n * ⛔ It rides the job's own turn and NOT the `fields` description in the plan\n * tool, which every kind's request caches. Written there it read better and\n * cost 40 tokens of the shared prefix — 2,980 to 3,020 — which is one credit\n * of the Free page's 300-credit wall, taking the room it keeps for a re-asked\n * section from 45 credits to 44 and breaking `ai-job-free-page.spec.ts`. A\n * page job must not pay for a sentence about templates.\n *\n * The list is the tokens a reader sees, never the whole catalog (AGL-3143\n * §16). Offered a slug and the publish timestamp, a live plan promised them,\n * and its build kept the promise the only way a slug can be kept: it printed\n * \"entry slug: {{entry.slug}}\" on every article.\n */\nexport function aiPlanTemplateTokenLines(job: Pick<AiJob, 'kind' | 'inputs'>): string[] {\n if (job.kind !== 'template') return []\n const subject = (job.inputs ?? {})['subject']\n const definition =\n typeof subject === 'string'\n ? AI_TEMPLATE_SUBJECT_DEFINITIONS[subject as AiTemplateSubject]\n : undefined\n if (!definition) return []\n return [\n `The template's fields are the binding tokens its page shows a reader, each one of: ${aiTemplateShownTokens(\n definition,\n ).join(', ')}. A link or picture token is shown by the link or picture holding it. Promise only what the page fills.`,\n ]\n}\n\n/** A kind that builds only some plans: the creations it makes, and the shapes it refuses. */\nexport interface AiJobPlanScope extends AiPlanJobScope {\n /** Why a job of the kind cannot build a plan of this shape; `null` when it can. Pure. */\n shapeRefusal: (plan: AiBuildPlan, options?: { freeTaste?: boolean }) => string | null\n}\n\n/**\n * The kinds whose confirm door builds only some plans (AGL-3030). A page job\n * builds one screen and a scaffold four to eight; each builds only the\n * creations its list names. A template, layout, component, form or email job\n * builds its own record and what that record places (AGL-3143 §15,\n * `AI_JOB_CREATE_KINDS`), and holds no plan to a shape.\n */\nexport const AI_JOB_PLAN_SCOPES: Readonly<Partial<Record<AiJobKind, AiJobPlanScope>>> = {\n page: { noun: 'a page job', creates: AI_PAGE_CREATE_KINDS, shapeRefusal: aiPagePlanShapeRefusal },\n // A build from one request (AGL-3616): its operations are judged against\n // the site's registry by the step, which reads it (`aiBuildPlanViolations`).\n build: {\n noun: 'a build',\n creates: AI_BUILD_CREATE_KINDS,\n shapeRefusal: (plan, options) => aiBuildPlanShapeRefusal(plan, { freeTaste: options?.freeTaste }),\n },\n site: { noun: 'a site scaffold', creates: AI_SITE_CREATE_KINDS, shapeRefusal: aiSitePlanShapeRefusal },\n ...Object.fromEntries(\n Object.entries(AI_JOB_CREATE_KINDS).map(([kind, creates]) => [\n kind,\n { noun: AI_JOB_CREATE_NOUNS[kind as AiJobKind] as string, creates, shapeRefusal: () => null },\n ]),\n ),\n}\n\n/**\n * What the plan step holds beyond the doctrine's plan rules, as the\n * violations the plan's one re-ask names: the players the plan lists against\n * the brief it answers (AGL-3433), which only this step reads beside the plan,\n * and a kind's shape refusal.\n */\nfunction planViolations(\n scope: AiJobPlanScope | null,\n brief: string,\n freeTaste = false,\n ops: AiBuildOps | null = null,\n): (plan: AiBuildPlan) => AiDoctrineViolation[] {\n return (plan) => {\n // A build's plan is held to the operations this site has (AGL-3616):\n // an unknown op, arguments its schema refuses, a cycle or a reference\n // nothing makes are re-asked once like every other plan rule.\n const message = ops\n ? aiBuildPlanShapeRefusal(plan, { freeTaste, ops })\n : (scope?.shapeRefusal(plan, { freeTaste }) ?? null)\n return [\n ...aiPlanEmbedBriefViolations(plan, brief),\n ...(message ? [{ rule: null, code: 'plan-job-shape', message }] : []),\n ]\n }\n}\n\n/**\n * The inventory names of every id the plan references, so the proposal reads\n * \"the Services layout\" rather than an id — kept on the plan because the\n * inventory is not read again when the member opens it.\n */\nexport function aiPlanLabels(\n plan: AiBuildPlan,\n inventory: AiSiteInventory | null,\n): Record<string, string> {\n const names = new Map<string, string>()\n for (const rows of [\n inventory?.components,\n inventory?.layouts,\n inventory?.templates,\n inventory?.forms,\n inventory?.datasets,\n inventory?.collections,\n inventory?.screens,\n ]) {\n for (const row of rows ?? []) names.set(row.id, row.name)\n }\n const refs = [\n ...plan.reuse.map((entry) => entry.id),\n ...plan.create.map((entry) => entry.duplicateOf),\n ...plan.screens.flatMap((screen) => [\n screen.layout,\n screen.template,\n screen.duplicateOf,\n ...screen.sections.flatMap((section) => section.uses),\n ]),\n ]\n const labels: Record<string, string> = {}\n for (const ref of refs) {\n if (!ref || isAiPlanNewRef(ref)) continue\n const name = names.get(ref)\n if (name) labels[ref] = name\n }\n return labels\n}\n\n/* ------------------------------------------------------------------------ *\n * Reusing an identical brief's plan\n * ------------------------------------------------------------------------ */\n\n/**\n * How long a plan may be reused for (AGL-2937).\n *\n * The window is what makes reuse safe rather than merely cheap. The key\n * already covers everything the request said — the brief, the inputs, the\n * model and the prompt as rendered, site inventory included — so a plan is\n * reused only when nothing the model was shown has changed. What the key\n * cannot see is the world outside the request: a page published, a component\n * renamed after the inventory was read, a member who meant something\n * different the second time. Fifteen minutes is short enough that the answer\n * is still the one the site would give, and long enough to cover what reuse\n * is actually for — the same brief run twice in a sitting, a job resubmitted\n * after a refused reservation, two members starting the same work.\n */\nexport const AI_PLAN_REUSE_WINDOW_MS = 15 * 60 * 1_000\n\n/** Jobs one lookup reads. More than one can share a key; the newest plan wins. */\nexport const AI_PLAN_REUSE_CANDIDATES = 5\n\n/** A job whose plan might be reused, as the finder reports it. */\nexport interface AiJobPlanCandidate {\n jobId: string\n status: AiJobStatus\n plan: AiJobPlan\n}\n\n/**\n * The digest a plan is reused by: the whole request, never the answer.\n *\n * It hashes what the model was asked and what it was shown — the job's kind\n * and site, the user turn (which carries the trimmed brief and every scalar\n * input), the model that would answer, every rendered system block including\n * the site inventory, and the tool's schema. Two requests that hash the same\n * would have been sent the same bytes to the same model, so the second can\n * keep the first's answer.\n *\n * The version tag is the escape hatch: anything that changes what a key\n * MEANS, rather than what it covers, bumps it and strands every old key\n * harmlessly, since a key nothing matches simply asks the model.\n */\nexport function aiJobPlanKey(input: {\n job: Pick<AiJob, 'kind' | 'hostId'>\n prompt: string\n model: string\n system: readonly AiSystemBlock[]\n /** The plan tool the request offers (AGL-3433); the plain one when absent. */\n tool?: AiTool\n}): string {\n const digest = createHash('sha256')\n for (const part of [\n 'plan.v1',\n input.job.kind,\n input.job.hostId ?? '',\n input.model,\n input.prompt,\n ...input.system.map((block) => block.text),\n JSON.stringify(input.tool ?? AI_BUILD_PLAN_TOOL),\n ]) {\n // Length-prefixed, so two different splits of the same characters cannot\n // collide by running into one another.\n digest.update(`${part.length}:${part}\\u0000`)\n }\n return digest.digest('hex')\n}\n\n/** A job that could not have produced a reusable plan, whatever its key says. */\nconst UNREUSABLE: readonly AiJobStatus[] = ['canceled', 'failed']\n\nfunction planMillis(plan: AiJobPlan): number | null {\n const at = plan.proposedAt as unknown\n if (at instanceof Date) return at.getTime()\n if (at && typeof (at as { toMillis?: unknown }).toMillis === 'function') {\n return (at as { toMillis(): number }).toMillis()\n }\n return null\n}\n\n/**\n * The newest plan worth reusing out of what the finder returned: another\n * job's, still proposed or already confirmed, on a job that was neither\n * canceled nor failed, proposed inside the window.\n *\n * A canceled or failed job is excluded even though its plan may be perfectly\n * good: those are the jobs a member walked away from, and handing their plan\n * to the next one would make a rejected answer look like a fresh one.\n */\nexport function aiReusablePlan(\n candidates: readonly AiJobPlanCandidate[],\n context: { jobId: string; now: Date },\n): AiJobPlanCandidate | null {\n const floor = context.now.getTime() - AI_PLAN_REUSE_WINDOW_MS\n let best: AiJobPlanCandidate | null = null\n let bestAt = -1\n for (const candidate of candidates) {\n if (candidate.jobId === context.jobId) continue\n if (UNREUSABLE.includes(candidate.status)) continue\n if (candidate.plan.status !== 'proposed' && candidate.plan.status !== 'confirmed') continue\n const at = planMillis(candidate.plan)\n if (at === null || at < floor || at > context.now.getTime()) continue\n if (at > bestAt) {\n best = candidate\n bestAt = at\n }\n }\n return best\n}\n\nexport type AiJobPlanFinder = (\n orgId: string,\n key: string,\n firestore?: FirebaseFirestore.Firestore,\n) => Promise<AiJobPlanCandidate[]>\n\n/**\n * The finder the step uses in production: an equality on `plan.key` inside\n * the org's own jobs.\n *\n * One equality on one field, with no ordering beside it, so Firestore's\n * automatic single-field index answers it and no composite index is deployed.\n * The window and the statuses are applied in memory instead, which is what\n * keeps it that way.\n */\nexport const findAiJobsByPlanKey: AiJobPlanFinder = async (orgId, key, firestore) => {\n if (!firestore) return []\n const snapshot = await firestore\n .collection('orgs')\n .doc(orgId)\n .collection(AI_JOBS_COLLECTION)\n .where('plan.key', '==', key)\n .limit(AI_PLAN_REUSE_CANDIDATES)\n .get()\n return snapshot.docs.flatMap((doc) => {\n const data = doc.data() as { status?: AiJobStatus; plan?: AiJobPlan | null }\n return data.plan\n ? [{ jobId: doc.id, status: data.status ?? 'queued', plan: data.plan }]\n : []\n })\n}\n\n/** What a job may create on its site, read for the plan step; `null` for no site. */\nexport type AiPlanCapabilitiesReader = (input: {\n job: AiJob\n org: Partial<AglynOrgBilling> | null\n firestore: FirebaseFirestore.Firestore\n}) => Promise<AiPlanCapabilities | null>\n\n/** The reader the step uses in production: the draft bands' own arithmetic, for the job's site. */\nexport const readAiJobPlanCapabilities: AiPlanCapabilitiesReader = async ({ job, org, firestore }) =>\n job.hostId ? readAiPlanCapabilities(firestore, { hostId: job.hostId, org }) : null\n\nexport interface AiJobPlanStepDeps {\n /** The inventory reader; specs hand in a fake. */\n readInventory?: typeof readSiteInventory\n /** The reuse lookup; specs hand in a fake, and `null` turns reuse off. */\n findPlansByKey?: AiJobPlanFinder | null\n /** What the job may create on its site (AGL-3030); specs and the eval recorder hand in their own. */\n readCapabilities?: AiPlanCapabilitiesReader\n /** The kind's admission, asked of a plan before it is kept; the registry's otherwise. */\n admissionRefusal?: typeof aiJobAdmissionRefusal\n /** A build's operations on its site (AGL-3616); the registry and its gates otherwise. */\n readOps?: AiBuildOpsReader\n /**\n * The site's business profile, status and remembered preferences\n * (AGL-3661); specs and the eval recorder hand in their own, and `null`\n * turns it off.\n */\n readSiteContext?: AiSiteContextReader | null\n}\n\n/** What a job's site context is read with (AGL-3661). */\nexport type AiSiteContextReader = (input: {\n job: AiJob\n firestore: FirebaseFirestore.Firestore\n}) => Promise<AiSiteContextInput | null>\n\n/** The reader the step uses in production: fail-soft, org-scoped, `null` for a job with no site. */\nexport const readAiJobSiteContext: AiSiteContextReader = ({ job, firestore }) =>\n readAiSiteContext(firestore, { orgId: job.orgId, hostId: job.hostId })\n\n/** What a build may plan on its site (AGL-3616). */\nexport type AiBuildOpsReader = (input: {\n job: AiJob\n org: Partial<AglynOrgBilling> | null\n firestore: FirebaseFirestore.Firestore\n freeTaste: boolean\n}) => Promise<AiBuildOps>\n\n/** The reader the step uses in production: the registry, gated for the job's site. */\nexport const readAiBuildOps: AiBuildOpsReader = async ({ job, org, firestore, freeTaste }) => {\n const host = job.hostId\n ? (((await firestore.collection('hosts').doc(job.hostId).get()).data() ?? null) as Record<string, unknown> | null)\n : null\n return aiBuildOps({ orgId: job.orgId, hostId: job.hostId ?? null, org, host, freeTaste })\n}\n\n/**\n * A build plan's items with what each can cost (AGL-3616), from its\n * capability, recorded as the plan is kept so the console's estimate and the\n * confirm door read one figure without the registry.\n */\nexport function aiPlanWithItemCredits<T extends AiBuildPlan>(ops: AiBuildOps | null, plan: T): T {\n if (!ops || !plan.items?.length) return plan\n return {\n ...plan,\n items: plan.items.map((item) => {\n const capability = ops.get(item.op)\n return capability ? { ...item, credits: Math.max(0, Math.floor(capability.estimateCredits(item.args))) } : item\n }),\n }\n}\n\nexport function createAiJobPlanStep(deps: AiJobPlanStepDeps = {}): AiJobStepRunner {\n const readInventory = deps.readInventory ?? readSiteInventory\n const findPlansByKey =\n deps.findPlansByKey === undefined ? findAiJobsByPlanKey : deps.findPlansByKey\n const readCapabilities = deps.readCapabilities ?? readAiJobPlanCapabilities\n const admissionRefusal = deps.admissionRefusal ?? aiJobAdmissionRefusal\n const readOps = deps.readOps ?? readAiBuildOps\n const readContext = deps.readSiteContext === undefined ? readAiJobSiteContext : deps.readSiteContext\n return async ({ job, now, signal, firestore, modelFor, org: orgDocument }) => {\n const org = (orgDocument ?? null) as Partial<AglynOrgBilling> | null\n const [inventory, workspace, siteContext] = await Promise.all([\n job.hostId ? readInventory(job.orgId, job.hostId, { firestore }) : Promise.resolve(null),\n readCapabilities({ job, org, firestore }),\n job.hostId && readContext ? readContext({ job, firestore }) : Promise.resolve(null),\n ])\n // The site's profile, status and memory (AGL-3661), as a per-site cached\n // block after the plan rules. The inventory block already lists what the\n // site holds, so the context carries no index of its own here.\n const instructions = aiInstructionsWithSiteContext(AI_JOB_PLAN_INSTRUCTIONS, siteContext)\n const scope = AI_JOB_PLAN_SCOPES[job.kind] ?? null\n const capabilities = aiSitePlanCapabilities(\n job,\n workspace ? aiPlanCapabilitiesForJob(workspace, scope) : null,\n )\n const freeTaste = capabilities?.freeTaste === true\n // A build's operations, as this site has them (AGL-3616).\n const ops = job.kind === 'build' ? await readOps({ job, org, firestore, freeTaste }) : null\n const site = job.kind === 'site'\n // The model switch's answer for this job (AGL-2942): the creator's pick\n // where the plan, the org restriction and the allotment allowlists allow\n // it, and Auto held to those same lists otherwise. Without a resolver the\n // doctrine asks the routing table itself. A Free site plans on its\n // provider's fast tier (AGL-3594), unless the creator picked a model.\n const model = aiSitePlanModel(job, modelFor?.('job.plan'), freeTaste)\n const route = AI_ROUTING_TABLE['job.plan']\n const prompt = aiJobPlanPrompt(job, capabilities, inventory, ops)\n\n /**\n * The confirm door's answer for this plan, asked before the plan is kept\n * (AGL-3030): the kind's own admission, handed the plan as the resume\n * door hands it. A refusal fails the job with the door's sentence; a door\n * that could not answer keeps the plan, since the resume door asks again\n * before anything is built.\n */\n const refusalOnKeep = async (plan: AiJobPlan, outcome: AiJobStepOutcome): Promise<AiJobStepOutcome | null> => {\n let refusal: Awaited<ReturnType<typeof aiJobAdmissionRefusal>> = null\n try {\n refusal = await admissionRefusal(job.kind, {\n firestore,\n orgId: job.orgId,\n hostId: job.hostId ?? null,\n inputs: job.inputs ?? {},\n org,\n plan,\n uid: job.createdBy,\n })\n } catch (error) {\n console.error('ai plan admission failed', { orgId: job.orgId, jobId: job.$id, error })\n }\n return refusal ? { ...outcome, failure: refusal.error } : null\n }\n\n // Reuse before asking (AGL-2937). The key covers the whole request, so a\n // hit is a request that would have been sent the same bytes to the same\n // model; the window covers what the key cannot see. A reused plan spends\n // nothing, so the machine's spent-nothing branch releases the reservation\n // and meters no credit, and the job still stops for the member to confirm\n // — this job's plan is proposed to this member, whatever the last one did\n // with theirs.\n const resolved = model ?? aiModelForStep('job.plan')\n // A brief that asks for a video is offered the plan's list of players\n // (AGL-3433), and a job that may bind a dataset a record template on\n // each screen (AGL-3475).\n const tool = aiBuildPlanToolFor(job.brief, {\n records: Boolean(inventory?.datasets.length) || capabilities?.create.dataset.allowed === true,\n items: job.kind === 'build',\n })\n const key = aiJobPlanKey({\n job,\n prompt,\n model: resolved,\n system: aiDoctrineSystemBlocks(inventory, { instructions }),\n tool,\n })\n const reused = findPlansByKey\n ? aiReusablePlan(await findPlansByKey(job.orgId, key, firestore), {\n jobId: job.$id,\n now,\n })\n : null\n if (reused) {\n // The reused plan's draft ids name the other job's drafts; this job's are its own.\n const plan: AiJobPlan = aiPlanWithItemCredits(ops, aiPlanWithDraftIds(job.kind, {\n ...reused.plan,\n status: 'proposed',\n labels: aiPlanLabels(reused.plan, inventory),\n proposedAt: now as unknown as AiJobPlan['proposedAt'],\n confirmedAt: null,\n confirmedBy: null,\n key,\n reusedFrom: reused.jobId,\n }))\n const unspent = aiUnspentOutcome(resolved)\n return (\n (await refusalOnKeep(plan, unspent)) ?? {\n ...unspent,\n plan,\n review: { reason: 'plan', message: AI_JOB_PLAN_REVIEW_COPY, findings: [] },\n }\n )\n }\n\n const result = await runValidatedGeneration('plan', {\n step: 'job.plan',\n ...(model ? { model } : {}),\n instructions,\n inventory,\n messages: [{ role: 'user', content: prompt }],\n tool,\n // The routing ceiling, lowered on a tier too slow to look records up,\n // answer and ask again inside the least time the step registered; a\n // scaffold's outline is held to its own, far lower ceiling (AGL-3594).\n maxTokens: aiSitePlanMaxTokens(job, resolved, freeTaste),\n // A scaffold plans an outline without thinking (AGL-3594): the thinking\n // was nearly all of the 13,491 tokens a Free site's plan spent.\n ...(site ? { thinking: 'off' as const } : route.thinking ? { thinking: route.thinking } : {}),\n ...(route.effort ? { effort: route.effort } : {}),\n ...(signal ? { signal } : {}),\n capabilities,\n extend: planViolations(scope, job.brief, freeTaste, ops),\n })\n const spent: AiJobStepOutcome = {\n outputs: [],\n usage: result.usage,\n estCostUsd: result.estCostUsd,\n model: result.model,\n stopReason: result.stopReason,\n ...(result.effort ? { effort: result.effort } : {}),\n }\n if (result.status === 'refused') return { ...spent, refused: true }\n if (result.status === 'needs_input') {\n // Refused by our own checks, after the one re-ask (AGL-3594): the member\n // reads a sentence and an action, staff the rules; the machine gives the\n // credits back (`uncredited`), and on the Free taste Try again says when\n // it cannot work. Whether the give-back was made is the job's to say\n // (`refundedCredits`), so this sentence does not promise it.\n const review = aiDoctrineReview(result)\n const retryRefusal = freeTaste\n ? await aiFreePlanRetryRefusal({ job, org, firestore, now, site })\n : null\n return {\n ...spent,\n uncredited: true,\n review: {\n ...review,\n message: aiPlanFailureCopy({\n kind: job.kind,\n codes: result.violations.map((violation) => violation.code),\n refunded: false,\n }),\n detail: review.detail ?? review.message,\n ...(retryRefusal ? { retryRefusal } : {}),\n },\n }\n }\n // Each draft the plan decides is named as the plan is kept, before anything is built (AGL-3079).\n const plan: AiJobPlan = aiPlanWithItemCredits(ops, aiPlanWithDraftIds(job.kind, {\n ...result.value,\n status: 'proposed',\n labels: aiPlanLabels(result.value, inventory),\n // A Date the Admin SDK stores as a timestamp, like every instant the machine writes.\n proposedAt: now as unknown as AiJobPlan['proposedAt'],\n confirmedAt: null,\n confirmedBy: null,\n key,\n }))\n return (\n (await refusalOnKeep(plan, spent)) ?? {\n ...spent,\n plan,\n review: { reason: 'plan', message: AI_JOB_PLAN_REVIEW_COPY, findings: [] },\n }\n )\n }\n}\n\n/**\n * A site job's capabilities (AGL-3594, AGL-3660): it changes no theme in its\n * plan — every scaffold designs its look first, in a unit of its own — and on\n * the Free taste its plan holds at most the pages the member asked for within\n * the Free band, which the Free wall then holds it to. Every other job's\n * capabilities pass through.\n */\nexport function aiSitePlanCapabilities(\n job: Pick<AiJob, 'kind' | 'inputs'>,\n capabilities: AiPlanCapabilities | null,\n): AiPlanCapabilities | null {\n if (job.kind !== 'site' || !capabilities) return capabilities\n const create = {\n ...capabilities.create,\n 'theme-change': {\n allowed: false,\n left: null,\n reason: 'a site start designs its own look before its pages',\n },\n // A site start builds its look, one layout and one form, never a\n // component (`AI_SITE_CREATE_KINDS`), so a paid workspace's plan draws\n // repeated items in their sections, as a Free one's does. Held to rule 1\n // instead, every paid plan was refused: for the component it left out,\n // or, re-asked, for the one it could not build (AGL-3660).\n component: {\n allowed: false,\n left: null,\n reason: 'a site start draws its repeated items in their sections',\n },\n }\n const site = { ...capabilities, reusableComponents: false, create }\n if (!capabilities.freeTaste) return site\n const asked = Number((job.inputs ?? {})['pages'])\n const pages =\n Number.isInteger(asked) && asked >= AI_SITE_FREE_PAGES.min\n ? Math.min(asked, AI_SITE_FREE_PAGES.max)\n : AI_SITE_FREE_PAGES.max\n return { ...site, freeSitePages: pages }\n}\n\n/**\n * The model a plan runs on (AGL-3594): the resolved one, except a Free site\n * plans on its provider's fast tier — an outline the plan rules hold and\n * re-ask, at a fifth of the balanced tier's output rate. A model the creator\n * picked by name stays theirs.\n */\nexport function aiSitePlanModel(\n job: Pick<AiJob, 'kind' | 'model'>,\n resolved: string | undefined,\n freeTaste: boolean,\n): string | undefined {\n if (job.kind !== 'site' || !freeTaste) return resolved\n const picked = typeof job.model === 'string' ? job.model.trim() : ''\n if (picked && picked !== 'auto') return resolved\n const entry = aiCatalogEntry(resolved ?? aiModelForStep('job.plan'))\n return (entry ? aiDefaultModelFor(entry.provider, 'fast') : undefined) ?? resolved\n}\n\n/** The plan's answer ceiling: the step's own, and a scaffold's outline ceiling under it (AGL-3594). */\nexport function aiSitePlanMaxTokens(\n job: Pick<AiJob, 'kind'>,\n model: string,\n freeTaste: boolean,\n): number {\n const ceiling = aiJobPlanMaxTokens(model)\n if (job.kind !== 'site') return ceiling\n return Math.min(ceiling, freeTaste ? AI_SITE_PLAN_MAX_TOKENS.free : AI_SITE_PLAN_MAX_TOKENS.paid)\n}\n\n/**\n * Why trying a Free plan again cannot work this month, or `null` (AGL-3594):\n * the owner's Free allowance left, read off the account month the meter\n * writes net of give-backs, against what a plan of this kind costs at its\n * worst. Read before this step is metered, and the machine gives a refused\n * plan's credits back, so the figure read is the figure left. A read that fails\n * leaves the button on: the reservation still refuses at the wall.\n */\nasync function aiFreePlanRetryRefusal(input: {\n job: AiJob\n org: Partial<AglynOrgBilling> | null\n firestore: FirebaseFirestore.Firestore\n now: Date\n site: boolean\n}): Promise<string | null> {\n const account = freeAssistAccount(input.org as AssistMeteredOrg | null)\n if (!account?.accountUid) return null\n try {\n // The meter's month key, `YYYY-MM` in UTC (`assistUsageMonth`).\n const month = input.now.toISOString().slice(0, 7)\n const snapshot = await freeAccountUsageRef(input.firestore, account.accountUid, month).get()\n const spent = assistCreditsFromUsd(\n assistSpendAfterReturnsUsd(snapshot.get('estCostUsd'), snapshot.get(ASSIST_RETURNED_USD_FIELD)),\n )\n return aiPlanRetryRefusal({\n creditsLeft: FREE_AI_TASTE_CREDITS_PER_MONTH - spent,\n planCredits: input.site ? AI_FREE_SITE_WORST_CASE_CREDITS.plan : AI_FREE_PAGE_WORST_CASE_CREDITS.plan,\n })\n } catch (error) {\n console.error('ai plan retry allowance read failed', { orgId: input.job.orgId, jobId: input.job.$id, error })\n return null\n }\n}\n\nexport const runAiJobPlanStep = createAiJobPlanStep()\n\n/**\n * Registers the plan step every planned kind runs first, with the least time\n * a plan needs; the plugin's console surface calls it.\n */\nexport function registerAiJobPlan(): void {\n registerAiJobPlanStep(runAiJobPlanStep, { minimumMs: AI_JOB_PLAN_STEP_MINIMUM_MS })\n}\n"],"names":["aiSiteKindOfInputs","createHash","AI_BUILD_PLAN_TOOL","aiBuildPlanToolFor","isAiPlanNewRef","AI_TEMPLATE_SUBJECT_DEFINITIONS","aiTemplateShownTokens","AI_JOB_CREATE_KINDS","AI_JOB_CREATE_NOUNS","AI_PAGE_CREATE_KINDS","aiPagePlanShapeRefusal","AI_PLAN_NO_FORM_SENTENCE","aiPlanCanPlaceForm","aiPlanCapabilitiesForJob","aiPlanCapabilityLines","AI_FREE_SITE_WORST_CASE_CREDITS","AI_SITE_CREATE_KINDS","AI_SITE_FREE_PAGES","AI_SITE_PLAN_MAX_TOKENS","aiFreeSiteSectionsWithin","aiSiteNameSentence","aiSitePlanShapeRefusal","aiPlanFailureCopy","aiPlanRetryRefusal","FREE_AI_TASTE_CREDITS_PER_MONTH","aiDoctrineSystemBlocks","runValidatedGeneration","AI_STEP_TIERS","aiCatalogEntry","aiDefaultModelFor","AI_FREE_PAGE_WORST_CASE_CREDITS","aiPlanEmbedBriefViolations","assistCreditsFromUsd","ASSIST_RETURNED_USD_FIELD","assistSpendAfterReturnsUsd","freeAccountUsageRef","freeAssistAccount","AI_ROUTING_TABLE","aiModelForStep","readSiteInventory","readAiSiteContext","aiInstructionsWithSiteContext","AI_BUILD_CREATE_KINDS","AI_BUILD_STRUCTURAL_OPS","aiBuildPageLimit","aiBuildPlanShapeRefusal","aiBuildOpLines","aiBuildOps","aiJobAdmissionRefusal","readAiPlanCapabilities","AI_JOB_BRIEF_MAX_CHARS","aiJobStepBudget","aiDoctrineReview","aiUnspentOutcome","aiPlanWithDraftIds","AI_JOBS_COLLECTION","registerAiJobPlanStep","AI_JOB_PLAN_INSTRUCTIONS","text","AI_JOB_PLAN_STEP_BUDGET","tier","maxTokens","AI_JOB_PLAN_STEP_MINIMUM_MS","minimumMs","aiJobPlanMaxTokens","model","AI_JOB_PLAN_REVIEW_COPY","aiJobPlanPrompt","job","capabilities","inventory","ops","lines","kind","brief","slice","key","value","Object","entries","inputs","push","String","aiPlanTemplateTokenLines","aiPlanSiteLines","aiPlanBuildLines","join","pages","freeTaste","name","trim","screens","filter","screen","template","starter","find","replaceable","length","page","slug","some","cap","freeSitePages","undefined","sections","layouts","label","toLowerCase","subject","definition","AI_JOB_PLAN_SCOPES","noun","creates","shapeRefusal","build","plan","options","site","fromEntries","map","planViolations","scope","message","rule","code","aiPlanLabels","names","Map","rows","components","templates","forms","datasets","collections","row","set","id","refs","reuse","entry","create","duplicateOf","flatMap","layout","section","uses","labels","ref","get","AI_PLAN_REUSE_WINDOW_MS","AI_PLAN_REUSE_CANDIDATES","aiJobPlanKey","input","digest","part","hostId","prompt","system","block","JSON","stringify","tool","update","UNREUSABLE","planMillis","at","proposedAt","Date","getTime","toMillis","aiReusablePlan","candidates","context","floor","now","best","bestAt","candidate","jobId","includes","status","findAiJobsByPlanKey","orgId","firestore","snapshot","collection","doc","where","limit","docs","data","readAiJobPlanCapabilities","org","readAiJobSiteContext","readAiBuildOps","host","aiPlanWithItemCredits","items","item","capability","op","credits","Math","max","estimateCredits","args","createAiJobPlanStep","deps","readInventory","findPlansByKey","readCapabilities","admissionRefusal","readOps","readContext","readSiteContext","signal","modelFor","orgDocument","workspace","siteContext","Promise","all","resolve","instructions","aiSitePlanCapabilities","aiSitePlanModel","route","refusalOnKeep","outcome","refusal","uid","createdBy","error","console","$id","failure","resolved","records","Boolean","dataset","allowed","reused","confirmedAt","confirmedBy","reusedFrom","unspent","review","reason","findings","result","step","messages","role","content","aiSitePlanMaxTokens","thinking","effort","extend","spent","outputs","usage","estCostUsd","stopReason","refused","retryRefusal","aiFreePlanRetryRefusal","uncredited","codes","violations","violation","refunded","detail","left","component","reusableComponents","asked","Number","isInteger","min","picked","provider","ceiling","free","paid","account","accountUid","month","toISOString","creditsLeft","planCredits","runAiJobPlanStep","registerAiJobPlan"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,QAAQ,4BAAwB;AAC3D,SAASC,UAAU,QAAQ,cAAa;AAExC,SACEC,kBAAkB,EAClBC,kBAAkB,EAClBC,cAAc,QAET,4BAAwB;AAE/B,SACEC,+BAA+B,EAC/BC,qBAAqB,QAEhB,mCAA+B;AACtC,SAASC,mBAAmB,EAAEC,mBAAmB,QAAQ,+BAA2B;AACpF,SAASC,oBAAoB,EAAEC,sBAAsB,QAAQ,0BAAsB;AACnF,SACEC,wBAAwB,EACxBC,kBAAkB,EAClBC,wBAAwB,EACxBC,qBAAqB,QAGhB,mCAA+B;AAEtC,SACEC,+BAA+B,EAC/BC,oBAAoB,EACpBC,kBAAkB,EAClBC,uBAAuB,EACvBC,wBAAwB,EACxBC,kBAAkB,EAClBC,sBAAsB,QACjB,0BAAsB;AAC7B,SAASC,iBAAiB,EAAEC,kBAAkB,QAAQ,kCAA8B;AACpF,SAASC,+BAA+B,QAAQ,0BAAsB;AACtE,SAASC,sBAAsB,EAAEC,sBAAsB,QAAQ,4BAAwB;AACvF,SAASC,aAAa,EAAEC,cAAc,EAAEC,iBAAiB,QAAQ,0BAAsB;AACvF,SACEC,+BAA+B,EAC/BC,0BAA0B,QAErB,uCAAmC;AAC1C,SAASC,oBAAoB,QAAQ,6BAAyB;AAC9D,SAASC,yBAAyB,EAAEC,0BAA0B,QAAQ,oCAAgC;AACtG,SAASC,mBAAmB,EAAEC,iBAAiB,QAA+B,gCAA4B;AAC1G,SAASC,gBAAgB,EAAEC,cAAc,QAAQ,0BAAsB;AAGvE,SAASC,iBAAiB,QAAQ,+BAA2B;AAC7D,SAASC,iBAAiB,QAAQ,6BAAyB;AAC3D,SAASC,6BAA6B,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