@pixerate/editor 0.22.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/README.md +175 -2
  2. package/THIRD_PARTY_NOTICES.md +139 -0
  3. package/dist/agent/index.cjs +87 -111
  4. package/dist/agent/index.cjs.map +1 -1
  5. package/dist/agent/index.d.cts +70 -211
  6. package/dist/agent/index.d.ts +70 -211
  7. package/dist/agent/index.js +78 -102
  8. package/dist/agent/index.js.map +1 -1
  9. package/dist/arrangeShortcuts-B8O3f8-P.d.cts +184 -0
  10. package/dist/arrangeShortcuts-sLlD2rSX.d.ts +184 -0
  11. package/dist/canvas/index.cjs +2075 -86
  12. package/dist/canvas/index.cjs.map +1 -1
  13. package/dist/canvas/index.d.cts +608 -186
  14. package/dist/canvas/index.d.ts +608 -186
  15. package/dist/canvas/index.js +2060 -71
  16. package/dist/canvas/index.js.map +1 -1
  17. package/dist/chunk-26BVFKHU.cjs +453 -0
  18. package/dist/chunk-26BVFKHU.cjs.map +1 -0
  19. package/dist/chunk-2H7ZHPEJ.js +762 -0
  20. package/dist/chunk-2H7ZHPEJ.js.map +1 -0
  21. package/dist/{chunk-DENSCKFC.js → chunk-3CN2WD3X.js} +1730 -189
  22. package/dist/chunk-3CN2WD3X.js.map +1 -0
  23. package/dist/{chunk-JJDLPEWL.js → chunk-3LV6RRPH.js} +2 -2
  24. package/dist/{chunk-MJZBNWG7.js → chunk-5S3Z4PPF.js} +78 -557
  25. package/dist/chunk-5S3Z4PPF.js.map +1 -0
  26. package/dist/chunk-664LQYFJ.js +115 -0
  27. package/dist/chunk-664LQYFJ.js.map +1 -0
  28. package/dist/chunk-7DWMJCAT.js +453 -0
  29. package/dist/chunk-7DWMJCAT.js.map +1 -0
  30. package/dist/chunk-ARRTP33I.js +101 -0
  31. package/dist/chunk-ARRTP33I.js.map +1 -0
  32. package/dist/chunk-CPOKFNBG.cjs +101 -0
  33. package/dist/chunk-CPOKFNBG.cjs.map +1 -0
  34. package/dist/{chunk-AA4ZEVCC.cjs → chunk-D27YFC46.cjs} +101 -580
  35. package/dist/chunk-D27YFC46.cjs.map +1 -0
  36. package/dist/chunk-D6FH2YAX.cjs +131 -0
  37. package/dist/chunk-D6FH2YAX.cjs.map +1 -0
  38. package/dist/{chunk-4SUNJZWB.cjs → chunk-FD4LPFAE.cjs} +48 -200
  39. package/dist/chunk-FD4LPFAE.cjs.map +1 -0
  40. package/dist/chunk-FODNLX5N.js +749 -0
  41. package/dist/chunk-FODNLX5N.js.map +1 -0
  42. package/dist/{chunk-OYXSKQFR.js → chunk-FPENXAEJ.js} +35 -187
  43. package/dist/chunk-FPENXAEJ.js.map +1 -0
  44. package/dist/chunk-G2I4QJOT.cjs +762 -0
  45. package/dist/chunk-G2I4QJOT.cjs.map +1 -0
  46. package/dist/chunk-HLIMTC6N.js +1 -0
  47. package/dist/chunk-HLIMTC6N.js.map +1 -0
  48. package/dist/{chunk-QGHGJ56O.js → chunk-ITBSKI26.js} +1483 -19
  49. package/dist/chunk-ITBSKI26.js.map +1 -0
  50. package/dist/{chunk-6M3BCTBD.cjs → chunk-MA2F5KHF.cjs} +470 -242
  51. package/dist/chunk-MA2F5KHF.cjs.map +1 -0
  52. package/dist/{chunk-SAZRENEZ.cjs → chunk-MCSJFWAO.cjs} +1733 -192
  53. package/dist/chunk-MCSJFWAO.cjs.map +1 -0
  54. package/dist/chunk-MKA3AHLV.cjs +256 -0
  55. package/dist/chunk-MKA3AHLV.cjs.map +1 -0
  56. package/dist/chunk-OLZJXL4R.cjs +749 -0
  57. package/dist/chunk-OLZJXL4R.cjs.map +1 -0
  58. package/dist/chunk-OXSV64JX.js +689 -0
  59. package/dist/chunk-OXSV64JX.js.map +1 -0
  60. package/dist/chunk-P3RQ5UJE.cjs +689 -0
  61. package/dist/chunk-P3RQ5UJE.cjs.map +1 -0
  62. package/dist/chunk-P6ODPZ4W.js +256 -0
  63. package/dist/chunk-P6ODPZ4W.js.map +1 -0
  64. package/dist/chunk-PGNZKFQS.js +685 -0
  65. package/dist/chunk-PGNZKFQS.js.map +1 -0
  66. package/dist/chunk-PL4JB3BF.cjs +1 -0
  67. package/dist/chunk-PL4JB3BF.cjs.map +1 -0
  68. package/dist/{chunk-GVSMRPHB.cjs → chunk-SBCZ6RN5.cjs} +1568 -104
  69. package/dist/chunk-SBCZ6RN5.cjs.map +1 -0
  70. package/dist/{chunk-CL37JGFW.cjs → chunk-SML64VJG.cjs} +4 -4
  71. package/dist/{chunk-CL37JGFW.cjs.map → chunk-SML64VJG.cjs.map} +1 -1
  72. package/dist/chunk-TNNJXF46.cjs +115 -0
  73. package/dist/chunk-TNNJXF46.cjs.map +1 -0
  74. package/dist/chunk-U5HZSFCS.js +131 -0
  75. package/dist/chunk-U5HZSFCS.js.map +1 -0
  76. package/dist/{chunk-RU52I7QO.js → chunk-U5KWZU4X.js} +388 -160
  77. package/dist/chunk-U5KWZU4X.js.map +1 -0
  78. package/dist/chunk-XNORY7M6.cjs +685 -0
  79. package/dist/chunk-XNORY7M6.cjs.map +1 -0
  80. package/dist/commands/index.cjs +860 -0
  81. package/dist/commands/index.cjs.map +1 -0
  82. package/dist/commands/index.d.cts +244 -0
  83. package/dist/commands/index.d.ts +244 -0
  84. package/dist/commands/index.js +860 -0
  85. package/dist/commands/index.js.map +1 -0
  86. package/dist/comment-store-BEMgVlAA.d.cts +135 -0
  87. package/dist/comment-store-BEMgVlAA.d.ts +135 -0
  88. package/dist/compare/index.cjs +15 -0
  89. package/dist/compare/index.cjs.map +1 -0
  90. package/dist/compare/index.d.cts +58 -0
  91. package/dist/compare/index.d.ts +58 -0
  92. package/dist/compare/index.js +15 -0
  93. package/dist/compare/index.js.map +1 -0
  94. package/dist/{controller-B7GIybc4.d.cts → controller-BhLLAoi8.d.cts} +119 -5
  95. package/dist/{controller-B7GIybc4.d.ts → controller-BhLLAoi8.d.ts} +119 -5
  96. package/dist/documents-BQjzJNe2.d.ts +76 -0
  97. package/dist/documents-KRTPhvst.d.cts +76 -0
  98. package/dist/extensions/index.cjs +53 -5
  99. package/dist/extensions/index.cjs.map +1 -1
  100. package/dist/extensions/index.d.cts +7 -3
  101. package/dist/extensions/index.d.ts +7 -3
  102. package/dist/extensions/index.js +52 -4
  103. package/dist/generation/index.cjs +1373 -0
  104. package/dist/generation/index.cjs.map +1 -0
  105. package/dist/generation/index.d.cts +554 -0
  106. package/dist/generation/index.d.ts +554 -0
  107. package/dist/generation/index.js +1373 -0
  108. package/dist/generation/index.js.map +1 -0
  109. package/dist/grammar/index.cjs +48 -3
  110. package/dist/grammar/index.cjs.map +1 -1
  111. package/dist/grammar/index.d.cts +322 -100
  112. package/dist/grammar/index.d.ts +322 -100
  113. package/dist/grammar/index.js +54 -9
  114. package/dist/history/index.cjs +12 -2
  115. package/dist/history/index.cjs.map +1 -1
  116. package/dist/history/index.d.cts +211 -7
  117. package/dist/history/index.d.ts +211 -7
  118. package/dist/history/index.js +13 -3
  119. package/dist/image-editor/index.cjs +2244 -38
  120. package/dist/image-editor/index.cjs.map +1 -1
  121. package/dist/image-editor/index.d.cts +742 -4
  122. package/dist/image-editor/index.d.ts +742 -4
  123. package/dist/image-editor/index.js +2222 -16
  124. package/dist/image-editor/index.js.map +1 -1
  125. package/dist/{index-CCr_z9kF.d.cts → index-BhJBSm2d.d.cts} +370 -4
  126. package/dist/{index-Ck6ajwXh.d.ts → index-fJrlkJCd.d.ts} +370 -4
  127. package/dist/index.cjs +193 -98
  128. package/dist/index.cjs.map +1 -1
  129. package/dist/index.d.cts +17 -48
  130. package/dist/index.d.ts +17 -48
  131. package/dist/index.js +198 -103
  132. package/dist/index.js.map +1 -1
  133. package/dist/migrate-iTlm3a8h.d.cts +112 -0
  134. package/dist/migrate-iTlm3a8h.d.ts +112 -0
  135. package/dist/persistence/index.cjs +676 -0
  136. package/dist/persistence/index.cjs.map +1 -0
  137. package/dist/persistence/index.d.cts +347 -0
  138. package/dist/persistence/index.d.ts +347 -0
  139. package/dist/persistence/index.js +676 -0
  140. package/dist/persistence/index.js.map +1 -0
  141. package/dist/registry-BDe-vlv3.d.ts +171 -0
  142. package/dist/registry-D32LpIc4.d.cts +354 -0
  143. package/dist/registry-DnzpgY27.d.cts +171 -0
  144. package/dist/registry-evKTP4ls.d.ts +354 -0
  145. package/dist/schema-DYDGdYL9.d.cts +41 -0
  146. package/dist/schema-DYDGdYL9.d.ts +41 -0
  147. package/dist/serializers/index.cjs +4 -3
  148. package/dist/serializers/index.cjs.map +1 -1
  149. package/dist/serializers/index.d.cts +2 -1
  150. package/dist/serializers/index.d.ts +2 -1
  151. package/dist/serializers/index.js +3 -2
  152. package/dist/sourcemap-C8AH3MBQ.d.cts +91 -0
  153. package/dist/sourcemap-DA1Evhrv.d.ts +91 -0
  154. package/dist/spreadsheet/index.cjs +53 -3
  155. package/dist/spreadsheet/index.cjs.map +1 -1
  156. package/dist/spreadsheet/index.d.cts +247 -18
  157. package/dist/spreadsheet/index.d.ts +247 -18
  158. package/dist/spreadsheet/index.js +58 -8
  159. package/dist/{tokens-CyLZmIei.d.cts → tokens-D7yXvUU6.d.cts} +15 -2
  160. package/dist/{tokens-CyLZmIei.d.ts → tokens-D7yXvUU6.d.ts} +15 -2
  161. package/dist/{track-changes-BSF58RK0.d.cts → track-changes-BK5sVf4_.d.cts} +18 -136
  162. package/dist/{track-changes-BSF58RK0.d.ts → track-changes-CDjCrwKe.d.ts} +18 -136
  163. package/dist/{types-CJ4U-HHI.d.ts → types-DX4Mh4SL.d.cts} +1 -1
  164. package/dist/{types-CJ4U-HHI.d.cts → types-DX4Mh4SL.d.ts} +1 -1
  165. package/dist/types-GT5a5YAX.d.cts +86 -0
  166. package/dist/types-GT5a5YAX.d.ts +86 -0
  167. package/package.json +23 -2
  168. package/dist/chunk-2TWGLC5K.cjs +0 -262
  169. package/dist/chunk-2TWGLC5K.cjs.map +0 -1
  170. package/dist/chunk-4SUNJZWB.cjs.map +0 -1
  171. package/dist/chunk-6M3BCTBD.cjs.map +0 -1
  172. package/dist/chunk-AA4ZEVCC.cjs.map +0 -1
  173. package/dist/chunk-AXV2ZW34.cjs +0 -118
  174. package/dist/chunk-AXV2ZW34.cjs.map +0 -1
  175. package/dist/chunk-B2ZRLN4S.js +0 -118
  176. package/dist/chunk-B2ZRLN4S.js.map +0 -1
  177. package/dist/chunk-DENSCKFC.js.map +0 -1
  178. package/dist/chunk-GVSMRPHB.cjs.map +0 -1
  179. package/dist/chunk-KAADNAPF.js +0 -262
  180. package/dist/chunk-KAADNAPF.js.map +0 -1
  181. package/dist/chunk-MJZBNWG7.js.map +0 -1
  182. package/dist/chunk-OYXSKQFR.js.map +0 -1
  183. package/dist/chunk-QGHGJ56O.js.map +0 -1
  184. package/dist/chunk-RU52I7QO.js.map +0 -1
  185. package/dist/chunk-SAZRENEZ.cjs.map +0 -1
  186. package/dist/types-BZgcDsC5.d.cts +0 -42
  187. package/dist/types-BZgcDsC5.d.ts +0 -42
  188. /package/dist/{chunk-JJDLPEWL.js.map → chunk-3LV6RRPH.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/generation/capabilities.ts","../../src/generation/plan.ts","../../src/generation/schema.ts","../../src/generation/tools.ts","../../src/generation/provenance.ts","../../src/generation/batch.ts","../../src/generation/progress.ts","../../src/generation/controls.ts"],"sourcesContent":["/**\n * Declarative descriptions of generative models (what a model accepts) and of\n * the requests sent to them. Everything here is plain data so capabilities can\n * come from a server, be merged with local presentation overlays, and be\n * turned into JSON Schema for agents.\n */\n\nexport type GenerationMediaKind = 'image' | 'video' | 'audio' | 'text';\n\n/** What a reference input is used for. */\nexport type ReferenceRole =\n\t| 'start_frame'\n\t| 'end_frame'\n\t| 'style_ref'\n\t| 'character_ref'\n\t| 'background_ref'\n\t| 'mask'\n\t| 'image_ref'\n\t| 'video_ref'\n\t| 'audio_ref';\n\n/** Every reference role, in a stable display order. */\nexport const REFERENCE_ROLES: readonly ReferenceRole[] = [\n\t'start_frame',\n\t'end_frame',\n\t'style_ref',\n\t'character_ref',\n\t'background_ref',\n\t'mask',\n\t'image_ref',\n\t'video_ref',\n\t'audio_ref'\n];\n\n/** Human-readable default labels for reference roles. */\nexport const REFERENCE_ROLE_LABELS: Readonly<Record<ReferenceRole, string>> = {\n\tstart_frame: 'Start frame',\n\tend_frame: 'End frame',\n\tstyle_ref: 'Style reference',\n\tcharacter_ref: 'Character reference',\n\tbackground_ref: 'Background reference',\n\tmask: 'Mask',\n\timage_ref: 'Image reference',\n\tvideo_ref: 'Video reference',\n\taudio_ref: 'Audio reference'\n};\n\n/** A choice from a fixed list. `options` order matters (low → high where it applies). */\nexport interface EnumCapability<T extends string | number = string> {\n\toptions: readonly T[];\n\tdefault?: T;\n\t/** Display labels by option value. */\n\tlabels?: Readonly<Record<string, string>>;\n}\n\nexport interface TextFieldCapability {\n\tmaxLength?: number;\n}\n\nexport interface PromptCapability extends TextFieldCapability {\n\t/**\n\t * Count the resolved prompt (templates expanded, variables substituted)\n\t * against `maxLength` rather than the raw template text. Default `true`.\n\t * Pass the resolved text to the planner as `resolvedPrompt`.\n\t */\n\tcountResolved?: boolean;\n\t/** The prompt must be non-empty. */\n\trequired?: boolean;\n}\n\nexport interface CountCapability {\n\t/** Largest number of outputs per request. */\n\tmax: number;\n\t/** Predefined choices; when given, requests snap to one of them. */\n\toptions?: readonly number[];\n\tdefault?: number;\n}\n\nexport interface DurationCapability {\n\t/** Seconds. */\n\tmin?: number;\n\tmax?: number;\n\t/** Predefined choices; when given, requests snap to one of them. */\n\toptions?: readonly number[];\n\tdefault?: number;\n\tstep?: number;\n}\n\nexport interface SeedCapability {\n\tmin?: number;\n\tmax?: number;\n}\n\nexport interface ReferenceRoleCapability {\n\t/** Most references of this role. */\n\tmax: number;\n\t/** Fewest references of this role (e.g. an image-to-video model needs a `start_frame`). */\n\tmin?: number;\n\tlabel?: string;\n\tdescription?: string;\n}\n\nexport interface ReferenceCapability {\n\t/** Supported roles and their per-role limits. Roles not listed are unsupported. */\n\troles: Partial<Readonly<Record<ReferenceRole, ReferenceRoleCapability>>>;\n\t/** Most references across all roles. */\n\tmaxTotal?: number;\n}\n\nexport interface NumberParamSpec {\n\ttype: 'number' | 'integer';\n\tmin?: number;\n\tmax?: number;\n\tstep?: number;\n\tdefault?: number;\n\tlabel?: string;\n\tdescription?: string;\n}\n\nexport interface EnumParamSpec {\n\ttype: 'enum';\n\toptions: readonly (string | number)[];\n\tdefault?: string | number;\n\tlabel?: string;\n\tdescription?: string;\n}\n\nexport interface BooleanParamSpec {\n\ttype: 'boolean';\n\tdefault?: boolean;\n\tlabel?: string;\n\tdescription?: string;\n}\n\n/** A model-specific parameter (`guidance`, `motion_strength`, `style`, …). */\nexport type ExtraParamSpec = NumberParamSpec | EnumParamSpec | BooleanParamSpec;\n\n/** Rough timing used for progress estimates (`expectedDurationFor`). */\nexport interface TimingCapability {\n\t/** Fixed cost of one request in ms. */\n\tbaseMs: number;\n\t/** Extra ms per output beyond the first. */\n\tperItemMs?: number;\n\t/** Extra ms per second of requested duration (video/audio). */\n\tperSecondMs?: number;\n\t/** Extra ms per megapixel of the requested resolution. */\n\tperMegapixelMs?: number;\n}\n\n/** Presentation-only fields; overlays may set these (see `mergeCapabilities`). */\nexport interface CapabilityPresentation {\n\tname?: string;\n\tdescription?: string;\n\tbadges?: readonly string[];\n\ticon?: string;\n\tgroup?: string;\n}\n\n/** Everything a generative model accepts. Absent sections mean \"unsupported\". */\nexport interface ModelCapabilities extends CapabilityPresentation {\n\tid: string;\n\tmedia: GenerationMediaKind;\n\tprompt?: PromptCapability;\n\t/** Negative prompt support (`true` or limits). */\n\tnegativePrompt?: boolean | TextFieldCapability;\n\t/** System prompt support (`true` or limits). */\n\tsystemPrompt?: boolean | TextFieldCapability;\n\t/** E.g. `['1:1', '16:9', '9:16']`. */\n\taspectRatios?: EnumCapability<string>;\n\t/** E.g. `['512x512', '1024x1024']`, `['720p', '1080p']` or `['1k', '2k', '4k']`, low → high. */\n\tresolutions?: EnumCapability<string>;\n\t/** Ordered low → high, e.g. `['draft', 'standard', 'high']`. */\n\tquality?: EnumCapability<string>;\n\tcount?: CountCapability;\n\tduration?: DurationCapability;\n\tseed?: boolean | SeedCapability;\n\treferences?: ReferenceCapability;\n\t/** Accepts a source to edit (`mode: 'edit'`). */\n\tediting?: boolean;\n\t/** Accepts a source plus a `mask` reference (`mode: 'inpaint'`). */\n\tinpainting?: boolean;\n\tparams?: Readonly<Record<string, ExtraParamSpec>>;\n\ttiming?: TimingCapability;\n}\n\nexport interface GenerationReference {\n\t/** Asset id (opaque to this library). */\n\tid: string;\n\trole: ReferenceRole;\n\turl?: string;\n}\n\nexport type GenerationMode = 'generate' | 'edit' | 'inpaint';\n\nexport type GenerationParamValue = string | number | boolean;\n\n/** A request for one model. Every field is optional; the planner fills and fixes. */\nexport interface GenerationRequest {\n\tmodel?: string;\n\tprompt?: string;\n\tnegativePrompt?: string;\n\tsystemPrompt?: string;\n\taspectRatio?: string;\n\tresolution?: string;\n\tquality?: string;\n\tcount?: number;\n\t/** Seconds. */\n\tduration?: number;\n\tseed?: number;\n\tmode?: GenerationMode;\n\treferences?: GenerationReference[];\n\tparams?: Record<string, GenerationParamValue>;\n}\n\n/** Fields of {@link GenerationRequest} the planner knows about, in planning order. */\nexport const GENERATION_REQUEST_FIELDS = [\n\t'model',\n\t'prompt',\n\t'negativePrompt',\n\t'systemPrompt',\n\t'aspectRatio',\n\t'resolution',\n\t'quality',\n\t'count',\n\t'duration',\n\t'seed',\n\t'mode',\n\t'references',\n\t'params'\n] as const;\n\n/** Text field limits normalized from `boolean | TextFieldCapability`. */\nexport function textFieldCapability(value: boolean | TextFieldCapability | undefined): TextFieldCapability | null {\n\tif (!value) return null;\n\treturn value === true ? {} : value;\n}\n\n/** Seed limits normalized from `boolean | SeedCapability`. */\nexport function seedCapability(value: boolean | SeedCapability | undefined): SeedCapability | null {\n\tif (!value) return null;\n\treturn value === true ? {} : value;\n}\n\n/** Supported reference roles of a model in {@link REFERENCE_ROLES} order. */\nexport function supportedReferenceRoles(caps: ModelCapabilities): ReferenceRole[] {\n\tconst roles = caps.references?.roles ?? {};\n\treturn REFERENCE_ROLES.filter((role) => (roles[role]?.max ?? 0) > 0);\n}\n\n/** Supported generation modes of a model. */\nexport function supportedModes(caps: ModelCapabilities): GenerationMode[] {\n\tconst modes: GenerationMode[] = ['generate'];\n\tif (caps.editing) modes.push('edit');\n\tif (caps.inpainting) modes.push('inpaint');\n\treturn modes;\n}\n\nconst PRESENTATION_KEYS = ['name', 'description', 'badges', 'icon', 'group'] as const;\n\n/** A partial model entry used to decorate (or add) models locally. */\nexport type CapabilityOverlay = Partial<ModelCapabilities> & { id: string };\n\n/**\n * Merges server-reported capabilities with a local overlay. For models the\n * server knows, every capability value comes from `remote`; the overlay only\n * contributes presentation fields (`name`, `description`, `badges`, `icon`,\n * `group`), filling in or replacing the remote ones. Overlay entries for\n * models the server does not report are appended when they are complete\n * (have a `media` kind). Remote order is kept; overlay-only models follow in\n * overlay order.\n */\nexport function mergeCapabilities(\n\tremote: readonly ModelCapabilities[],\n\toverlay: readonly CapabilityOverlay[] = []\n): ModelCapabilities[] {\n\tconst overlayById = new Map(overlay.map((entry) => [entry.id, entry]));\n\tconst remoteIds = new Set(remote.map((model) => model.id));\n\tconst merged = remote.map((model) => {\n\t\tconst extra = overlayById.get(model.id);\n\t\tif (!extra) return { ...model };\n\t\tconst next: ModelCapabilities = { ...model };\n\t\tfor (const key of PRESENTATION_KEYS) {\n\t\t\tif (extra[key] !== undefined) (next as any)[key] = extra[key];\n\t\t}\n\t\treturn next;\n\t});\n\tfor (const entry of overlay) {\n\t\tif (remoteIds.has(entry.id) || !entry.media) continue;\n\t\tremoteIds.add(entry.id);\n\t\tmerged.push({ ...(entry as ModelCapabilities) });\n\t}\n\treturn merged;\n}\n","import {\n\tGENERATION_REQUEST_FIELDS,\n\tREFERENCE_ROLES,\n\tseedCapability,\n\tsupportedModes,\n\ttextFieldCapability,\n\ttype EnumCapability,\n\ttype ExtraParamSpec,\n\ttype GenerationParamValue,\n\ttype GenerationReference,\n\ttype GenerationRequest,\n\ttype ModelCapabilities,\n\ttype ReferenceRole,\n\ttype ReferenceRoleCapability\n} from './capabilities.js';\n\n/**\n * How the planner treats values the model does not support:\n *\n * - `error`: nothing is changed; every mismatch is an error.\n * - `nearest`: snap to the closest supported value (ties go to the higher\n * value), clamp ranges, truncate lists, drop unsupported fields and\n * unsupported references.\n * - `downgrade`: like `nearest`, but ties go to the lower value.\n * - `upgrade`: like `nearest`, but never drops references the model cannot\n * use (that would lose intent), so those are errors.\n *\n * \"Lower\" means a narrower aspect ratio, fewer pixels, an earlier quality\n * option, a smaller number.\n */\nexport type PlanStrategy = 'error' | 'upgrade' | 'downgrade' | 'nearest';\n\nexport type PlanAdjustmentKind = 'snapped' | 'clamped' | 'truncated' | 'dropped' | 'defaulted';\n\nexport interface PlanAdjustment {\n\t/** Request path, e.g. `aspectRatio`, `params.guidance`, `references.style_ref`. */\n\tfield: string;\n\tfrom: unknown;\n\tto: unknown;\n\treason: string;\n\tkind: PlanAdjustmentKind;\n}\n\nexport interface PlanError {\n\tfield: string;\n\tvalue: unknown;\n\tmessage: string;\n}\n\nexport interface GenerationPlan {\n\t/** `true` when there are no errors and `request` can be sent. */\n\tok: boolean;\n\t/** The adjusted request (always a copy; the input is never mutated). */\n\trequest: GenerationRequest;\n\tadjustments: PlanAdjustment[];\n\terrors: PlanError[];\n\t/** Model the plan was made for. */\n\tmodel: string;\n\tstrategy: PlanStrategy;\n}\n\nexport interface PlanOptions {\n\t/** Default `nearest`. */\n\tstrategy?: PlanStrategy;\n\t/**\n\t * The prompt with templates and variables resolved. Measured against\n\t * `prompt.maxLength` when the model counts resolved text (the default).\n\t */\n\tresolvedPrompt?: string;\n\t/** Fill missing fields that have a capability `default` (reported as `defaulted`). */\n\tfillDefaults?: boolean;\n\t/** Override whether references with unsupported roles may be dropped (default: `nearest` and `downgrade` only). */\n\tdropUnsupportedReferences?: boolean;\n}\n\nconst EPSILON = 1e-9;\n\n/** Numeric rank of an aspect ratio such as `16:9` (log of width / height). */\nexport function aspectRatioRank(value: string): number | undefined {\n\tconst match = /^\\s*(\\d+(?:\\.\\d+)?)\\s*[:x/×]\\s*(\\d+(?:\\.\\d+)?)\\s*$/i.exec(String(value));\n\tif (!match) return undefined;\n\tconst w = Number(match[1]);\n\tconst h = Number(match[2]);\n\tif (!(w > 0) || !(h > 0)) return undefined;\n\treturn Math.log(w / h);\n}\n\n/**\n * Numeric rank of a resolution: `1024x768` (pixels), `720p` (16:9 pixels at\n * that height) or `2k` (square of that many kibi-pixels). Log scale.\n */\nexport function resolutionRank(value: string): number | undefined {\n\tconst text = String(value).trim().toLowerCase();\n\tlet pixels: number | undefined;\n\tlet match = /^(\\d+(?:\\.\\d+)?)\\s*[x×*]\\s*(\\d+(?:\\.\\d+)?)$/.exec(text);\n\tif (match) pixels = Number(match[1]) * Number(match[2]);\n\telse if ((match = /^(\\d+(?:\\.\\d+)?)p$/.exec(text))) pixels = (Number(match[1]) ** 2 * 16) / 9;\n\telse if ((match = /^(\\d+(?:\\.\\d+)?)k$/.exec(text))) pixels = (Number(match[1]) * 1024) ** 2;\n\treturn pixels && pixels > 0 ? Math.log(pixels) : undefined;\n}\n\n/** Megapixels of a resolution string, when it can be parsed. */\nexport function resolutionMegapixels(value: string): number | undefined {\n\tconst rank = resolutionRank(value);\n\treturn rank === undefined ? undefined : Math.exp(rank) / 1_000_000;\n}\n\n/** Common quality names, low → high. Used to compare values missing from a model's options. */\nexport const QUALITY_LADDER: Readonly<Record<string, number>> = {\n\tdraft: 0,\n\tpreview: 0,\n\tlow: 1,\n\tfast: 1,\n\tturbo: 1,\n\tstandard: 2,\n\tnormal: 2,\n\tmedium: 2,\n\tbalanced: 2,\n\thigh: 3,\n\thd: 3,\n\tquality: 3,\n\tultra: 4,\n\tmax: 5,\n\tbest: 5\n};\n\nexport function qualityRank(value: string): number | undefined {\n\treturn QUALITY_LADDER[String(value).trim().toLowerCase()];\n}\n\nconst numberRank = (value: unknown) => (typeof value === 'number' && Number.isFinite(value) ? value : undefined);\n\n/**\n * Picks the option closest to `value` by `rank`. Ties go to the lower or\n * higher rank. Returns `undefined` when `value` or no option can be ranked.\n */\nexport function snapToOption<T>(\n\tvalue: unknown,\n\toptions: readonly T[],\n\trank: (value: any) => number | undefined,\n\ttie: 'lower' | 'higher'\n): T | undefined {\n\tconst target = rank(value);\n\tif (target === undefined) return undefined;\n\tlet best: { option: T; distance: number; rank: number } | undefined;\n\tfor (const option of options) {\n\t\tconst r = rank(option);\n\t\tif (r === undefined) continue;\n\t\tconst distance = Math.abs(r - target);\n\t\tif (\n\t\t\t!best ||\n\t\t\tdistance < best.distance - EPSILON ||\n\t\t\t(Math.abs(distance - best.distance) <= EPSILON && (tie === 'lower' ? r < best.rank : r > best.rank))\n\t\t) {\n\t\t\tbest = { option, distance, rank: r };\n\t\t}\n\t}\n\treturn best?.option;\n}\n\n/** Truncates to `max` UTF-16 units without splitting a surrogate pair. */\nfunction truncateText(text: string, max: number): string {\n\tif (text.length <= max) return text;\n\tlet end = max;\n\tconst code = text.charCodeAt(end - 1);\n\tif (end > 0 && code >= 0xd800 && code <= 0xdbff) end -= 1;\n\treturn text.slice(0, end);\n}\n\nfunction cloneRequest(request: GenerationRequest): GenerationRequest {\n\tconst copy: GenerationRequest = { ...request };\n\tif (request.references) copy.references = request.references.map((ref) => ({ ...ref }));\n\tif (request.params) copy.params = { ...request.params };\n\treturn copy;\n}\n\nconst describe = (value: unknown) => (typeof value === 'string' ? `\"${value}\"` : JSON.stringify(value));\nconst list = (options: readonly unknown[]) => options.map(describe).join(', ');\n\nclass Planner {\n\treadonly adjustments: PlanAdjustment[] = [];\n\treadonly errors: PlanError[] = [];\n\treadonly tie: 'lower' | 'higher';\n\treadonly strict: boolean;\n\n\tconstructor(\n\t\treadonly caps: ModelCapabilities,\n\t\treadonly request: GenerationRequest,\n\t\treadonly options: PlanOptions,\n\t\treadonly strategy: PlanStrategy\n\t) {\n\t\tthis.tie = strategy === 'downgrade' ? 'lower' : 'higher';\n\t\tthis.strict = strategy === 'error';\n\t}\n\n\tadjust(field: string, from: unknown, to: unknown, kind: PlanAdjustmentKind, reason: string) {\n\t\tthis.adjustments.push({ field, from, to, kind, reason });\n\t}\n\n\terror(field: string, value: unknown, message: string) {\n\t\tthis.errors.push({ field, value, message });\n\t}\n\n\t/** Removes an unsupported field (or reports it under `error`). */\n\tunsupported(field: keyof GenerationRequest, message: string) {\n\t\tconst value = this.request[field];\n\t\tif (this.strict) {\n\t\t\tthis.error(field, value, message);\n\t\t\treturn;\n\t\t}\n\t\tdelete this.request[field];\n\t\tthis.adjust(field, value, undefined, 'dropped', message);\n\t}\n\n\tdefaulted(field: string, value: unknown, set: () => void) {\n\t\tif (!this.options.fillDefaults || value === undefined) return;\n\t\tset();\n\t\tthis.adjust(field, undefined, value, 'defaulted', 'Filled with the model default.');\n\t}\n\n\tplanText(field: 'prompt' | 'negativePrompt' | 'systemPrompt', maxLength: number | undefined, measured?: string) {\n\t\tconst value = this.request[field];\n\t\tif (value === undefined || maxLength === undefined) return;\n\t\tif (typeof value !== 'string') {\n\t\t\tthis.error(field, value, `Expected text.`);\n\t\t\treturn;\n\t\t}\n\t\tconst text = measured ?? value;\n\t\tif (text.length <= maxLength) return;\n\t\tif (this.strict || measured !== undefined) {\n\t\t\tthis.error(\n\t\t\t\tfield,\n\t\t\t\ttext.length,\n\t\t\t\t`${measured !== undefined ? 'Resolved text' : 'Text'} is ${text.length} characters; the model accepts at most ${maxLength}.`\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tconst next = truncateText(value, maxLength);\n\t\tthis.request[field] = next;\n\t\tthis.adjust(field, value.length, next.length, 'truncated', `Truncated to the model's ${maxLength}-character limit.`);\n\t}\n\n\tplanEnum(\n\t\tfield: 'aspectRatio' | 'resolution' | 'quality',\n\t\tcap: EnumCapability<string> | undefined,\n\t\trank: (value: string) => number | undefined,\n\t\tlabel: string\n\t) {\n\t\tconst value = this.request[field];\n\t\tif (value === undefined) {\n\t\t\tif (cap) this.defaulted(field, cap.default, () => (this.request[field] = cap.default));\n\t\t\treturn;\n\t\t}\n\t\tif (!cap || cap.options.length === 0) {\n\t\t\tthis.unsupported(field, `The model does not take a ${label}.`);\n\t\t\treturn;\n\t\t}\n\t\tif (cap.options.includes(value)) return;\n\t\tif (this.strict) {\n\t\t\tthis.error(field, value, `${describe(value)} is not a supported ${label}; supported: ${list(cap.options)}.`);\n\t\t\treturn;\n\t\t}\n\t\tconst snapped = snapToOption(value, cap.options, rank, this.tie);\n\t\tconst next = snapped ?? cap.default ?? cap.options[0];\n\t\tthis.request[field] = next;\n\t\tthis.adjust(\n\t\t\tfield,\n\t\t\tvalue,\n\t\t\tnext,\n\t\t\t'snapped',\n\t\t\tsnapped !== undefined\n\t\t\t\t? `${describe(value)} is not supported; using the nearest ${label}.`\n\t\t\t\t: `${describe(value)} is not supported; using ${cap.default !== undefined ? 'the default' : 'the first option'}.`\n\t\t);\n\t}\n\n\t/** Clamps/rounds/snaps a number. Returns the next value or `undefined` after an error. */\n\tplanNumber(\n\t\tfield: string,\n\t\tvalue: unknown,\n\t\tspec: { min?: number; max?: number; step?: number; integer?: boolean; options?: readonly number[] },\n\t\tlabel: string\n\t): { value: number; changed: boolean } | undefined {\n\t\tif (typeof value !== 'number' || !Number.isFinite(value)) {\n\t\t\tthis.error(field, value, `Expected a number for ${label}.`);\n\t\t\treturn undefined;\n\t\t}\n\t\tconst options = spec.options?.filter(\n\t\t\t(o) => (spec.min === undefined || o >= spec.min) && (spec.max === undefined || o <= spec.max)\n\t\t);\n\t\tif (options && options.length > 0) {\n\t\t\tif (options.includes(value)) return { value, changed: false };\n\t\t\tif (this.strict) {\n\t\t\t\tthis.error(field, value, `${value} is not a supported ${label}; supported: ${list(options)}.`);\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tconst next = snapToOption(value, options, numberRank, this.tie)!;\n\t\t\tthis.adjust(field, value, next, 'snapped', `${value} is not supported; using the nearest ${label}.`);\n\t\t\treturn { value: next, changed: true };\n\t\t}\n\t\tlet next = value;\n\t\tif (spec.step !== undefined && spec.step > 0) {\n\t\t\tconst base = spec.min ?? 0;\n\t\t\tconst steps = (next - base) / spec.step;\n\t\t\tconst rounded = Math.abs(steps - Math.trunc(steps) - 0.5) < EPSILON\n\t\t\t\t? this.tie === 'lower' ? Math.floor(steps) : Math.ceil(steps)\n\t\t\t\t: Math.round(steps);\n\t\t\tnext = Number((base + rounded * spec.step).toPrecision(12));\n\t\t}\n\t\tif (spec.integer && !Number.isInteger(next)) {\n\t\t\tconst frac = next - Math.floor(next);\n\t\t\tnext = Math.abs(frac - 0.5) < EPSILON ? (this.tie === 'lower' ? Math.floor(next) : Math.ceil(next)) : Math.round(next);\n\t\t}\n\t\tlet kind: PlanAdjustmentKind = 'snapped';\n\t\tif (spec.min !== undefined && next < spec.min) {\n\t\t\tnext = spec.min;\n\t\t\tkind = 'clamped';\n\t\t}\n\t\tif (spec.max !== undefined && next > spec.max) {\n\t\t\tnext = spec.max;\n\t\t\tkind = 'clamped';\n\t\t}\n\t\tif (next === value) return { value, changed: false };\n\t\tconst range = `${spec.min ?? '-∞'}–${spec.max ?? '∞'}`;\n\t\tif (this.strict) {\n\t\t\tthis.error(\n\t\t\t\tfield,\n\t\t\t\tvalue,\n\t\t\t\tkind === 'clamped' ? `${label} must be within ${range}.` : `${value} is not a valid ${label} (try ${next}).`\n\t\t\t);\n\t\t\treturn undefined;\n\t\t}\n\t\tthis.adjust(\n\t\t\tfield,\n\t\t\tvalue,\n\t\t\tnext,\n\t\t\tkind,\n\t\t\tkind === 'clamped' ? `Clamped to the supported range ${range}.` : `Rounded to a supported ${label}.`\n\t\t);\n\t\treturn { value: next, changed: true };\n\t}\n\n\tplanCount() {\n\t\tconst value = this.request.count;\n\t\tconst cap = this.caps.count;\n\t\tif (value === undefined) {\n\t\t\tif (cap) this.defaulted('count', cap.default, () => (this.request.count = cap.default));\n\t\t\treturn;\n\t\t}\n\t\tif (!cap) {\n\t\t\tif (value === 1) return;\n\t\t\tthis.unsupported('count', 'The model produces one output per request.');\n\t\t\treturn;\n\t\t}\n\t\tconst result = this.planNumber('count', value, { min: 1, max: cap.max, integer: true, options: cap.options }, 'output count');\n\t\tif (result) this.request.count = result.value;\n\t}\n\n\tplanDuration() {\n\t\tconst value = this.request.duration;\n\t\tconst cap = this.caps.duration;\n\t\tif (value === undefined) {\n\t\t\tif (cap) this.defaulted('duration', cap.default, () => (this.request.duration = cap.default));\n\t\t\treturn;\n\t\t}\n\t\tif (!cap) {\n\t\t\tthis.unsupported('duration', 'The model does not take a duration.');\n\t\t\treturn;\n\t\t}\n\t\tconst result = this.planNumber('duration', value, cap, 'duration');\n\t\tif (result) this.request.duration = result.value;\n\t}\n\n\tplanSeed() {\n\t\tconst value = this.request.seed;\n\t\tif (value === undefined) return;\n\t\tconst cap = seedCapability(this.caps.seed);\n\t\tif (!cap) {\n\t\t\tthis.unsupported('seed', 'The model does not take a seed.');\n\t\t\treturn;\n\t\t}\n\t\tconst result = this.planNumber('seed', value, { ...cap, integer: true }, 'seed');\n\t\tif (result) this.request.seed = result.value;\n\t}\n\n\tplanMode() {\n\t\tconst mode = this.request.mode;\n\t\tif (mode === undefined) return;\n\t\tconst modes = supportedModes(this.caps);\n\t\tif (!modes.includes(mode)) {\n\t\t\tthis.error('mode', mode, `The model does not support ${describe(mode)}; supported: ${list(modes)}.`);\n\t\t}\n\t}\n\n\troleCapability(role: ReferenceRole): ReferenceRoleCapability | undefined {\n\t\tconst cap = this.caps.references?.roles[role];\n\t\tif (cap && cap.max > 0) return cap;\n\t\tif (role === 'mask' && this.caps.inpainting) return { max: 1 };\n\t\treturn undefined;\n\t}\n\n\tplanReferences() {\n\t\tconst refs = this.request.references;\n\t\tconst allowDrop =\n\t\t\t!this.strict &&\n\t\t\t(this.options.dropUnsupportedReferences ?? (this.strategy === 'nearest' || this.strategy === 'downgrade'));\n\t\tconst byRole = new Map<ReferenceRole, GenerationReference[]>();\n\t\tconst kept: GenerationReference[] = [];\n\t\tconst unsupported = new Map<string, number>();\n\t\tfor (const [index, ref] of (refs ?? []).entries()) {\n\t\t\tif (!ref || typeof ref.id !== 'string' || ref.id === '' || !REFERENCE_ROLES.includes(ref.role)) {\n\t\t\t\tthis.error(`references.${index}`, ref, 'Each reference needs an `id` and a known `role`.');\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!this.roleCapability(ref.role)) {\n\t\t\t\tunsupported.set(ref.role, (unsupported.get(ref.role) ?? 0) + 1);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst group = byRole.get(ref.role) ?? [];\n\t\t\tif (group.some((other) => other.id === ref.id)) {\n\t\t\t\tthis.adjust(`references.${ref.role}`, ref.id, undefined, 'dropped', `Duplicate reference \"${ref.id}\" removed.`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tgroup.push(ref);\n\t\t\tbyRole.set(ref.role, group);\n\t\t\tkept.push(ref);\n\t\t}\n\n\t\tfor (const [role, count] of unsupported) {\n\t\t\tconst message =\n\t\t\t\tthis.caps.media === 'text' || !this.caps.references\n\t\t\t\t\t? `The ${this.caps.media} model \"${this.caps.id}\" does not accept reference inputs (${role}).`\n\t\t\t\t\t: `The model does not accept ${role} references.`;\n\t\t\tif (allowDrop) this.adjust(`references.${role}`, count, 0, 'dropped', message);\n\t\t\telse this.error(`references.${role}`, count, message);\n\t\t}\n\n\t\t// Per-role limits.\n\t\tconst removed = new Set<GenerationReference>();\n\t\tfor (const role of REFERENCE_ROLES) {\n\t\t\tconst cap = this.roleCapability(role);\n\t\t\tconst group = byRole.get(role) ?? [];\n\t\t\tif (!cap) continue;\n\t\t\tif (group.length > cap.max) {\n\t\t\t\tif (this.strict) {\n\t\t\t\t\tthis.error(`references.${role}`, group.length, `At most ${cap.max} ${role} reference(s) are supported.`);\n\t\t\t\t} else {\n\t\t\t\t\tgroup.slice(cap.max).forEach((ref) => removed.add(ref));\n\t\t\t\t\tthis.adjust(\n\t\t\t\t\t\t`references.${role}`,\n\t\t\t\t\t\tgroup.length,\n\t\t\t\t\t\tcap.max,\n\t\t\t\t\t\t'truncated',\n\t\t\t\t\t\t`Kept the first ${cap.max} ${role} reference(s); the model accepts no more.`\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (cap.min !== undefined && group.length < cap.min) {\n\t\t\t\tthis.error(`references.${role}`, group.length, `At least ${cap.min} ${role} reference(s) are required.`);\n\t\t\t}\n\t\t}\n\t\tlet next = kept.filter((ref) => !removed.has(ref));\n\n\t\t// Total limit.\n\t\tconst maxTotal = this.caps.references?.maxTotal;\n\t\tif (maxTotal !== undefined && next.length > maxTotal) {\n\t\t\tif (this.strict) {\n\t\t\t\tthis.error('references', next.length, `At most ${maxTotal} references are supported in total.`);\n\t\t\t} else {\n\t\t\t\tthis.adjust(\n\t\t\t\t\t'references',\n\t\t\t\t\tnext.length,\n\t\t\t\t\tmaxTotal,\n\t\t\t\t\t'truncated',\n\t\t\t\t\t`Kept the first ${maxTotal} references; the model accepts no more in total.`\n\t\t\t\t);\n\t\t\t\tnext = next.slice(0, maxTotal);\n\t\t\t}\n\t\t}\n\n\t\tif (this.request.mode === 'inpaint' && !next.some((ref) => ref.role === 'mask')) {\n\t\t\tthis.error('references.mask', 0, 'Inpainting needs a `mask` reference.');\n\t\t}\n\n\t\tif (refs === undefined) return;\n\t\tif (!this.strict) {\n\t\t\tif (next.length > 0) this.request.references = next;\n\t\t\telse delete this.request.references;\n\t\t}\n\t}\n\n\tplanParam(name: string, spec: ExtraParamSpec | undefined, value: GenerationParamValue): GenerationParamValue | undefined {\n\t\tconst field = `params.${name}`;\n\t\tif (!spec) {\n\t\t\tif (this.strict) this.error(field, value, `Unknown parameter \"${name}\".`);\n\t\t\telse this.adjust(field, value, undefined, 'dropped', `The model has no \"${name}\" parameter.`);\n\t\t\treturn undefined;\n\t\t}\n\t\tconst label = spec.label ?? name;\n\t\tif (spec.type === 'boolean') {\n\t\t\tif (typeof value !== 'boolean') this.error(field, value, `Expected true or false for ${label}.`);\n\t\t\treturn value;\n\t\t}\n\t\tif (spec.type === 'enum') {\n\t\t\tif (spec.options.includes(value as string | number)) return value;\n\t\t\tif (this.strict) {\n\t\t\t\tthis.error(field, value, `${describe(value)} is not a supported ${label}; supported: ${list(spec.options)}.`);\n\t\t\t\treturn value;\n\t\t\t}\n\t\t\tconst numeric = spec.options.every((o) => typeof o === 'number');\n\t\t\tconst snapped = numeric ? snapToOption(value, spec.options, numberRank, this.tie) : undefined;\n\t\t\tconst next = snapped ?? spec.default ?? spec.options[0];\n\t\t\tthis.adjust(\n\t\t\t\tfield,\n\t\t\t\tvalue,\n\t\t\t\tnext,\n\t\t\t\t'snapped',\n\t\t\t\tsnapped !== undefined ? `Using the nearest supported ${label}.` : `${describe(value)} is not supported; using ${spec.default !== undefined ? 'the default' : 'the first option'}.`\n\t\t\t);\n\t\t\treturn next;\n\t\t}\n\t\tconst result = this.planNumber(field, value, { ...spec, integer: spec.type === 'integer' }, label);\n\t\treturn result ? result.value : value;\n\t}\n\n\tplanParams() {\n\t\tconst params = this.request.params;\n\t\tconst specs = this.caps.params ?? {};\n\t\tconst next: Record<string, GenerationParamValue> = {};\n\t\tfor (const [name, value] of Object.entries(params ?? {})) {\n\t\t\tif (value === undefined) continue;\n\t\t\tconst planned = this.planParam(name, specs[name], value);\n\t\t\tif (planned !== undefined) next[name] = planned;\n\t\t\telse if (this.strict) next[name] = value;\n\t\t}\n\t\tif (this.options.fillDefaults) {\n\t\t\tfor (const [name, spec] of Object.entries(specs)) {\n\t\t\t\tif (next[name] === undefined && spec.default !== undefined) {\n\t\t\t\t\tnext[name] = spec.default;\n\t\t\t\t\tthis.adjust(`params.${name}`, undefined, spec.default, 'defaulted', 'Filled with the model default.');\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (Object.keys(next).length > 0) this.request.params = next;\n\t\telse delete this.request.params;\n\t}\n\n\trun(): void {\n\t\tconst { caps, request } = this;\n\t\tfor (const key of Object.keys(request)) {\n\t\t\tif ((GENERATION_REQUEST_FIELDS as readonly string[]).includes(key)) continue;\n\t\t\tconst value = (request as any)[key];\n\t\t\tif (this.strict) this.error(key, value, `Unknown request field \"${key}\".`);\n\t\t\telse {\n\t\t\t\tdelete (request as any)[key];\n\t\t\t\tthis.adjust(key, value, undefined, 'dropped', `Unknown request field \"${key}\".`);\n\t\t\t}\n\t\t}\n\n\t\tif (request.model !== undefined && request.model !== caps.id) {\n\t\t\tthis.error('model', request.model, `The request targets \"${request.model}\" but the plan is for \"${caps.id}\".`);\n\t\t}\n\t\trequest.model = caps.id;\n\n\t\t// Text fields.\n\t\tconst promptCap = caps.prompt ?? {};\n\t\tif (promptCap.required && !(request.prompt ?? '').trim()) {\n\t\t\tthis.error('prompt', request.prompt, 'A prompt is required.');\n\t\t}\n\t\tconst countResolved = promptCap.countResolved ?? true;\n\t\tconst measured =\n\t\t\tcountResolved && this.options.resolvedPrompt !== undefined && this.options.resolvedPrompt !== request.prompt\n\t\t\t\t? this.options.resolvedPrompt\n\t\t\t\t: undefined;\n\t\tthis.planText('prompt', promptCap.maxLength, measured);\n\t\tfor (const field of ['negativePrompt', 'systemPrompt'] as const) {\n\t\t\tif (request[field] === undefined) continue;\n\t\t\tconst cap = textFieldCapability(caps[field]);\n\t\t\tif (!cap) {\n\t\t\t\tthis.unsupported(field, `The model does not take a ${field === 'negativePrompt' ? 'negative' : 'system'} prompt.`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis.planText(field, cap.maxLength);\n\t\t}\n\n\t\tthis.planEnum('aspectRatio', caps.aspectRatios, aspectRatioRank, 'aspect ratio');\n\t\tthis.planEnum('resolution', caps.resolutions, resolutionRank, 'resolution');\n\t\tthis.planEnum('quality', caps.quality, qualityRank, 'quality');\n\t\tthis.planCount();\n\t\tthis.planDuration();\n\t\tthis.planSeed();\n\t\tthis.planMode();\n\t\tthis.planReferences();\n\t\tthis.planParams();\n\t}\n}\n\n/**\n * Plans `request` against a model's capabilities before sending it: snaps\n * enum values (aspect ratio, resolution, quality, count/duration choices) to\n * the nearest supported option, clamps ranges, truncates text and reference\n * lists over their limits, drops unsupported fields, and reports every change\n * in `adjustments` and every unfixable problem in `errors`.\n *\n * Pure and deterministic: the input is not mutated and the same input always\n * gives the same plan.\n */\nexport function planGenerationRequest(\n\trequest: GenerationRequest,\n\tcaps: ModelCapabilities,\n\toptions: PlanOptions = {}\n): GenerationPlan {\n\tconst strategy = options.strategy ?? 'nearest';\n\tconst planner = new Planner(caps, cloneRequest(request ?? {}), options, strategy);\n\tplanner.run();\n\treturn {\n\t\tok: planner.errors.length === 0,\n\t\trequest: planner.request,\n\t\tadjustments: planner.adjustments,\n\t\terrors: planner.errors,\n\t\tmodel: caps.id,\n\t\tstrategy\n\t};\n}\n","import type { JsonSchema } from '../agent/schema.js';\nimport {\n\tREFERENCE_ROLE_LABELS,\n\tseedCapability,\n\tsupportedModes,\n\tsupportedReferenceRoles,\n\ttextFieldCapability,\n\ttype EnumCapability,\n\ttype ExtraParamSpec,\n\ttype ModelCapabilities\n} from './capabilities.js';\n\nfunction enumSchema(cap: EnumCapability<string>, description: string): JsonSchema {\n\treturn {\n\t\ttype: 'string',\n\t\tenum: [...cap.options],\n\t\t...(cap.default !== undefined ? { default: cap.default } : {}),\n\t\tdescription\n\t};\n}\n\nfunction paramSchema(name: string, spec: ExtraParamSpec): JsonSchema {\n\tconst description = spec.description ?? spec.label ?? name;\n\tif (spec.type === 'boolean') {\n\t\treturn { type: 'boolean', description, ...(spec.default !== undefined ? { default: spec.default } : {}) };\n\t}\n\tif (spec.type === 'enum') {\n\t\tconst numeric = spec.options.every((o) => typeof o === 'number');\n\t\treturn {\n\t\t\ttype: numeric ? 'number' : 'string',\n\t\t\tenum: [...spec.options],\n\t\t\tdescription,\n\t\t\t...(spec.default !== undefined ? { default: spec.default } : {})\n\t\t};\n\t}\n\treturn {\n\t\ttype: spec.type,\n\t\tdescription: spec.step !== undefined ? `${description} (step ${spec.step})` : description,\n\t\t...(spec.min !== undefined ? { minimum: spec.min } : {}),\n\t\t...(spec.max !== undefined ? { maximum: spec.max } : {}),\n\t\t...(spec.default !== undefined ? { default: spec.default } : {})\n\t};\n}\n\n/**\n * JSON Schema for a request to one model: enums for choices, `minimum` /\n * `maximum` for ranges, `maxItems` for reference lists and `description`s that\n * spell out limits the schema cannot express (per-role reference counts,\n * resolved-prompt length). Unsupported fields are absent and\n * `additionalProperties` is `false`, so `validateJsonSchema` rejects them.\n */\nexport function capabilitiesToJsonSchema(caps: ModelCapabilities): JsonSchema & { type: 'object' } {\n\tconst properties: Record<string, JsonSchema> = {\n\t\tmodel: { type: 'string', const: caps.id, description: 'Model id.' }\n\t};\n\tconst required: string[] = [];\n\n\tconst prompt = caps.prompt ?? {};\n\tconst countResolved = prompt.countResolved ?? true;\n\tproperties.prompt = {\n\t\ttype: 'string',\n\t\tdescription:\n\t\t\tprompt.maxLength !== undefined\n\t\t\t\t? `Prompt text. At most ${prompt.maxLength} characters${countResolved ? ' after templates and variables are resolved' : ''}.`\n\t\t\t\t: 'Prompt text.',\n\t\t...(prompt.maxLength !== undefined && !countResolved ? { maxLength: prompt.maxLength } : {}),\n\t\t...(prompt.required ? { minLength: 1 } : {})\n\t};\n\tif (prompt.required) required.push('prompt');\n\n\tconst negative = textFieldCapability(caps.negativePrompt);\n\tif (negative) {\n\t\tproperties.negativePrompt = {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'What to avoid in the output.',\n\t\t\t...(negative.maxLength !== undefined ? { maxLength: negative.maxLength } : {})\n\t\t};\n\t}\n\tconst system = textFieldCapability(caps.systemPrompt);\n\tif (system) {\n\t\tproperties.systemPrompt = {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'System instructions.',\n\t\t\t...(system.maxLength !== undefined ? { maxLength: system.maxLength } : {})\n\t\t};\n\t}\n\n\tif (caps.aspectRatios?.options.length) properties.aspectRatio = enumSchema(caps.aspectRatios, 'Aspect ratio (width:height).');\n\tif (caps.resolutions?.options.length) properties.resolution = enumSchema(caps.resolutions, 'Output resolution, low to high.');\n\tif (caps.quality?.options.length) properties.quality = enumSchema(caps.quality, 'Quality level, low to high.');\n\n\tif (caps.count) {\n\t\tconst options = caps.count.options?.filter((o) => o >= 1 && o <= caps.count!.max);\n\t\tproperties.count = options?.length\n\t\t\t? { type: 'integer', enum: options, description: 'Number of outputs.' }\n\t\t\t: { type: 'integer', minimum: 1, maximum: caps.count.max, description: 'Number of outputs.' };\n\t\tif (caps.count.default !== undefined) properties.count.default = caps.count.default;\n\t}\n\n\tif (caps.duration) {\n\t\tconst d = caps.duration;\n\t\tconst options = d.options?.filter((o) => (d.min === undefined || o >= d.min) && (d.max === undefined || o <= d.max));\n\t\tproperties.duration = options?.length\n\t\t\t? { type: 'number', enum: options, description: 'Duration in seconds.' }\n\t\t\t: {\n\t\t\t\t\ttype: 'number',\n\t\t\t\t\tdescription: d.step !== undefined ? `Duration in seconds (step ${d.step}).` : 'Duration in seconds.',\n\t\t\t\t\t...(d.min !== undefined ? { minimum: d.min } : {}),\n\t\t\t\t\t...(d.max !== undefined ? { maximum: d.max } : {})\n\t\t\t\t};\n\t\tif (d.default !== undefined) properties.duration.default = d.default;\n\t}\n\n\tconst seed = seedCapability(caps.seed);\n\tif (seed) {\n\t\tproperties.seed = {\n\t\t\ttype: 'integer',\n\t\t\tdescription: 'Random seed for reproducible output.',\n\t\t\t...(seed.min !== undefined ? { minimum: seed.min } : {}),\n\t\t\t...(seed.max !== undefined ? { maximum: seed.max } : {})\n\t\t};\n\t}\n\n\tconst modes = supportedModes(caps);\n\tif (modes.length > 1) {\n\t\tproperties.mode = { type: 'string', enum: modes, default: 'generate', description: 'Generate, edit a source, or inpaint with a mask.' };\n\t}\n\n\tconst roles = supportedReferenceRoles(caps);\n\tif (caps.inpainting && !roles.includes('mask')) roles.push('mask');\n\tif (roles.length > 0) {\n\t\tconst limits = roles.map((role) => {\n\t\t\tconst cap = caps.references?.roles[role] ?? { max: 1 };\n\t\t\tconst min = cap.min ? `${cap.min}–` : 'up to ';\n\t\t\treturn `${role} (${cap.label ?? REFERENCE_ROLE_LABELS[role]}): ${min}${cap.max}`;\n\t\t});\n\t\tconst perRoleTotal = roles.reduce((sum, role) => sum + (caps.references?.roles[role]?.max ?? 1), 0);\n\t\tconst maxItems = Math.min(caps.references?.maxTotal ?? Infinity, perRoleTotal);\n\t\tproperties.references = {\n\t\t\ttype: 'array',\n\t\t\tdescription: `Reference inputs by role. Limits: ${limits.join('; ')}${\n\t\t\t\tcaps.references?.maxTotal !== undefined ? `; at most ${caps.references.maxTotal} in total` : ''\n\t\t\t}.`,\n\t\t\tmaxItems,\n\t\t\titems: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tid: { type: 'string', minLength: 1, description: 'Asset id.' },\n\t\t\t\t\trole: { type: 'string', enum: roles },\n\t\t\t\t\turl: { type: 'string' }\n\t\t\t\t},\n\t\t\t\trequired: ['id', 'role'],\n\t\t\t\tadditionalProperties: false\n\t\t\t}\n\t\t};\n\t\tif (roles.some((role) => (caps.references?.roles[role]?.min ?? 0) > 0)) required.push('references');\n\t}\n\n\tconst params = Object.entries(caps.params ?? {});\n\tif (params.length > 0) {\n\t\tproperties.params = {\n\t\t\ttype: 'object',\n\t\t\tdescription: 'Model-specific parameters.',\n\t\t\tproperties: Object.fromEntries(params.map(([name, spec]) => [name, paramSchema(name, spec)])),\n\t\t\tadditionalProperties: false\n\t\t};\n\t}\n\n\treturn {\n\t\ttype: 'object',\n\t\ttitle: caps.name ?? caps.id,\n\t\tdescription: `${caps.description ? `${caps.description} ` : ''}(${caps.media} model \"${caps.id}\")`,\n\t\tproperties,\n\t\t...(required.length ? { required } : {}),\n\t\tadditionalProperties: false\n\t};\n}\n","import type { AgentTool, AgentToolProvider, ToolCallContext } from '../agent/registry.js';\nimport type { JsonSchema } from '../agent/schema.js';\nimport { REFERENCE_ROLES, type GenerationRequest, type ModelCapabilities } from './capabilities.js';\nimport { planGenerationRequest, type GenerationPlan, type PlanStrategy } from './plan.js';\nimport { capabilitiesToJsonSchema } from './schema.js';\n\nexport interface GenerateContext {\n\tmodel: ModelCapabilities;\n\tplan: GenerationPlan;\n\tidempotencyKey: string;\n\tsignal?: AbortSignal;\n}\n\nexport interface EstimateContext {\n\tmodel: ModelCapabilities;\n\tplan: GenerationPlan;\n\tsignal?: AbortSignal;\n}\n\nexport interface GenerationToolProviderOptions {\n\t/** Provider id (default `generation`). */\n\tid?: string;\n\tnamespace?: string;\n\t/** Models, or a function returning the current models (re-read on every list/call). */\n\tmodels: readonly ModelCapabilities[] | (() => readonly ModelCapabilities[]);\n\t/** Sends a planned request. Its resolved value is the tool result (e.g. `{ jobId }`). */\n\tgenerate: (request: GenerationRequest, context: GenerateContext) => unknown | Promise<unknown>;\n\t/** Optional cost/time estimate; adds the `estimate_generation` tool. */\n\testimate?: (request: GenerationRequest, context: EstimateContext) => unknown | Promise<unknown>;\n\t/** Strategy used when the caller does not pass one (default `nearest`). */\n\tdefaultStrategy?: PlanStrategy;\n\t/** Completed idempotency keys remembered (default 500, oldest evicted first). */\n\tmaxIdempotencyKeys?: number;\n\t/** Lets the host signal that the model list changed. */\n\tsubscribe?: AgentToolProvider['subscribe'];\n}\n\nexport interface GenerationToolProvider extends AgentToolProvider {\n\t/** Forgets remembered idempotency keys (all, or one). */\n\tclearIdempotencyKeys(key?: string): void;\n}\n\nconst STRATEGIES: PlanStrategy[] = ['nearest', 'upgrade', 'downgrade', 'error'];\n\nconst requestSchema: JsonSchema = {\n\ttype: 'object',\n\tdescription:\n\t\t'Generation request. Call list_models for the fields each model supports; unsupported values are adjusted per `strategy`.',\n\tproperties: {\n\t\tprompt: { type: 'string' },\n\t\tnegativePrompt: { type: 'string' },\n\t\tsystemPrompt: { type: 'string' },\n\t\taspectRatio: { type: 'string', description: 'E.g. \"16:9\".' },\n\t\tresolution: { type: 'string' },\n\t\tquality: { type: 'string' },\n\t\tcount: { type: 'integer', minimum: 1 },\n\t\tduration: { type: 'number', minimum: 0, description: 'Seconds.' },\n\t\tseed: { type: 'integer' },\n\t\tmode: { type: 'string', enum: ['generate', 'edit', 'inpaint'] },\n\t\treferences: {\n\t\t\ttype: 'array',\n\t\t\titems: {\n\t\t\t\ttype: 'object',\n\t\t\t\tproperties: {\n\t\t\t\t\tid: { type: 'string', minLength: 1 },\n\t\t\t\t\trole: { type: 'string', enum: [...REFERENCE_ROLES] },\n\t\t\t\t\turl: { type: 'string' }\n\t\t\t\t},\n\t\t\t\trequired: ['id', 'role'],\n\t\t\t\tadditionalProperties: false\n\t\t\t}\n\t\t},\n\t\tparams: { type: 'object', additionalProperties: { type: ['string', 'number', 'boolean'] } }\n\t},\n\tadditionalProperties: false\n};\n\nconst strategySchema: JsonSchema = {\n\ttype: 'string',\n\tenum: STRATEGIES,\n\tdescription:\n\t\t'How to handle unsupported values: nearest (snap/clamp, ties up), downgrade (ties down), upgrade (ties up, never drops references), error (change nothing).'\n};\n\n/** Stable JSON (sorted object keys) used to compare retried arguments. */\nfunction stableStringify(value: unknown): string {\n\tif (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;\n\tif (value && typeof value === 'object') {\n\t\tconst entries = Object.keys(value as object)\n\t\t\t.filter((key) => (value as any)[key] !== undefined)\n\t\t\t.sort()\n\t\t\t.map((key) => `${JSON.stringify(key)}:${stableStringify((value as any)[key])}`);\n\t\treturn `{${entries.join(',')}}`;\n\t}\n\treturn JSON.stringify(value) ?? 'null';\n}\n\nfunction planFailure(plan: GenerationPlan) {\n\treturn {\n\t\tisError: true,\n\t\tcontent: [\n\t\t\t{\n\t\t\t\ttype: 'text',\n\t\t\t\ttext: `The request cannot be sent to \"${plan.model}\":\\n${plan.errors.map((e) => `- ${e.field}: ${e.message}`).join('\\n')}`\n\t\t\t}\n\t\t],\n\t\tstructuredContent: { error: { code: 'plan_failed', message: 'Request planning failed.' }, plan }\n\t};\n}\n\n/**\n * Exposes generation models to a `ToolRegistry`:\n *\n * - `list_models` (read-only): ids, presentation fields and per-model request schemas.\n * - `plan_generation` (read-only): the adjusted request, adjustments and errors.\n * - `estimate_generation` (read-only, only with `estimate`): your estimate for the planned request.\n * - `generate` (destructive): plans, then calls `generate` with the adjusted\n * request. Requires an `idempotencyKey`: a retry with the same key and\n * arguments returns the first call's result (or joins it while in flight)\n * instead of generating again; the same key with different arguments is\n * rejected. Failed calls forget their key so they can be retried.\n */\nexport function createGenerationToolProvider(options: GenerationToolProviderOptions): GenerationToolProvider {\n\tconst readModels = () => (typeof options.models === 'function' ? options.models() : options.models);\n\tconst defaultStrategy = options.defaultStrategy ?? 'nearest';\n\tconst maxKeys = Math.max(1, options.maxIdempotencyKeys ?? 500);\n\tconst calls = new Map<string, { signature: string; result: Promise<unknown> }>();\n\n\tconst findModel = (id: unknown) => {\n\t\tconst model = readModels().find((m) => m.id === id);\n\t\tif (!model) throw new Error(`Unknown model \"${String(id)}\". Call list_models for the available ids.`);\n\t\treturn model;\n\t};\n\n\tconst plan = (args: Record<string, any>) => {\n\t\tconst model = findModel(args.model);\n\t\tconst request: GenerationRequest = { ...(args.request ?? {}), model: model.id };\n\t\treturn {\n\t\t\tmodel,\n\t\t\tplan: planGenerationRequest(request, model, {\n\t\t\t\tstrategy: args.strategy ?? defaultStrategy,\n\t\t\t\tresolvedPrompt: args.resolvedPrompt\n\t\t\t})\n\t\t};\n\t};\n\n\tconst planInput = (): JsonSchema & { type: 'object' } => {\n\t\tconst ids = readModels().map((m) => m.id);\n\t\treturn {\n\t\t\ttype: 'object',\n\t\t\tproperties: {\n\t\t\t\tmodel: { type: 'string', ...(ids.length ? { enum: ids } : {}), description: 'Model id from list_models.' },\n\t\t\t\trequest: requestSchema,\n\t\t\t\tstrategy: strategySchema,\n\t\t\t\tresolvedPrompt: {\n\t\t\t\t\ttype: 'string',\n\t\t\t\t\tdescription: 'The prompt with templates and variables resolved, when `request.prompt` is a template.'\n\t\t\t\t}\n\t\t\t},\n\t\t\trequired: ['model', 'request'],\n\t\t\tadditionalProperties: false\n\t\t};\n\t};\n\n\tconst tools = (): AgentTool[] => {\n\t\tconst list: AgentTool[] = [\n\t\t\t{\n\t\t\t\tname: 'list_models',\n\t\t\t\ttitle: 'List generation models',\n\t\t\t\tdescription:\n\t\t\t\t\t'Lists the available generation models with their media kind, description and the JSON Schema of the request each accepts.',\n\t\t\t\tinputSchema: {\n\t\t\t\t\ttype: 'object',\n\t\t\t\t\tproperties: {\n\t\t\t\t\t\tmedia: { type: 'string', enum: ['image', 'video', 'audio', 'text'], description: 'Only models of this kind.' }\n\t\t\t\t\t},\n\t\t\t\t\tadditionalProperties: false\n\t\t\t\t},\n\t\t\t\tannotations: {\n\t\t\t\t\ttitle: 'List generation models',\n\t\t\t\t\treadOnlyHint: true,\n\t\t\t\t\tdestructiveHint: false,\n\t\t\t\t\tidempotentHint: true,\n\t\t\t\t\topenWorldHint: false\n\t\t\t\t},\n\t\t\t\thandler: (args) => ({\n\t\t\t\t\tmodels: readModels()\n\t\t\t\t\t\t.filter((m) => !args.media || m.media === args.media)\n\t\t\t\t\t\t.map((m) => ({\n\t\t\t\t\t\t\tid: m.id,\n\t\t\t\t\t\t\tmedia: m.media,\n\t\t\t\t\t\t\t...(m.name ? { name: m.name } : {}),\n\t\t\t\t\t\t\t...(m.description ? { description: m.description } : {}),\n\t\t\t\t\t\t\t...(m.badges?.length ? { badges: [...m.badges] } : {}),\n\t\t\t\t\t\t\trequestSchema: capabilitiesToJsonSchema(m)\n\t\t\t\t\t\t}))\n\t\t\t\t})\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: 'plan_generation',\n\t\t\t\ttitle: 'Plan a generation request',\n\t\t\t\tdescription:\n\t\t\t\t\t'Checks a request against a model without generating: returns the adjusted request, every adjustment (field, from, to, reason) and errors.',\n\t\t\t\tinputSchema: planInput(),\n\t\t\t\tannotations: {\n\t\t\t\t\ttitle: 'Plan a generation request',\n\t\t\t\t\treadOnlyHint: true,\n\t\t\t\t\tdestructiveHint: false,\n\t\t\t\t\tidempotentHint: true,\n\t\t\t\t\topenWorldHint: false\n\t\t\t\t},\n\t\t\t\thandler: (args) => ({ plan: plan(args).plan })\n\t\t\t}\n\t\t];\n\n\t\tif (options.estimate) {\n\t\t\tconst estimate = options.estimate;\n\t\t\tlist.push({\n\t\t\t\tname: 'estimate_generation',\n\t\t\t\ttitle: 'Estimate a generation',\n\t\t\t\tdescription: 'Estimates cost and/or time of a request after planning it. Does not generate anything.',\n\t\t\t\tinputSchema: planInput(),\n\t\t\t\tannotations: {\n\t\t\t\t\ttitle: 'Estimate a generation',\n\t\t\t\t\treadOnlyHint: true,\n\t\t\t\t\tdestructiveHint: false,\n\t\t\t\t\tidempotentHint: true,\n\t\t\t\t\topenWorldHint: true\n\t\t\t\t},\n\t\t\t\thandler: async (args, context: ToolCallContext) => {\n\t\t\t\t\tconst planned = plan(args);\n\t\t\t\t\tif (!planned.plan.ok) return planFailure(planned.plan);\n\t\t\t\t\tconst value = await estimate(planned.plan.request, { ...planned, signal: context.signal });\n\t\t\t\t\treturn { plan: planned.plan, estimate: value };\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tconst generateInput = planInput();\n\t\tlist.push({\n\t\t\tname: 'generate',\n\t\t\ttitle: 'Generate media',\n\t\t\tdescription:\n\t\t\t\t'Plans the request and starts a generation. Pass a fresh `idempotencyKey` per intended generation and reuse it when retrying, so a retry never generates twice.',\n\t\t\tinputSchema: {\n\t\t\t\t...generateInput,\n\t\t\t\tproperties: {\n\t\t\t\t\t...generateInput.properties,\n\t\t\t\t\tidempotencyKey: {\n\t\t\t\t\t\ttype: 'string',\n\t\t\t\t\t\tminLength: 1,\n\t\t\t\t\t\tmaxLength: 200,\n\t\t\t\t\t\tdescription: 'Unique per intended generation; reuse it to retry safely.'\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\trequired: ['model', 'request', 'idempotencyKey']\n\t\t\t},\n\t\t\tannotations: {\n\t\t\t\ttitle: 'Generate media',\n\t\t\t\treadOnlyHint: false,\n\t\t\t\tdestructiveHint: true,\n\t\t\t\tidempotentHint: true,\n\t\t\t\topenWorldHint: true\n\t\t\t},\n\t\t\thandler: async (args, context: ToolCallContext) => {\n\t\t\t\tconst key = String(args.idempotencyKey);\n\t\t\t\tconst { idempotencyKey: _key, ...rest } = args;\n\t\t\t\tconst signature = stableStringify(rest);\n\t\t\t\tconst existing = calls.get(key);\n\t\t\t\tif (existing) {\n\t\t\t\t\tif (existing.signature !== signature) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`Idempotency key \"${key}\" was already used with different arguments. Use a new key for a new generation.`\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\treturn { ...(await existing.result as object), deduplicated: true };\n\t\t\t\t}\n\t\t\t\tconst planned = plan(args);\n\t\t\t\tif (!planned.plan.ok) return planFailure(planned.plan);\n\t\t\t\tconst result = Promise.resolve()\n\t\t\t\t\t.then(() =>\n\t\t\t\t\t\toptions.generate(planned.plan.request, {\n\t\t\t\t\t\t\t...planned,\n\t\t\t\t\t\t\tidempotencyKey: key,\n\t\t\t\t\t\t\tsignal: context.signal\n\t\t\t\t\t\t})\n\t\t\t\t\t)\n\t\t\t\t\t.then((value) => ({\n\t\t\t\t\t\tresult: value,\n\t\t\t\t\t\tplan: planned.plan,\n\t\t\t\t\t\tidempotencyKey: key\n\t\t\t\t\t}));\n\t\t\t\tcalls.set(key, { signature, result });\n\t\t\t\twhile (calls.size > maxKeys) calls.delete(calls.keys().next().value as string);\n\t\t\t\ttry {\n\t\t\t\t\treturn await result;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (calls.get(key)?.result === result) calls.delete(key);\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\treturn list;\n\t};\n\n\treturn {\n\t\tid: options.id ?? 'generation',\n\t\t...(options.namespace ? { namespace: options.namespace } : {}),\n\t\ttools,\n\t\t...(options.subscribe ? { subscribe: options.subscribe } : {}),\n\t\tclearIdempotencyKeys(key?: string) {\n\t\t\tif (key === undefined) calls.clear();\n\t\t\telse calls.delete(key);\n\t\t}\n\t};\n}\n","import { getLatestVersion, getTemplateBody, resolvePrompt } from '../grammar/engine.js';\nimport type { SourceMapSegment } from '../grammar/sourcemap.js';\nimport { tokenizePrompt } from '../grammar/tokenizer.js';\nimport type { PromptValues, Template } from '../grammar/tokens.js';\nimport type { GenerationRequest, ModelCapabilities, ReferenceRole } from './capabilities.js';\nimport type { GenerationPlan, PlanAdjustment } from './plan.js';\n\nexport const PROVENANCE_FORMAT = 'pixerate.generation-provenance';\nexport const PROVENANCE_VERSION = 1;\n\n/** The exact template body a generation used. */\nexport interface PinnedTemplate {\n\tname: string;\n\ttemplateId?: string;\n\t/** Version id or version label the body came from (absent for unversioned templates). */\n\tversionId?: string;\n\tversion?: string | number;\n\tbody: string;\n}\n\n/** Everything needed to explain and reproduce one generation. */\nexport interface GenerationProvenance {\n\tformat: typeof PROVENANCE_FORMAT;\n\tversion: typeof PROVENANCE_VERSION;\n\t/** Raw prompt as typed, with `{{templates}}` and `{variables}`. */\n\trawPrompt: string;\n\t/** Every template the prompt reached (recursively), pinned to the body used. */\n\ttemplates: PinnedTemplate[];\n\t/** Version bindings in effect (`{ templateName: versionId }`) for every pinned versioned template. */\n\tbindings: Record<string, string>;\n\t/** Variable values, or `null` when variables were left unresolved. */\n\tvalues: PromptValues | null;\n\tresolvedPrompt: string;\n\tsourceMap: SourceMapSegment[];\n\tmodelId: string;\n\t/** The planned (adjusted) request that was sent. */\n\trequest: GenerationRequest;\n\tadjustments: PlanAdjustment[];\n\treferences: { id: string; role: ReferenceRole }[];\n\t/** ISO timestamps. */\n\tcreatedAt: string;\n\tstartedAt?: string;\n\tcompletedAt?: string;\n\t/** Ids of the outputs this generation produced. */\n\toutputIds?: string[];\n\tmeta?: Record<string, unknown>;\n}\n\nexport interface CreateProvenanceOptions {\n\trawPrompt: string;\n\ttemplates?: Template[];\n\t/** Template version bindings (`{ templateName: versionIdOrVersion }`). */\n\tbindings?: Record<string, string>;\n\tvalues?: PromptValues;\n\tmodel: string | ModelCapabilities;\n\t/** The plan the request came from (its request and adjustments are recorded) … */\n\tplan?: GenerationPlan;\n\t/** … or the request that was sent. */\n\trequest?: GenerationRequest;\n\tadjustments?: PlanAdjustment[];\n\t/** Creation time (default `Date.now()`). */\n\tcreatedAt?: Date | number | string;\n\tstartedAt?: Date | number | string;\n\tcompletedAt?: Date | number | string;\n\toutputIds?: string[];\n\tmeta?: Record<string, unknown>;\n\tmaxDepth?: number;\n}\n\nexport class ProvenanceParseError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = 'ProvenanceParseError';\n\t}\n}\n\nconst toIso = (value: Date | number | string) => new Date(value).toISOString();\nconst clone = <T>(value: T): T => (value === undefined ? value : JSON.parse(JSON.stringify(value)));\n\n/** Collects the templates a prompt reaches, with the body each one resolves to. */\nfunction pinTemplates(\n\trawPrompt: string,\n\ttemplates: Template[],\n\tbindings: Record<string, string>,\n\tmaxDepth: number\n): PinnedTemplate[] {\n\tconst byName = new Map(templates.map((t) => [t.name, t]));\n\tconst pinned = new Map<string, PinnedTemplate>();\n\tconst visit = (text: string, depth: number) => {\n\t\tif (depth > maxDepth) return;\n\t\tfor (const token of tokenizePrompt(text)) {\n\t\t\tif (token.type !== 'template' || pinned.has(token.value)) continue;\n\t\t\tconst template = byName.get(token.value);\n\t\t\tif (!template) continue;\n\t\t\t// Mirror `getTemplateBody` so the pinned body is the one `resolvePrompt` used.\n\t\t\tconst body = getTemplateBody(template, bindings);\n\t\t\tif (body === undefined) continue;\n\t\t\tconst bound = bindings[template.name];\n\t\t\tconst version =\n\t\t\t\tbound && template.versions\n\t\t\t\t\t? template.versions.find((v) => v.id === bound || v.version === bound)\n\t\t\t\t\t: getLatestVersion(template);\n\t\t\tconst isVersioned = !!template.versions?.length && !!version;\n\t\t\tpinned.set(template.name, {\n\t\t\t\tname: template.name,\n\t\t\t\t...(template.id !== undefined ? { templateId: template.id } : {}),\n\t\t\t\t...(isVersioned ? { versionId: version!.id, version: version!.version } : {}),\n\t\t\t\tbody\n\t\t\t});\n\t\t\tvisit(body, depth + 1);\n\t\t}\n\t};\n\tvisit(rawPrompt, 0);\n\treturn [...pinned.values()];\n}\n\n/** Templates that reproduce the pinned bodies exactly (one single-version template each). */\nexport function pinnedTemplatesToTemplates(pinned: readonly PinnedTemplate[]): Template[] {\n\treturn pinned.map((p) =>\n\t\tp.versionId !== undefined\n\t\t\t? {\n\t\t\t\t\t...(p.templateId !== undefined ? { id: p.templateId } : {}),\n\t\t\t\t\tname: p.name,\n\t\t\t\t\tlatestVersion: p.version,\n\t\t\t\t\tversions: [{ id: p.versionId, version: p.version ?? p.versionId, body: p.body }]\n\t\t\t\t}\n\t\t\t: { ...(p.templateId !== undefined ? { id: p.templateId } : {}), name: p.name, body: p.body }\n\t);\n}\n\n/**\n * Records what produced an output: the raw prompt, the exact template bodies\n * and versions it reached, variable values, the resolved prompt and its\n * source map, the model, the planned settings and adjustments, and the\n * references by role.\n */\nexport function createProvenance(options: CreateProvenanceOptions): GenerationProvenance {\n\tconst templates = options.templates ?? [];\n\tconst maxDepth = options.maxDepth ?? 10;\n\tconst resolved = resolvePrompt(options.rawPrompt, templates, {\n\t\tbindings: options.bindings,\n\t\tvalues: options.values,\n\t\tmaxDepth\n\t});\n\tconst pinned = pinTemplates(options.rawPrompt, templates, options.bindings ?? {}, maxDepth);\n\tconst bindings: Record<string, string> = {};\n\tfor (const p of pinned) if (p.versionId !== undefined) bindings[p.name] = p.versionId;\n\n\tconst modelId = typeof options.model === 'string' ? options.model : options.model.id;\n\tconst request: GenerationRequest = clone(options.plan?.request ?? options.request ?? {});\n\trequest.model = modelId;\n\tif (request.prompt === undefined) request.prompt = resolved.text;\n\tconst adjustments = clone(options.adjustments ?? options.plan?.adjustments ?? []);\n\n\treturn {\n\t\tformat: PROVENANCE_FORMAT,\n\t\tversion: PROVENANCE_VERSION,\n\t\trawPrompt: options.rawPrompt,\n\t\ttemplates: pinned,\n\t\tbindings,\n\t\tvalues: options.values ? clone(options.values) : null,\n\t\tresolvedPrompt: resolved.text,\n\t\tsourceMap: resolved.map.map((segment) => {\n\t\t\tconst { locked: _locked, ...rest } = segment as SourceMapSegment & { locked?: boolean };\n\t\t\treturn rest;\n\t\t}),\n\t\tmodelId,\n\t\trequest,\n\t\tadjustments,\n\t\treferences: (request.references ?? []).map(({ id, role }) => ({ id, role })),\n\t\tcreatedAt: toIso(options.createdAt ?? Date.now()),\n\t\t...(options.startedAt !== undefined ? { startedAt: toIso(options.startedAt) } : {}),\n\t\t...(options.completedAt !== undefined ? { completedAt: toIso(options.completedAt) } : {}),\n\t\t...(options.outputIds ? { outputIds: [...options.outputIds] } : {}),\n\t\t...(options.meta ? { meta: clone(options.meta) } : {})\n\t};\n}\n\n/** Versioned JSON for storage next to an output. */\nexport function serializeProvenance(provenance: GenerationProvenance): string {\n\treturn JSON.stringify(provenance);\n}\n\nconst isRecord = (value: unknown): value is Record<string, any> =>\n\t!!value && typeof value === 'object' && !Array.isArray(value);\n\n/** Parses and checks serialized provenance. Throws {@link ProvenanceParseError}. */\nexport function parseProvenance(input: string | unknown): GenerationProvenance {\n\tlet data: unknown = input;\n\tif (typeof input === 'string') {\n\t\ttry {\n\t\t\tdata = JSON.parse(input);\n\t\t} catch {\n\t\t\tthrow new ProvenanceParseError('Provenance is not valid JSON.');\n\t\t}\n\t}\n\tif (!isRecord(data) || data.format !== PROVENANCE_FORMAT) {\n\t\tthrow new ProvenanceParseError('Not a generation provenance record.');\n\t}\n\tif (typeof data.version !== 'number' || data.version > PROVENANCE_VERSION) {\n\t\tthrow new ProvenanceParseError(`Unsupported provenance version ${JSON.stringify(data.version)}.`);\n\t}\n\tconst checks: [string, boolean][] = [\n\t\t['rawPrompt', typeof data.rawPrompt === 'string'],\n\t\t['resolvedPrompt', typeof data.resolvedPrompt === 'string'],\n\t\t['modelId', typeof data.modelId === 'string'],\n\t\t['createdAt', typeof data.createdAt === 'string'],\n\t\t['request', isRecord(data.request)],\n\t\t['templates', Array.isArray(data.templates) && data.templates.every((t: any) => isRecord(t) && typeof t.name === 'string' && typeof t.body === 'string')],\n\t\t['sourceMap', Array.isArray(data.sourceMap)],\n\t\t['adjustments', Array.isArray(data.adjustments)],\n\t\t['references', Array.isArray(data.references)]\n\t];\n\tconst bad = checks.find(([, ok]) => !ok);\n\tif (bad) throw new ProvenanceParseError(`Invalid provenance field \"${bad[0]}\".`);\n\treturn {\n\t\t...(data as GenerationProvenance),\n\t\tbindings: isRecord(data.bindings) ? data.bindings : {},\n\t\tvalues: isRecord(data.values) ? data.values : null\n\t};\n}\n\n/**\n * A request that reproduces the recorded generation exactly: the planned\n * settings, model, seed and references that were sent, with the prompt as\n * resolved at the time (not re-resolved against today's templates).\n */\nexport function recreateRequest(provenance: GenerationProvenance): GenerationRequest {\n\tconst request = clone(provenance.request);\n\trequest.model = provenance.modelId;\n\tif (request.prompt === undefined) request.prompt = provenance.resolvedPrompt;\n\treturn request;\n}\n\n/**\n * Re-resolves the raw prompt against the pinned template bodies and values,\n * e.g. to check a record or to open it in an editor with its source map.\n */\nexport function replayProvenancePrompt(provenance: GenerationProvenance): {\n\ttext: string;\n\tmap: SourceMapSegment[];\n\tmatches: boolean;\n} {\n\tconst result = resolvePrompt(provenance.rawPrompt, pinnedTemplatesToTemplates(provenance.templates), {\n\t\tbindings: provenance.bindings,\n\t\t...(provenance.values ? { values: provenance.values } : {})\n\t});\n\treturn { text: result.text, map: result.map, matches: result.text === provenance.resolvedPrompt };\n}\n","export interface BatchResolverOptions<K, V> {\n\t/** Loads many keys at once. Keys missing from the map resolve to `undefined`. */\n\tfetch: (keys: K[]) => Promise<Map<K, V>>;\n\t/** Largest batch passed to `fetch` (default 50). */\n\tmaxBatch?: number;\n\t/** How long to collect keys before fetching, in ms (default 0: the same tick). */\n\tdelayMs?: number;\n\t/** Called once per failed batch. The batch's keys are recorded as resolved-empty. */\n\tonError?: (error: unknown, keys: K[]) => void;\n}\n\nexport interface BatchResolver<K, V> {\n\t/** Resolves one key, batched with other loads in the same window. Never rejects. */\n\tload(key: K): Promise<V | undefined>;\n\tloadMany(keys: readonly K[]): Promise<(V | undefined)[]>;\n\t/** The settled value for a key, if it has been resolved. */\n\tpeek(key: K): V | undefined;\n\t/** Whether a key has settled (found, missing or failed). */\n\thas(key: K): boolean;\n\t/** Whether a key's last fetch failed. */\n\tfailed(key: K): boolean;\n\t/** Seeds a value without fetching. */\n\tprime(key: K, value: V): void;\n\t/** Forgets one key (or all) so the next `load` fetches again. */\n\tclear(key?: K): void;\n\t/** Fetches anything still waiting now, without waiting for `delayMs`. */\n\tflush(): void;\n}\n\ninterface Pending<V> {\n\tpromise: Promise<V | undefined>;\n\tresolve: (value: V | undefined) => void;\n}\n\n/**\n * Coalesces lookups (e.g. asset ids → thumbnails, template ids → bodies) into\n * batched `fetch` calls: keys requested within `delayMs` share a batch of at\n * most `maxBatch`, duplicate keys are fetched once, and results are cached.\n * A failed batch resolves its keys to `undefined` and records them as\n * resolved-empty (`failed(key)` is `true`) so one bad response does not cause\n * a retry storm; `clear(key)` allows a retry.\n */\nexport function createBatchResolver<K, V>(options: BatchResolverOptions<K, V>): BatchResolver<K, V> {\n\tconst maxBatch = Math.max(1, Math.floor(options.maxBatch ?? 50));\n\tconst delayMs = Math.max(0, options.delayMs ?? 0);\n\tconst settled = new Map<K, V | undefined>();\n\tconst failures = new Set<K>();\n\tconst inFlight = new Map<K, Pending<V>>();\n\tlet queue: K[] = [];\n\tlet timer: ReturnType<typeof setTimeout> | null = null;\n\n\tconst run = (keys: K[]) => {\n\t\tconst pendings = keys.map((key) => inFlight.get(key));\n\t\tconst finish = (values: Map<K, V> | null, error?: unknown) => {\n\t\t\tif (values === null) options.onError?.(error, keys);\n\t\t\tkeys.forEach((key, index) => {\n\t\t\t\tconst pending = pendings[index];\n\t\t\t\tconst value = values?.get(key);\n\t\t\t\t// Only cache if nobody cleared the key while the batch was in flight.\n\t\t\t\tif (pending && inFlight.get(key) === pending) {\n\t\t\t\t\tinFlight.delete(key);\n\t\t\t\t\tsettled.set(key, value);\n\t\t\t\t\tif (values === null) failures.add(key);\n\t\t\t\t}\n\t\t\t\tpending?.resolve(value);\n\t\t\t});\n\t\t};\n\t\tlet promise: Promise<Map<K, V>>;\n\t\ttry {\n\t\t\tpromise = Promise.resolve(options.fetch(keys));\n\t\t} catch (error) {\n\t\t\tpromise = Promise.reject(error);\n\t\t}\n\t\tpromise.then(\n\t\t\t(values) => finish(values instanceof Map ? values : new Map()),\n\t\t\t(error) => finish(null, error ?? new Error('Batch fetch failed.'))\n\t\t);\n\t};\n\n\tconst flush = () => {\n\t\tif (timer !== null) clearTimeout(timer);\n\t\ttimer = null;\n\t\tconst keys = queue;\n\t\tqueue = [];\n\t\tfor (let i = 0; i < keys.length; i += maxBatch) run(keys.slice(i, i + maxBatch));\n\t};\n\n\tconst load = (key: K): Promise<V | undefined> => {\n\t\tif (settled.has(key)) return Promise.resolve(settled.get(key));\n\t\tconst existing = inFlight.get(key);\n\t\tif (existing) return existing.promise;\n\t\tlet resolve!: (value: V | undefined) => void;\n\t\tconst promise = new Promise<V | undefined>((r) => (resolve = r));\n\t\tinFlight.set(key, { promise, resolve });\n\t\tqueue.push(key);\n\t\tif (queue.length >= maxBatch) flush();\n\t\telse if (timer === null) timer = setTimeout(flush, delayMs);\n\t\treturn promise;\n\t};\n\n\treturn {\n\t\tload,\n\t\tloadMany: (keys) => Promise.all(keys.map(load)),\n\t\tpeek: (key) => settled.get(key),\n\t\thas: (key) => settled.has(key),\n\t\tfailed: (key) => failures.has(key),\n\t\tprime(key, value) {\n\t\t\tsettled.set(key, value);\n\t\t\tfailures.delete(key);\n\t\t},\n\t\tclear(key) {\n\t\t\tif (key === undefined) {\n\t\t\t\tsettled.clear();\n\t\t\t\tfailures.clear();\n\t\t\t\t// Loads already fetching still resolve, but their results are not cached.\n\t\t\t\tfor (const k of [...inFlight.keys()]) if (!queue.includes(k)) inFlight.delete(k);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsettled.delete(key);\n\t\t\tfailures.delete(key);\n\t\t\tif (!queue.includes(key)) inFlight.delete(key);\n\t\t},\n\t\tflush\n\t};\n}\n","import type { GenerationRequest, ModelCapabilities } from './capabilities.js';\nimport { resolutionMegapixels } from './plan.js';\n\nexport interface JobProgressInput {\n\t/** Start time (ms since epoch, `Date` or ISO string). */\n\tstartedAt: number | Date | string;\n\t/** Current time (default `Date.now()`). */\n\tnow?: number | Date | string;\n\t/** Expected total duration in ms. Without it progress eases towards 95%. */\n\texpectedMs?: number;\n\t/** The job finished. */\n\tdone?: boolean;\n}\n\nexport interface JobProgressEstimate {\n\t/** 0–100. Never above 95 until `done`. */\n\tpercent: number;\n\t/** E.g. `~2m left`, `~40s left`, `Almost done…`, `Starting…`, `Done`. */\n\tlabel: string;\n\telapsedMs: number;\n\t/** Estimated ms left (`undefined` without `expectedMs`). */\n\tremainingMs?: number;\n\t/** Running longer than expected. */\n\toverdue: boolean;\n}\n\n/** Highest percentage shown before a job reports completion. */\nexport const MAX_PENDING_PERCENT = 95;\n/** Remaining time under which the label switches to \"Almost done…\". */\nconst ALMOST_DONE_MS = 5_000;\n/** Time constant for jobs without an expected duration. */\nconst UNKNOWN_DURATION_TAU_MS = 30_000;\n\nconst toMs = (value: number | Date | string) => (typeof value === 'number' ? value : new Date(value).getTime());\n\n/** `~45s left`, `~2m left`, `~1h 5m left`. Minutes and seconds round up. */\nexport function formatRemaining(ms: number): string {\n\tconst seconds = Math.ceil(ms / 1000);\n\tif (seconds < 60) return `~${Math.max(1, seconds)}s left`;\n\tconst minutes = Math.ceil(ms / 60_000);\n\tif (minutes < 60) return `~${minutes}m left`;\n\tconst hours = Math.floor(minutes / 60);\n\tconst rest = minutes % 60;\n\treturn rest ? `~${hours}h ${rest}m left` : `~${hours}h left`;\n}\n\n/**\n * Progress for a job that reports no progress of its own: linear in elapsed\n * time over `expectedMs`, held at 95% until `done` (so the bar never sits at\n * 100% while still waiting), with a \"~2m left\" style label that turns into\n * \"Almost done…\" near or past the expected end. Pure: pass `now` to test.\n */\nexport function estimateJobProgress(input: JobProgressInput): JobProgressEstimate {\n\tconst started = toMs(input.startedAt);\n\tconst now = toMs(input.now ?? Date.now());\n\tconst elapsedMs = Math.max(0, now - started);\n\tif (input.done) return { percent: 100, label: 'Done', elapsedMs, remainingMs: 0, overdue: false };\n\tif (!Number.isFinite(started) || now <= started) {\n\t\treturn { percent: 0, label: 'Starting…', elapsedMs: 0, ...(input.expectedMs ? { remainingMs: input.expectedMs } : {}), overdue: false };\n\t}\n\tconst expected = input.expectedMs;\n\tif (!expected || !(expected > 0)) {\n\t\tconst percent = MAX_PENDING_PERCENT * (1 - Math.exp(-elapsedMs / UNKNOWN_DURATION_TAU_MS));\n\t\treturn { percent: Math.floor(percent), label: 'Working…', elapsedMs, overdue: false };\n\t}\n\tconst remainingMs = Math.max(0, expected - elapsedMs);\n\tconst percent = Math.min(MAX_PENDING_PERCENT, Math.floor((elapsedMs / expected) * 100));\n\treturn {\n\t\tpercent,\n\t\tlabel: remainingMs <= ALMOST_DONE_MS ? 'Almost done…' : formatRemaining(remainingMs),\n\t\telapsedMs,\n\t\tremainingMs,\n\t\toverdue: elapsedMs > expected\n\t};\n}\n\n/**\n * Expected duration of a request from the model's `timing`: `baseMs`, plus\n * `perItemMs` per output beyond the first, `perSecondMs` per second of\n * duration and `perMegapixelMs` per megapixel of resolution. `undefined` when\n * the model has no timing.\n */\nexport function expectedDurationFor(caps: ModelCapabilities, request: GenerationRequest = {}): number | undefined {\n\tconst timing = caps.timing;\n\tif (!timing) return undefined;\n\tconst count = request.count ?? caps.count?.default ?? 1;\n\tconst duration = request.duration ?? caps.duration?.default ?? 0;\n\tconst resolution = request.resolution ?? caps.resolutions?.default;\n\tconst megapixels = resolution ? (resolutionMegapixels(resolution) ?? 0) : 0;\n\treturn Math.round(\n\t\ttiming.baseMs +\n\t\t\t(timing.perItemMs ?? 0) * Math.max(0, count - 1) +\n\t\t\t(timing.perSecondMs ?? 0) * duration +\n\t\t\t(timing.perMegapixelMs ?? 0) * megapixels\n\t);\n}\n","import {\n\tREFERENCE_ROLE_LABELS,\n\tseedCapability,\n\tsupportedModes,\n\tsupportedReferenceRoles,\n\ttextFieldCapability,\n\ttype EnumCapability,\n\ttype GenerationParamValue,\n\ttype GenerationReference,\n\ttype GenerationRequest,\n\ttype ModelCapabilities,\n\ttype ReferenceRole\n} from './capabilities.js';\n\nexport interface GenerationControlOption {\n\tvalue: string | number;\n\tlabel: string;\n}\n\n/**\n * A UI control derived from capabilities. `key` is a request path:\n * `aspectRatio`, `count`, `params.guidance`, …\n */\nexport interface GenerationControl {\n\tkey: string;\n\tlabel: string;\n\t/** `select` for choices, `range` for bounded numbers, `number` for open numbers. */\n\tkind: 'select' | 'range' | 'number' | 'textarea' | 'checkbox';\n\tvalueType: 'string' | 'number' | 'boolean';\n\toptions?: GenerationControlOption[];\n\tmin?: number;\n\tmax?: number;\n\tstep?: number;\n\tmaxLength?: number;\n\tdefaultValue?: string | number | boolean;\n\tdescription?: string;\n}\n\nexport interface ReferenceSlot {\n\trole: ReferenceRole;\n\tlabel: string;\n\tdescription?: string;\n\tmin: number;\n\tmax: number;\n\treferences: GenerationReference[];\n\t/** More references of this role fit (per role and in total). */\n\tcanAdd: boolean;\n}\n\nfunction enumControl(key: string, label: string, cap: EnumCapability<string> | undefined): GenerationControl | null {\n\tif (!cap?.options.length) return null;\n\treturn {\n\t\tkey,\n\t\tlabel,\n\t\tkind: 'select',\n\t\tvalueType: 'string',\n\t\toptions: cap.options.map((value) => ({ value, label: cap.labels?.[value] ?? value })),\n\t\t...(cap.default !== undefined ? { defaultValue: cap.default } : {})\n\t};\n}\n\n/**\n * The settings controls a model supports, in display order. Excludes the\n * prompt (edited by the prompt editor) and references (see\n * {@link getReferenceSlots}).\n */\nexport function getGenerationControls(caps: ModelCapabilities): GenerationControl[] {\n\tconst controls: (GenerationControl | null)[] = [];\n\tconst modes = supportedModes(caps);\n\tif (modes.length > 1) {\n\t\tcontrols.push({\n\t\t\tkey: 'mode',\n\t\t\tlabel: 'Mode',\n\t\t\tkind: 'select',\n\t\t\tvalueType: 'string',\n\t\t\toptions: modes.map((m) => ({ value: m, label: m[0].toUpperCase() + m.slice(1) })),\n\t\t\tdefaultValue: 'generate'\n\t\t});\n\t}\n\tconst negative = textFieldCapability(caps.negativePrompt);\n\tif (negative) controls.push({ key: 'negativePrompt', label: 'Negative prompt', kind: 'textarea', valueType: 'string', maxLength: negative.maxLength });\n\tconst system = textFieldCapability(caps.systemPrompt);\n\tif (system) controls.push({ key: 'systemPrompt', label: 'System prompt', kind: 'textarea', valueType: 'string', maxLength: system.maxLength });\n\tcontrols.push(enumControl('aspectRatio', 'Aspect ratio', caps.aspectRatios));\n\tcontrols.push(enumControl('resolution', 'Resolution', caps.resolutions));\n\tcontrols.push(enumControl('quality', 'Quality', caps.quality));\n\n\tif (caps.count) {\n\t\tconst options = caps.count.options?.filter((o) => o >= 1 && o <= caps.count!.max);\n\t\tcontrols.push(\n\t\t\toptions?.length\n\t\t\t\t? { key: 'count', label: 'Outputs', kind: 'select', valueType: 'number', options: options.map((o) => ({ value: o, label: String(o) })), defaultValue: caps.count.default }\n\t\t\t\t: { key: 'count', label: 'Outputs', kind: 'range', valueType: 'number', min: 1, max: caps.count.max, step: 1, defaultValue: caps.count.default ?? 1 }\n\t\t);\n\t}\n\tif (caps.duration) {\n\t\tconst d = caps.duration;\n\t\tconst options = d.options?.filter((o) => (d.min === undefined || o >= d.min) && (d.max === undefined || o <= d.max));\n\t\tcontrols.push(\n\t\t\toptions?.length\n\t\t\t\t? { key: 'duration', label: 'Duration (s)', kind: 'select', valueType: 'number', options: options.map((o) => ({ value: o, label: `${o}s` })), defaultValue: d.default }\n\t\t\t\t: {\n\t\t\t\t\t\tkey: 'duration',\n\t\t\t\t\t\tlabel: 'Duration (s)',\n\t\t\t\t\t\tkind: d.min !== undefined && d.max !== undefined ? 'range' : 'number',\n\t\t\t\t\t\tvalueType: 'number',\n\t\t\t\t\t\tmin: d.min,\n\t\t\t\t\t\tmax: d.max,\n\t\t\t\t\t\tstep: d.step,\n\t\t\t\t\t\tdefaultValue: d.default\n\t\t\t\t\t}\n\t\t);\n\t}\n\tconst seed = seedCapability(caps.seed);\n\tif (seed) controls.push({ key: 'seed', label: 'Seed', kind: 'number', valueType: 'number', min: seed.min, max: seed.max, step: 1 });\n\n\tfor (const [name, spec] of Object.entries(caps.params ?? {})) {\n\t\tconst base = { key: `params.${name}`, label: spec.label ?? name, ...(spec.description ? { description: spec.description } : {}) };\n\t\tif (spec.type === 'boolean') {\n\t\t\tcontrols.push({ ...base, kind: 'checkbox', valueType: 'boolean', defaultValue: spec.default });\n\t\t} else if (spec.type === 'enum') {\n\t\t\tconst numeric = spec.options.every((o) => typeof o === 'number');\n\t\t\tcontrols.push({\n\t\t\t\t...base,\n\t\t\t\tkind: 'select',\n\t\t\t\tvalueType: numeric ? 'number' : 'string',\n\t\t\t\toptions: spec.options.map((value) => ({ value, label: String(value) })),\n\t\t\t\tdefaultValue: spec.default\n\t\t\t});\n\t\t} else {\n\t\t\tcontrols.push({\n\t\t\t\t...base,\n\t\t\t\tkind: spec.min !== undefined && spec.max !== undefined ? 'range' : 'number',\n\t\t\t\tvalueType: 'number',\n\t\t\t\tmin: spec.min,\n\t\t\t\tmax: spec.max,\n\t\t\t\tstep: spec.step ?? (spec.type === 'integer' ? 1 : undefined),\n\t\t\t\tdefaultValue: spec.default\n\t\t\t});\n\t\t}\n\t}\n\treturn controls.filter((c): c is GenerationControl => c !== null);\n}\n\n/** Reads a request value by control key (`params.x` reads a param). */\nexport function getRequestValue(request: GenerationRequest, key: string): unknown {\n\tif (key.startsWith('params.')) return request.params?.[key.slice(7)];\n\treturn (request as Record<string, unknown>)[key];\n}\n\n/** Returns a copy of `request` with `key` set (`undefined` or `''` removes it). */\nexport function setRequestValue(request: GenerationRequest, key: string, value: unknown): GenerationRequest {\n\tconst remove = value === undefined || value === '' || (typeof value === 'number' && Number.isNaN(value));\n\tif (key.startsWith('params.')) {\n\t\tconst name = key.slice(7);\n\t\tconst params = { ...(request.params ?? {}) };\n\t\tif (remove) delete params[name];\n\t\telse params[name] = value as GenerationParamValue;\n\t\tconst next: GenerationRequest = { ...request, params };\n\t\tif (Object.keys(params).length === 0) delete next.params;\n\t\treturn next;\n\t}\n\tconst next = { ...request } as Record<string, unknown>;\n\tif (remove) delete next[key];\n\telse next[key] = value;\n\treturn next as GenerationRequest;\n}\n\n/** Parses a DOM control's string value into the control's value type. */\nexport function parseControlValue(control: GenerationControl, raw: string | boolean): string | number | boolean | undefined {\n\tif (control.valueType === 'boolean') return Boolean(raw);\n\tif (raw === '' || raw === undefined) return undefined;\n\tif (control.valueType === 'number') {\n\t\tconst n = Number(raw);\n\t\treturn Number.isFinite(n) ? n : undefined;\n\t}\n\treturn String(raw);\n}\n\n/** Reference slots for every role the model accepts, filled from `request`. */\nexport function getReferenceSlots(caps: ModelCapabilities, request: GenerationRequest = {}): ReferenceSlot[] {\n\tconst roles = supportedReferenceRoles(caps);\n\tif (caps.inpainting && !roles.includes('mask')) roles.push('mask');\n\tconst refs = request.references ?? [];\n\tconst total = refs.length;\n\tconst maxTotal = caps.references?.maxTotal ?? Infinity;\n\treturn roles.map((role) => {\n\t\tconst cap = caps.references?.roles[role] ?? { max: 1 };\n\t\tconst references = refs.filter((ref) => ref.role === role);\n\t\treturn {\n\t\t\trole,\n\t\t\tlabel: cap.label ?? REFERENCE_ROLE_LABELS[role],\n\t\t\t...(cap.description ? { description: cap.description } : {}),\n\t\t\tmin: cap.min ?? 0,\n\t\t\tmax: cap.max,\n\t\t\treferences,\n\t\t\tcanAdd: references.length < cap.max && total < maxTotal\n\t\t};\n\t});\n}\n\n/** Returns a copy of `request` with a reference appended. */\nexport function addReference(request: GenerationRequest, reference: GenerationReference): GenerationRequest {\n\treturn { ...request, references: [...(request.references ?? []), { ...reference }] };\n}\n\n/** Returns a copy of `request` without the reference `id` in `role`. */\nexport function removeReference(request: GenerationRequest, role: ReferenceRole, id: string): GenerationRequest {\n\tconst references = (request.references ?? []).filter((ref) => !(ref.role === role && ref.id === id));\n\tconst next: GenerationRequest = { ...request, references };\n\tif (references.length === 0) delete next.references;\n\treturn next;\n}\n"],"mappings":";;;;;;;;;;;;AAsBO,IAAM,kBAA4C;AAAA,EACxD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD;AAGO,IAAM,wBAAiE;AAAA,EAC7E,aAAa;AAAA,EACb,WAAW;AAAA,EACX,WAAW;AAAA,EACX,eAAe;AAAA,EACf,gBAAgB;AAAA,EAChB,MAAM;AAAA,EACN,WAAW;AAAA,EACX,WAAW;AAAA,EACX,WAAW;AACZ;AA0KO,IAAM,4BAA4B;AAAA,EACxC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD;AAGO,SAAS,oBAAoB,OAA8E;AACjH,MAAI,CAAC,MAAO,QAAO;AACnB,SAAO,UAAU,OAAO,CAAC,IAAI;AAC9B;AAGO,SAAS,eAAe,OAAoE;AAClG,MAAI,CAAC,MAAO,QAAO;AACnB,SAAO,UAAU,OAAO,CAAC,IAAI;AAC9B;AAGO,SAAS,wBAAwB,MAA0C;AACjF,QAAM,QAAQ,KAAK,YAAY,SAAS,CAAC;AACzC,SAAO,gBAAgB,OAAO,CAAC,UAAU,MAAM,IAAI,GAAG,OAAO,KAAK,CAAC;AACpE;AAGO,SAAS,eAAe,MAA2C;AACzE,QAAM,QAA0B,CAAC,UAAU;AAC3C,MAAI,KAAK,QAAS,OAAM,KAAK,MAAM;AACnC,MAAI,KAAK,WAAY,OAAM,KAAK,SAAS;AACzC,SAAO;AACR;AAEA,IAAM,oBAAoB,CAAC,QAAQ,eAAe,UAAU,QAA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cjs');
23
22
 
24
23
 
25
24
 
26
25
 
26
+ var _chunkP3RQ5UJEcjs = require('../chunk-P3RQ5UJE.cjs');
27
27
 
28
28
 
29
29
 
@@ -34,7 +34,7 @@ var _chunk4SUNJZWBcjs = require('../chunk-4SUNJZWB.cjs');
34
34
 
35
35
 
36
36
 
37
- var _chunkAXV2ZW34cjs = require('../chunk-AXV2ZW34.cjs');
37
+ var _chunkFD4LPFAEcjs = require('../chunk-FD4LPFAE.cjs');
38
38
 
39
39
 
40
40
 
@@ -57,6 +57,8 @@ var _chunkAXV2ZW34cjs = require('../chunk-AXV2ZW34.cjs');
57
57
 
58
58
 
59
59
 
60
+ var _chunkMKA3AHLVcjs = require('../chunk-MKA3AHLV.cjs');
61
+ require('../chunk-TNNJXF46.cjs');
60
62
 
61
63
 
62
64
 
@@ -69,5 +71,48 @@ var _chunkAXV2ZW34cjs = require('../chunk-AXV2ZW34.cjs');
69
71
 
70
72
 
71
73
 
72
- exports.INSTRUCTION_REGEX = _chunkAXV2ZW34cjs.INSTRUCTION_REGEX; exports.TEMPLATE_DEPTH_ERROR = _chunk4SUNJZWBcjs.TEMPLATE_DEPTH_ERROR; exports.TEMPLATE_LOOP_ERROR = _chunk4SUNJZWBcjs.TEMPLATE_LOOP_ERROR; exports.TEMPLATE_REGEX = _chunkAXV2ZW34cjs.TEMPLATE_REGEX; exports.VARIABLE_REGEX = _chunkAXV2ZW34cjs.VARIABLE_REGEX; exports.compactVariableValues = _chunk4SUNJZWBcjs.compactVariableValues; exports.escapeVariableText = _chunkAXV2ZW34cjs.escapeVariableText; exports.evaluateCondition = _chunkAXV2ZW34cjs.evaluateCondition; exports.evaluatePromptTokens = _chunk4SUNJZWBcjs.evaluatePromptTokens; exports.extractInstructionNames = _chunk4SUNJZWBcjs.extractInstructionNames; exports.extractTemplateNames = _chunk4SUNJZWBcjs.extractTemplateNames; exports.extractVariableNames = _chunk4SUNJZWBcjs.extractVariableNames; exports.extractVariables = _chunk4SUNJZWBcjs.extractVariables; exports.getLatestVersion = _chunk4SUNJZWBcjs.getLatestVersion; exports.getPromptDiagnostics = _chunk4SUNJZWBcjs.getPromptDiagnostics; exports.getSuppliedValue = _chunkAXV2ZW34cjs.getSuppliedValue; exports.getTemplateBody = _chunk4SUNJZWBcjs.getTemplateBody; exports.getVariableFormFields = _chunk4SUNJZWBcjs.getVariableFormFields; exports.instructionRegex = _chunkAXV2ZW34cjs.instructionRegex; exports.isPromptValueSet = _chunkAXV2ZW34cjs.isPromptValueSet; exports.mapRawOffsetToResolved = _chunk4SUNJZWBcjs.mapRawOffsetToResolved; exports.mapResolvedOffsetToRaw = _chunk4SUNJZWBcjs.mapResolvedOffsetToRaw; exports.matchConditionalTags = _chunkAXV2ZW34cjs.matchConditionalTags; exports.parseVariableBody = _chunkAXV2ZW34cjs.parseVariableBody; exports.resolvePrompt = _chunk4SUNJZWBcjs.resolvePrompt; exports.resolveTemplates = _chunk4SUNJZWBcjs.resolveTemplates; exports.resolveTemplatesWithMapping = _chunk4SUNJZWBcjs.resolveTemplatesWithMapping; exports.resolveVariables = _chunk4SUNJZWBcjs.resolveVariables; exports.templateRegex = _chunkAXV2ZW34cjs.templateRegex; exports.tokenizePrompt = _chunk4SUNJZWBcjs.tokenizePrompt; exports.tokenizePromptWithDiagnostics = _chunk4SUNJZWBcjs.tokenizePromptWithDiagnostics; exports.unescapeVariableText = _chunkAXV2ZW34cjs.unescapeVariableText; exports.variableRegex = _chunkAXV2ZW34cjs.variableRegex;
74
+
75
+
76
+
77
+
78
+
79
+
80
+
81
+
82
+
83
+
84
+
85
+
86
+
87
+
88
+
89
+
90
+
91
+
92
+
93
+
94
+
95
+
96
+
97
+
98
+
99
+
100
+
101
+
102
+
103
+
104
+
105
+
106
+
107
+
108
+
109
+
110
+
111
+
112
+
113
+
114
+
115
+
116
+
117
+ exports.FIELD_ALIASES = _chunkP3RQ5UJEcjs.FIELD_ALIASES; exports.INSTRUCTION_REGEX = _chunkMKA3AHLVcjs.INSTRUCTION_REGEX; exports.MAX_DATA_SOURCE_FIELDS = _chunkP3RQ5UJEcjs.MAX_DATA_SOURCE_FIELDS; exports.MAX_DATA_SOURCE_RECORDS = _chunkP3RQ5UJEcjs.MAX_DATA_SOURCE_RECORDS; exports.MAX_MERGE_LENGTH = _chunkP3RQ5UJEcjs.MAX_MERGE_LENGTH; exports.MAX_MERGE_OUTPUTS = _chunkP3RQ5UJEcjs.MAX_MERGE_OUTPUTS; exports.TEMPLATE_DEPTH_ERROR = _chunkFD4LPFAEcjs.TEMPLATE_DEPTH_ERROR; exports.TEMPLATE_LOOP_ERROR = _chunkFD4LPFAEcjs.TEMPLATE_LOOP_ERROR; exports.TEMPLATE_REGEX = _chunkMKA3AHLVcjs.TEMPLATE_REGEX; exports.VARIABLE_REGEX = _chunkMKA3AHLVcjs.VARIABLE_REGEX; exports.compactVariableValues = _chunkP3RQ5UJEcjs.compactVariableValues; exports.compareConditionValues = _chunkMKA3AHLVcjs.compareConditionValues; exports.conditionSubject = _chunkMKA3AHLVcjs.conditionSubject; exports.describeConditionalTag = _chunkMKA3AHLVcjs.describeConditionalTag; exports.detectDelimiter = _chunkP3RQ5UJEcjs.detectDelimiter; exports.escapeVariableText = _chunkMKA3AHLVcjs.escapeVariableText; exports.evaluateCondition = _chunkMKA3AHLVcjs.evaluateCondition; exports.evaluateConditionExpression = _chunkMKA3AHLVcjs.evaluateConditionExpression; exports.evaluatePromptTokens = _chunkFD4LPFAEcjs.evaluatePromptTokens; exports.extractInstructionNames = _chunkP3RQ5UJEcjs.extractInstructionNames; exports.extractTemplateNames = _chunkP3RQ5UJEcjs.extractTemplateNames; exports.extractVariableNames = _chunkP3RQ5UJEcjs.extractVariableNames; exports.extractVariables = _chunkP3RQ5UJEcjs.extractVariables; exports.formatComparisonOperand = _chunkMKA3AHLVcjs.formatComparisonOperand; exports.formatConditionalTag = _chunkMKA3AHLVcjs.formatConditionalTag; exports.getLatestVersion = _chunkFD4LPFAEcjs.getLatestVersion; exports.getPromptDiagnostics = _chunkFD4LPFAEcjs.getPromptDiagnostics; exports.getSuppliedValue = _chunkMKA3AHLVcjs.getSuppliedValue; exports.getTemplateBody = _chunkFD4LPFAEcjs.getTemplateBody; exports.getVariableFormFields = _chunkP3RQ5UJEcjs.getVariableFormFields; exports.instructionRegex = _chunkMKA3AHLVcjs.instructionRegex; exports.isPromptValueSet = _chunkMKA3AHLVcjs.isPromptValueSet; exports.mapRawOffsetToResolved = _chunkP3RQ5UJEcjs.mapRawOffsetToResolved; exports.mapResolvedOffsetToRaw = _chunkP3RQ5UJEcjs.mapResolvedOffsetToRaw; exports.matchConditionalTags = _chunkMKA3AHLVcjs.matchConditionalTags; exports.matchFields = _chunkP3RQ5UJEcjs.matchFields; exports.mergeRecords = _chunkP3RQ5UJEcjs.mergeRecords; exports.normalizeFieldKey = _chunkP3RQ5UJEcjs.normalizeFieldKey; exports.normalizeFieldNames = _chunkP3RQ5UJEcjs.normalizeFieldNames; exports.parseComparison = _chunkMKA3AHLVcjs.parseComparison; exports.parseConditionExpression = _chunkMKA3AHLVcjs.parseConditionExpression; exports.parseDataSource = _chunkP3RQ5UJEcjs.parseDataSource; exports.parseVariableBody = _chunkMKA3AHLVcjs.parseVariableBody; exports.recordToValues = _chunkP3RQ5UJEcjs.recordToValues; exports.resolvePrompt = _chunkFD4LPFAEcjs.resolvePrompt; exports.resolveTemplates = _chunkP3RQ5UJEcjs.resolveTemplates; exports.resolveTemplatesWithMapping = _chunkP3RQ5UJEcjs.resolveTemplatesWithMapping; exports.resolveVariables = _chunkP3RQ5UJEcjs.resolveVariables; exports.serializeMergeOutputs = _chunkP3RQ5UJEcjs.serializeMergeOutputs; exports.templateRegex = _chunkMKA3AHLVcjs.templateRegex; exports.tokenizePrompt = _chunkFD4LPFAEcjs.tokenizePrompt; exports.tokenizePromptWithDiagnostics = _chunkFD4LPFAEcjs.tokenizePromptWithDiagnostics; exports.unescapeVariableText = _chunkMKA3AHLVcjs.unescapeVariableText; exports.variableRegex = _chunkMKA3AHLVcjs.variableRegex;
73
118
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/editor/editor/packages/core/dist/grammar/index.cjs"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,grEAAC","file":"/home/runner/work/editor/editor/packages/core/dist/grammar/index.cjs"}
1
+ {"version":3,"sources":["/home/runner/work/editor/editor/packages/core/dist/grammar/index.cjs"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B,iCAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,2jHAAC","file":"/home/runner/work/editor/editor/packages/core/dist/grammar/index.cjs"}