@puckeditor/plugin-ai 0.8.2 → 0.9.0-canary.50fad349

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.
package/dist/index.mjs CHANGED
@@ -36,37 +36,6 @@ var init_react_import = __esm({
36
36
  }
37
37
  });
38
38
 
39
- // ../../node_modules/.pnpm/throttleit@2.1.0/node_modules/throttleit/index.js
40
- var require_throttleit = __commonJS({
41
- "../../node_modules/.pnpm/throttleit@2.1.0/node_modules/throttleit/index.js"(exports, module) {
42
- "use strict";
43
- init_react_import();
44
- function throttle2(function_, wait) {
45
- if (typeof function_ !== "function") {
46
- throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof function_}\`.`);
47
- }
48
- let timeoutId;
49
- let lastCallTime = 0;
50
- return function throttled(...arguments_) {
51
- clearTimeout(timeoutId);
52
- const now = Date.now();
53
- const timeSinceLastCall = now - lastCallTime;
54
- const delayForNextCall = wait - timeSinceLastCall;
55
- if (delayForNextCall <= 0) {
56
- lastCallTime = now;
57
- function_.apply(this, arguments_);
58
- } else {
59
- timeoutId = setTimeout(() => {
60
- lastCallTime = Date.now();
61
- function_.apply(this, arguments_);
62
- }, delayForNextCall);
63
- }
64
- };
65
- }
66
- module.exports = throttle2;
67
- }
68
- });
69
-
70
39
  // ../../node_modules/.pnpm/classnames@2.5.1/node_modules/classnames/index.js
71
40
  var require_classnames = __commonJS({
72
41
  "../../node_modules/.pnpm/classnames@2.5.1/node_modules/classnames/index.js"(exports, module) {
@@ -129,267 +98,34 @@ var require_classnames = __commonJS({
129
98
  }
130
99
  });
131
100
 
132
- // ../reducer/dist/index.js
133
- var require_dist = __commonJS({
134
- "../reducer/dist/index.js"(exports, module) {
101
+ // ../../node_modules/.pnpm/throttleit@2.1.0/node_modules/throttleit/index.js
102
+ var require_throttleit = __commonJS({
103
+ "../../node_modules/.pnpm/throttleit@2.1.0/node_modules/throttleit/index.js"(exports, module) {
135
104
  "use strict";
136
105
  init_react_import();
137
- var __defProp2 = Object.defineProperty;
138
- var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
139
- var __getOwnPropNames2 = Object.getOwnPropertyNames;
140
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
141
- var __export = (target, all) => {
142
- for (var name in all)
143
- __defProp2(target, name, { get: all[name], enumerable: true });
144
- };
145
- var __copyProps2 = (to, from, except, desc) => {
146
- if (from && typeof from === "object" || typeof from === "function") {
147
- for (let key of __getOwnPropNames2(from))
148
- if (!__hasOwnProp2.call(to, key) && key !== except)
149
- __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
150
- }
151
- return to;
152
- };
153
- var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
154
- var index_exports = {};
155
- __export(index_exports, {
156
- dispatchOp: () => dispatchOp2,
157
- resolveAppends: () => resolveAppends
158
- });
159
- module.exports = __toCommonJS(index_exports);
160
- var parseAppendPath = (path) => {
161
- const segments = [];
162
- const pattern = /([^.[\]]+)|\[(\d+)\]/g;
163
- let match;
164
- while ((match = pattern.exec(path)) !== null) {
165
- segments.push(match[2] !== void 0 ? Number(match[2]) : match[1]);
166
- }
167
- return segments;
168
- };
169
- var appendAtPath = (base, segments, tail) => {
170
- if (segments.length === 0) {
171
- return `${typeof base === "string" ? base : ""}${tail}`;
172
- }
173
- const [head, ...rest] = segments;
174
- if (typeof head === "number") {
175
- const arr = Array.isArray(base) ? [...base] : [];
176
- arr[head] = appendAtPath(arr[head], rest, tail);
177
- return arr;
178
- }
179
- const obj = typeof base === "object" && base !== null && !Array.isArray(base) ? { ...base } : {};
180
- obj[head] = appendAtPath(obj[head], rest, tail);
181
- return obj;
182
- };
183
- var resolveAppends = (existingProps, props, appends) => {
184
- if (!appends) return props;
185
- const resolved = { ...props };
186
- for (const [path, tail] of Object.entries(appends)) {
187
- const [rootKey, ...rest] = parseAppendPath(path);
188
- if (typeof rootKey !== "string") continue;
189
- const base = rootKey in resolved ? resolved[rootKey] : existingProps == null ? void 0 : existingProps[rootKey];
190
- resolved[rootKey] = appendAtPath(base, rest, tail);
191
- }
192
- return resolved;
193
- };
194
- var getSelectorForId = (state, id) => {
195
- const node = state.indexes.nodes[id];
196
- if (!node) return;
197
- const zoneCompound = `${node.parentId}:${node.zone}`;
198
- const zone = state.indexes.zones[zoneCompound];
199
- if (!zone) return;
200
- const index = zone.contentIds.indexOf(id);
201
- return { zone: zoneCompound, index };
202
- };
203
- var getItemById = (state, id) => {
204
- var _a;
205
- return (_a = state.indexes.nodes[id]) == null ? void 0 : _a.data;
206
- };
207
- var applyArrayDefaults = (oldProps, newProps, fields) => {
208
- const updatedProps = {
209
- ...oldProps,
210
- ...newProps
211
- };
212
- for (const fieldName in fields) {
213
- const field = fields[fieldName];
214
- if (field.type === "array") {
215
- const arrayField = field;
216
- const arrayFields = arrayField.arrayFields;
217
- const value = updatedProps[fieldName];
218
- if (value === void 0) continue;
219
- if (!Array.isArray(value)) {
220
- const oldValue = oldProps[fieldName];
221
- if (Array.isArray(oldValue)) {
222
- updatedProps[fieldName] = oldValue;
223
- } else {
224
- delete updatedProps[fieldName];
225
- }
226
- continue;
227
- }
228
- updatedProps[fieldName] = value.map(
229
- (item, index) => {
230
- var _a, _b;
231
- const newItem = {};
232
- const defaultValue = typeof arrayField.defaultItemProps === "function" ? arrayField.defaultItemProps(index) : arrayField.defaultItemProps;
233
- for (const arrayFieldName in arrayFields) {
234
- const subField = arrayFields[arrayFieldName];
235
- if (subField.type === "slot") {
236
- newItem[arrayFieldName] = item[arrayFieldName] ?? ((_b = (_a = oldProps[fieldName]) == null ? void 0 : _a[index]) == null ? void 0 : _b[arrayFieldName]) ?? (defaultValue == null ? void 0 : defaultValue[arrayFieldName]);
237
- } else {
238
- newItem[arrayFieldName] = item[arrayFieldName] ?? (defaultValue == null ? void 0 : defaultValue[arrayFieldName]);
239
- }
240
- }
241
- return newItem;
242
- }
243
- );
244
- }
106
+ function throttle2(function_, wait) {
107
+ if (typeof function_ !== "function") {
108
+ throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof function_}\`.`);
245
109
  }
246
- return updatedProps;
247
- };
248
- var dispatchOp2 = (operation, {
249
- getState,
250
- dispatchAction,
251
- config
252
- }) => {
253
- var _a, _b;
254
- const state = getState();
255
- try {
256
- if (operation.op === "add") {
257
- if (operation.zone) {
258
- dispatchAction({
259
- type: "insert",
260
- destinationIndex: operation.index,
261
- destinationZone: operation.zone,
262
- componentType: operation.type,
263
- id: operation.id,
264
- recordHistory: false
265
- });
266
- const existing = getItemById(getState(), operation.id);
267
- if (!existing) {
268
- throw new Error(
269
- `Tried to update an item that doesn't exist: ${operation.id}`
270
- );
271
- }
272
- const newData = {
273
- ...existing,
274
- props: applyArrayDefaults(
275
- existing.props,
276
- operation.props,
277
- config.components[existing.type].fields
278
- )
279
- };
280
- newData.props.id ||= operation.id;
281
- const selector = getSelectorForId(getState(), operation.id);
282
- if (!selector) {
283
- throw new Error(
284
- `Tried to replace an item that doesn't exist: ${operation.id}`
285
- );
286
- }
287
- dispatchAction({
288
- type: "replace",
289
- destinationIndex: selector.index,
290
- destinationZone: selector.zone,
291
- data: newData,
292
- recordHistory: false
293
- });
294
- }
295
- } else if (operation.op === "update") {
296
- const selector = getSelectorForId(state, operation.id);
297
- const existing = getItemById(state, operation.id);
298
- if (!selector || !existing) {
299
- throw new Error(
300
- `Tried to update an item that doesn't exist: ${operation.id}`
301
- );
302
- }
303
- const newData = {
304
- ...existing,
305
- props: applyArrayDefaults(
306
- existing.props,
307
- resolveAppends(
308
- existing.props,
309
- operation.props,
310
- operation.appends
311
- ),
312
- config.components[existing.type].fields
313
- )
314
- };
315
- dispatchAction({
316
- type: "replace",
317
- destinationIndex: selector.index,
318
- destinationZone: selector.zone,
319
- data: newData,
320
- recordHistory: false
321
- });
322
- } else if (operation.op === "updateRoot") {
323
- const existing = state.data.root;
324
- const defaultProps = ((_a = config.root) == null ? void 0 : _a.defaultProps) ?? {};
325
- dispatchAction({
326
- type: "replaceRoot",
327
- root: {
328
- ...existing,
329
- props: {
330
- ...defaultProps,
331
- ...existing.props,
332
- ...resolveAppends(
333
- existing.props ?? {},
334
- operation.props,
335
- operation.appends
336
- )
337
- }
338
- },
339
- recordHistory: false
340
- });
341
- } else if (operation.op === "delete") {
342
- const selector = getSelectorForId(state, operation.id);
343
- if (selector) {
344
- dispatchAction({
345
- type: "remove",
346
- zone: selector.zone,
347
- index: selector.index,
348
- recordHistory: false
349
- });
350
- }
351
- } else if (operation.op === "duplicate") {
352
- const selector = getSelectorForId(state, operation.id);
353
- if (!selector) {
354
- throw new Error(
355
- `Tried to duplicate an item that doesn't exist: ${operation.id}`
356
- );
357
- }
358
- dispatchAction({
359
- type: "duplicate",
360
- sourceZone: selector.zone,
361
- sourceIndex: selector.index,
362
- recordHistory: false
363
- });
364
- } else if (operation.op === "move") {
365
- const selector = getSelectorForId(state, operation.id);
366
- if (!selector) {
367
- throw new Error(
368
- `Tried to move an item that doesn't exist: ${operation.id}`
369
- );
370
- }
371
- dispatchAction({
372
- type: "move",
373
- sourceZone: selector.zone,
374
- sourceIndex: selector.index,
375
- destinationIndex: operation.index,
376
- destinationZone: operation.zone,
377
- recordHistory: false
378
- });
379
- } else if (operation.op === "reset") {
380
- const defaultRootProps = ((_b = config.root) == null ? void 0 : _b.defaultProps) ?? {};
381
- dispatchAction({
382
- type: "setData",
383
- data: { content: [], root: defaultRootProps },
384
- recordHistory: false
385
- });
110
+ let timeoutId;
111
+ let lastCallTime = 0;
112
+ return function throttled(...arguments_) {
113
+ clearTimeout(timeoutId);
114
+ const now = Date.now();
115
+ const timeSinceLastCall = now - lastCallTime;
116
+ const delayForNextCall = wait - timeSinceLastCall;
117
+ if (delayForNextCall <= 0) {
118
+ lastCallTime = now;
119
+ function_.apply(this, arguments_);
386
120
  } else {
387
- throw new Error(`Unknown operation: ${operation.op}`);
121
+ timeoutId = setTimeout(() => {
122
+ lastCallTime = Date.now();
123
+ function_.apply(this, arguments_);
124
+ }, delayForNextCall);
388
125
  }
389
- } catch (e) {
390
- console.error("Error applying operation, skipping...", operation, e);
391
- }
392
- };
126
+ };
127
+ }
128
+ module.exports = throttle2;
393
129
  }
394
130
  });
395
131
 
@@ -728,416 +464,147 @@ import { ulid as ulid2 } from "ulid";
728
464
 
729
465
  // src/components/Chat/index.tsx
730
466
  init_react_import();
467
+ import { createUsePuck as createUsePuck2 } from "@puckeditor/core";
468
+ import {
469
+ useCallback as useCallback6,
470
+ useEffect as useEffect13,
471
+ useId as useId3,
472
+ useMemo as useMemo6,
473
+ useRef as useRef12,
474
+ useState as useState16
475
+ } from "react";
731
476
 
732
- // ../../node_modules/.pnpm/@ai-sdk+react@3.0.232_react@19.2.8_zod@4.4.3/node_modules/@ai-sdk/react/dist/index.mjs
477
+ // ../utils/lib/get-class-name-factory.ts
478
+ init_react_import();
479
+ var import_classnames = __toESM(require_classnames());
480
+ var getClassNameFactory = (rootClass, styles, { baseClass = "" } = {}) => (options = {}) => {
481
+ let descendant = false;
482
+ let modifiers = false;
483
+ if (typeof options === "string") {
484
+ descendant = options;
485
+ } else if (typeof options === "object") {
486
+ modifiers = options;
487
+ }
488
+ if (descendant) {
489
+ const style = styles[`${rootClass}-${descendant}`];
490
+ if (style) {
491
+ return baseClass + styles[`${rootClass}-${descendant}`] || "";
492
+ }
493
+ return "";
494
+ } else if (modifiers) {
495
+ const prefixedModifiers = {};
496
+ for (let modifier in modifiers) {
497
+ prefixedModifiers[styles[`${rootClass}--${modifier}`]] = modifiers[modifier];
498
+ }
499
+ const c = styles[rootClass];
500
+ return baseClass + (0, import_classnames.default)({
501
+ [c]: !!c,
502
+ // only apply the class if it exists
503
+ ...prefixedModifiers
504
+ });
505
+ } else {
506
+ return baseClass + styles[rootClass] || "";
507
+ }
508
+ };
509
+ var get_class_name_factory_default = getClassNameFactory;
510
+
511
+ // css-module:/home/runner/work/platform/platform/packages/plugin-ai/src/components/Chat/styles.module.css#css-module
512
+ init_react_import();
513
+ var styles_module_default = { "Chat": "_Chat_1ei0a_1", "Chat-header": "_Chat-header_1ei0a_9", "Chat-placeholder": "_Chat-placeholder_1ei0a_23", "Chat-placeholderIcon": "_Chat-placeholderIcon_1ei0a_42", "Chat-placeholderTitle": "_Chat-placeholderTitle_1ei0a_53", "Chat-placeholderDescription": "_Chat-placeholderDescription_1ei0a_58", "Chat-actions": "_Chat-actions_1ei0a_64", "Chat-action": "_Chat-action_1ei0a_64", "Chat-actionOutlined": "_Chat-actionOutlined_1ei0a_73", "Chat-attachmentControls": "_Chat-attachmentControls_1ei0a_108", "Chat-attachmentInput": "_Chat-attachmentInput_1ei0a_115", "Chat-attachmentButton": "_Chat-attachmentButton_1ei0a_119" };
514
+
515
+ // src/components/ChatBody/index.tsx
733
516
  init_react_import();
734
- var import_throttleit = __toESM(require_throttleit(), 1);
735
- import {
736
- DefaultChatTransport
737
- } from "ai";
738
- import { useCallback, useEffect, useRef, useSyncExternalStore } from "react";
739
- import {
740
- AbstractChat
741
- } from "ai";
742
- import {
743
- callCompletionApi
744
- } from "ai";
745
- import { useCallback as useCallback2, useEffect as useEffect2, useId, useRef as useRef2, useState } from "react";
746
517
  import {
747
- asSchema,
748
- isDeepEqualData,
749
- parsePartialJson
750
- } from "ai";
751
- import { useCallback as useCallback3, useId as useId2, useRef as useRef3, useState as useState2 } from "react";
752
- var __accessCheck = (obj, member, msg) => {
753
- if (!member.has(obj))
754
- throw TypeError("Cannot " + msg);
518
+ useContext as useContext3,
519
+ useEffect as useEffect7,
520
+ useMemo as useMemo3,
521
+ useRef as useRef6,
522
+ useState as useState11
523
+ } from "react";
524
+ import { useStickToBottom } from "use-stick-to-bottom";
525
+ import Markdown from "react-markdown";
526
+
527
+ // ../platform-client/index.ts
528
+ init_react_import();
529
+
530
+ // ../platform-client/components/ActionModal/index.ts
531
+ init_react_import();
532
+
533
+ // ../platform-client/components/ActionModal/ActionModal.tsx
534
+ init_react_import();
535
+
536
+ // css-module:/home/runner/work/platform/platform/packages/platform-client/components/ActionModal/ActionModal.module.css#css-module
537
+ init_react_import();
538
+ var ActionModal_module_default = { "ActionModal": "_ActionModal_1g44k_1", "ActionModal-header": "_ActionModal-header_1g44k_6", "ActionModal-body": "_ActionModal-body_1g44k_17", "ActionModal-footer": "_ActionModal-footer_1g44k_25" };
539
+
540
+ // ../platform-client/lib/index.ts
541
+ init_react_import();
542
+
543
+ // ../platform-client/lib/get-class-name-factory.ts
544
+ init_react_import();
545
+ var import_classnames2 = __toESM(require_classnames());
546
+ var getClassNameFactory2 = (rootClass, styles, { baseClass = "" } = {}) => (options = {}) => {
547
+ let descendant = false;
548
+ let modifiers = false;
549
+ if (typeof options === "string") {
550
+ descendant = options;
551
+ } else if (typeof options === "object") {
552
+ modifiers = options;
553
+ }
554
+ if (descendant) {
555
+ const style = styles[`${rootClass}-${descendant}`];
556
+ if (style) {
557
+ return baseClass + styles[`${rootClass}-${descendant}`] || "";
558
+ }
559
+ return "";
560
+ } else if (modifiers) {
561
+ const prefixedModifiers = {};
562
+ for (let modifier in modifiers) {
563
+ prefixedModifiers[styles[`${rootClass}--${modifier}`]] = modifiers[modifier];
564
+ }
565
+ const c = styles[rootClass];
566
+ return baseClass + (0, import_classnames2.default)({
567
+ [c]: !!c,
568
+ // only apply the class if it exists
569
+ ...prefixedModifiers
570
+ });
571
+ } else {
572
+ return baseClass + styles[rootClass] || "";
573
+ }
755
574
  };
756
- var __privateGet = (obj, member, getter) => {
757
- __accessCheck(obj, member, "read from private field");
758
- return getter ? getter.call(obj) : member.get(obj);
759
- };
760
- var __privateAdd = (obj, member, value) => {
761
- if (member.has(obj))
762
- throw TypeError("Cannot add the same private member more than once");
763
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
764
- };
765
- var __privateSet = (obj, member, value, setter) => {
766
- __accessCheck(obj, member, "write to private field");
767
- setter ? setter.call(obj, value) : member.set(obj, value);
768
- return value;
769
- };
770
- function throttle(fn, waitMs) {
771
- return waitMs != null ? (0, import_throttleit.default)(fn, waitMs) : fn;
772
- }
773
- var _messages;
774
- var _status;
775
- var _error;
776
- var _messagesCallbacks;
777
- var _statusCallbacks;
778
- var _errorCallbacks;
779
- var _callMessagesCallbacks;
780
- var _callStatusCallbacks;
781
- var _callErrorCallbacks;
782
- var ReactChatState = class {
783
- constructor(initialMessages = []) {
784
- __privateAdd(this, _messages, void 0);
785
- __privateAdd(this, _status, "ready");
786
- __privateAdd(this, _error, void 0);
787
- __privateAdd(this, _messagesCallbacks, /* @__PURE__ */ new Set());
788
- __privateAdd(this, _statusCallbacks, /* @__PURE__ */ new Set());
789
- __privateAdd(this, _errorCallbacks, /* @__PURE__ */ new Set());
790
- this.pushMessage = (message) => {
791
- __privateSet(this, _messages, __privateGet(this, _messages).concat(message));
792
- __privateGet(this, _callMessagesCallbacks).call(this);
793
- };
794
- this.popMessage = () => {
795
- __privateSet(this, _messages, __privateGet(this, _messages).slice(0, -1));
796
- __privateGet(this, _callMessagesCallbacks).call(this);
797
- };
798
- this.replaceMessage = (index, message) => {
799
- __privateSet(this, _messages, [
800
- ...__privateGet(this, _messages).slice(0, index),
801
- // We deep clone the message here to ensure the new React Compiler (currently in RC) detects deeply nested parts/metadata changes:
802
- this.snapshot(message),
803
- ...__privateGet(this, _messages).slice(index + 1)
804
- ]);
805
- __privateGet(this, _callMessagesCallbacks).call(this);
806
- };
807
- this.snapshot = (value) => structuredClone(value);
808
- this["~registerMessagesCallback"] = (onChange, throttleWaitMs) => {
809
- const callback = throttleWaitMs ? throttle(onChange, throttleWaitMs) : onChange;
810
- __privateGet(this, _messagesCallbacks).add(callback);
811
- return () => {
812
- __privateGet(this, _messagesCallbacks).delete(callback);
813
- };
814
- };
815
- this["~registerStatusCallback"] = (onChange) => {
816
- __privateGet(this, _statusCallbacks).add(onChange);
817
- return () => {
818
- __privateGet(this, _statusCallbacks).delete(onChange);
819
- };
820
- };
821
- this["~registerErrorCallback"] = (onChange) => {
822
- __privateGet(this, _errorCallbacks).add(onChange);
823
- return () => {
824
- __privateGet(this, _errorCallbacks).delete(onChange);
825
- };
826
- };
827
- __privateAdd(this, _callMessagesCallbacks, () => {
828
- __privateGet(this, _messagesCallbacks).forEach((callback) => callback());
829
- });
830
- __privateAdd(this, _callStatusCallbacks, () => {
831
- __privateGet(this, _statusCallbacks).forEach((callback) => callback());
832
- });
833
- __privateAdd(this, _callErrorCallbacks, () => {
834
- __privateGet(this, _errorCallbacks).forEach((callback) => callback());
835
- });
836
- __privateSet(this, _messages, initialMessages);
837
- }
838
- get status() {
839
- return __privateGet(this, _status);
840
- }
841
- set status(newStatus) {
842
- __privateSet(this, _status, newStatus);
843
- __privateGet(this, _callStatusCallbacks).call(this);
844
- }
845
- get error() {
846
- return __privateGet(this, _error);
847
- }
848
- set error(newError) {
849
- __privateSet(this, _error, newError);
850
- __privateGet(this, _callErrorCallbacks).call(this);
851
- }
852
- get messages() {
853
- return __privateGet(this, _messages);
854
- }
855
- set messages(newMessages) {
856
- __privateSet(this, _messages, [...newMessages]);
857
- __privateGet(this, _callMessagesCallbacks).call(this);
858
- }
859
- };
860
- _messages = /* @__PURE__ */ new WeakMap();
861
- _status = /* @__PURE__ */ new WeakMap();
862
- _error = /* @__PURE__ */ new WeakMap();
863
- _messagesCallbacks = /* @__PURE__ */ new WeakMap();
864
- _statusCallbacks = /* @__PURE__ */ new WeakMap();
865
- _errorCallbacks = /* @__PURE__ */ new WeakMap();
866
- _callMessagesCallbacks = /* @__PURE__ */ new WeakMap();
867
- _callStatusCallbacks = /* @__PURE__ */ new WeakMap();
868
- _callErrorCallbacks = /* @__PURE__ */ new WeakMap();
869
- var _state;
870
- var Chat = class extends AbstractChat {
871
- constructor({ messages, ...init }) {
872
- const state = new ReactChatState(messages);
873
- super({ ...init, state });
874
- __privateAdd(this, _state, void 0);
875
- this["~registerMessagesCallback"] = (onChange, throttleWaitMs) => __privateGet(this, _state)["~registerMessagesCallback"](onChange, throttleWaitMs);
876
- this["~registerStatusCallback"] = (onChange) => __privateGet(this, _state)["~registerStatusCallback"](onChange);
877
- this["~registerErrorCallback"] = (onChange) => __privateGet(this, _state)["~registerErrorCallback"](onChange);
878
- __privateSet(this, _state, state);
879
- }
880
- };
881
- _state = /* @__PURE__ */ new WeakMap();
882
- function useChat({
883
- experimental_throttle: throttleWaitMs,
884
- resume = false,
885
- ...options
886
- } = {}) {
887
- const latestRef = useRef({});
888
- if (!("chat" in options)) {
889
- latestRef.current = {
890
- onToolCall: options.onToolCall,
891
- onData: options.onData,
892
- onFinish: options.onFinish,
893
- onError: options.onError,
894
- sendAutomaticallyWhen: options.sendAutomaticallyWhen,
895
- transport: options.transport
896
- };
897
- }
898
- let defaultTransport;
899
- const getTransport = () => {
900
- var _a;
901
- return (_a = latestRef.current.transport) != null ? _a : defaultTransport != null ? defaultTransport : defaultTransport = new DefaultChatTransport();
902
- };
903
- const chatOptions = {
904
- ...options,
905
- transport: {
906
- sendMessages: (sendOptions) => getTransport().sendMessages(sendOptions),
907
- reconnectToStream: (reconnectOptions) => getTransport().reconnectToStream(reconnectOptions)
908
- },
909
- onToolCall: (arg) => {
910
- var _a, _b;
911
- return (_b = (_a = latestRef.current).onToolCall) == null ? void 0 : _b.call(_a, arg);
912
- },
913
- onData: (arg) => {
914
- var _a, _b;
915
- return (_b = (_a = latestRef.current).onData) == null ? void 0 : _b.call(_a, arg);
916
- },
917
- onFinish: (arg) => {
918
- var _a, _b;
919
- return (_b = (_a = latestRef.current).onFinish) == null ? void 0 : _b.call(_a, arg);
920
- },
921
- onError: (arg) => {
922
- var _a, _b;
923
- return (_b = (_a = latestRef.current).onError) == null ? void 0 : _b.call(_a, arg);
924
- },
925
- sendAutomaticallyWhen: (arg) => {
926
- var _a, _b, _c;
927
- return (_c = (_b = (_a = latestRef.current).sendAutomaticallyWhen) == null ? void 0 : _b.call(_a, arg)) != null ? _c : false;
928
- }
929
- };
930
- const chatRef = useRef(
931
- "chat" in options ? options.chat : new Chat(chatOptions)
932
- );
933
- const shouldRecreateChat = "chat" in options && options.chat !== chatRef.current || "id" in options && options.id != null && chatRef.current.id !== options.id;
934
- if (shouldRecreateChat) {
935
- chatRef.current = "chat" in options ? options.chat : new Chat(chatOptions);
936
- }
937
- const subscribeToMessages = useCallback(
938
- (update) => chatRef.current["~registerMessagesCallback"](update, throttleWaitMs),
939
- // `chatRef.current.id` is required to trigger re-subscription when the chat ID changes
940
- // eslint-disable-next-line react-hooks/exhaustive-deps
941
- [throttleWaitMs, chatRef.current.id]
942
- );
943
- const messages = useSyncExternalStore(
944
- subscribeToMessages,
945
- () => chatRef.current.messages,
946
- () => chatRef.current.messages
947
- );
948
- const status = useSyncExternalStore(
949
- chatRef.current["~registerStatusCallback"],
950
- () => chatRef.current.status,
951
- () => chatRef.current.status
952
- );
953
- const error = useSyncExternalStore(
954
- chatRef.current["~registerErrorCallback"],
955
- () => chatRef.current.error,
956
- () => chatRef.current.error
957
- );
958
- const setMessages = useCallback(
959
- (messagesParam) => {
960
- if (typeof messagesParam === "function") {
961
- messagesParam = messagesParam(chatRef.current.messages);
962
- }
963
- chatRef.current.messages = messagesParam;
964
- },
965
- [chatRef]
966
- );
967
- useEffect(() => {
968
- if (resume) {
969
- chatRef.current.resumeStream();
970
- }
971
- }, [resume, chatRef]);
972
- return {
973
- id: chatRef.current.id,
974
- messages,
975
- setMessages,
976
- sendMessage: chatRef.current.sendMessage,
977
- regenerate: chatRef.current.regenerate,
978
- clearError: chatRef.current.clearError,
979
- stop: chatRef.current.stop,
980
- error,
981
- resumeStream: chatRef.current.resumeStream,
982
- status,
983
- /**
984
- * @deprecated Use `addToolOutput` instead.
985
- */
986
- addToolResult: chatRef.current.addToolOutput,
987
- addToolOutput: chatRef.current.addToolOutput,
988
- addToolApprovalResponse: chatRef.current.addToolApprovalResponse
989
- };
990
- }
991
-
992
- // src/components/Chat/index.tsx
993
- import {
994
- createUsePuck,
995
- useGetPuck as useGetPuck4
996
- } from "@puckeditor/core";
997
- import {
998
- DefaultChatTransport as DefaultChatTransport2
999
- } from "ai";
1000
- import {
1001
- useCallback as useCallback6,
1002
- useEffect as useEffect13,
1003
- useId as useId3,
1004
- useMemo as useMemo6,
1005
- useRef as useRef13,
1006
- useState as useState16
1007
- } from "react";
1008
- import { ulid } from "ulid";
1009
-
1010
- // ../utils/lib/get-class-name-factory.ts
1011
- init_react_import();
1012
- var import_classnames = __toESM(require_classnames());
1013
- var getClassNameFactory = (rootClass, styles, { baseClass = "" } = {}) => (options = {}) => {
1014
- let descendant = false;
1015
- let modifiers = false;
1016
- if (typeof options === "string") {
1017
- descendant = options;
1018
- } else if (typeof options === "object") {
1019
- modifiers = options;
1020
- }
1021
- if (descendant) {
1022
- const style = styles[`${rootClass}-${descendant}`];
1023
- if (style) {
1024
- return baseClass + styles[`${rootClass}-${descendant}`] || "";
1025
- }
1026
- return "";
1027
- } else if (modifiers) {
1028
- const prefixedModifiers = {};
1029
- for (let modifier in modifiers) {
1030
- prefixedModifiers[styles[`${rootClass}--${modifier}`]] = modifiers[modifier];
1031
- }
1032
- const c = styles[rootClass];
1033
- return baseClass + (0, import_classnames.default)({
1034
- [c]: !!c,
1035
- // only apply the class if it exists
1036
- ...prefixedModifiers
1037
- });
1038
- } else {
1039
- return baseClass + styles[rootClass] || "";
1040
- }
1041
- };
1042
- var get_class_name_factory_default = getClassNameFactory;
1043
-
1044
- // css-module:/home/runner/work/platform/platform/packages/plugin-ai/src/components/Chat/styles.module.css#css-module
1045
- init_react_import();
1046
- var styles_module_default = { "Chat": "_Chat_1ei0a_1", "Chat-header": "_Chat-header_1ei0a_9", "Chat-placeholder": "_Chat-placeholder_1ei0a_23", "Chat-placeholderIcon": "_Chat-placeholderIcon_1ei0a_42", "Chat-placeholderTitle": "_Chat-placeholderTitle_1ei0a_53", "Chat-placeholderDescription": "_Chat-placeholderDescription_1ei0a_58", "Chat-actions": "_Chat-actions_1ei0a_64", "Chat-action": "_Chat-action_1ei0a_64", "Chat-actionOutlined": "_Chat-actionOutlined_1ei0a_73", "Chat-attachmentControls": "_Chat-attachmentControls_1ei0a_108", "Chat-attachmentInput": "_Chat-attachmentInput_1ei0a_115", "Chat-attachmentButton": "_Chat-attachmentButton_1ei0a_119" };
1047
-
1048
- // src/components/ChatBody/index.tsx
1049
- init_react_import();
1050
- import {
1051
- useContext as useContext3,
1052
- useEffect as useEffect9,
1053
- useMemo as useMemo3,
1054
- useRef as useRef9,
1055
- useState as useState13
1056
- } from "react";
1057
- import { useStickToBottom } from "use-stick-to-bottom";
1058
- import Markdown from "react-markdown";
1059
-
1060
- // ../platform-client/index.ts
1061
- init_react_import();
1062
-
1063
- // ../platform-client/components/ActionModal/index.ts
1064
- init_react_import();
1065
-
1066
- // ../platform-client/components/ActionModal/ActionModal.tsx
1067
- init_react_import();
1068
-
1069
- // css-module:/home/runner/work/platform/platform/packages/platform-client/components/ActionModal/ActionModal.module.css#css-module
1070
- init_react_import();
1071
- var ActionModal_module_default = { "ActionModal": "_ActionModal_1g44k_1", "ActionModal-header": "_ActionModal-header_1g44k_6", "ActionModal-body": "_ActionModal-body_1g44k_17", "ActionModal-footer": "_ActionModal-footer_1g44k_25" };
1072
-
1073
- // ../platform-client/lib/index.ts
1074
- init_react_import();
1075
-
1076
- // ../platform-client/lib/get-class-name-factory.ts
1077
- init_react_import();
1078
- var import_classnames2 = __toESM(require_classnames());
1079
- var getClassNameFactory2 = (rootClass, styles, { baseClass = "" } = {}) => (options = {}) => {
1080
- let descendant = false;
1081
- let modifiers = false;
1082
- if (typeof options === "string") {
1083
- descendant = options;
1084
- } else if (typeof options === "object") {
1085
- modifiers = options;
1086
- }
1087
- if (descendant) {
1088
- const style = styles[`${rootClass}-${descendant}`];
1089
- if (style) {
1090
- return baseClass + styles[`${rootClass}-${descendant}`] || "";
1091
- }
1092
- return "";
1093
- } else if (modifiers) {
1094
- const prefixedModifiers = {};
1095
- for (let modifier in modifiers) {
1096
- prefixedModifiers[styles[`${rootClass}--${modifier}`]] = modifiers[modifier];
1097
- }
1098
- const c = styles[rootClass];
1099
- return baseClass + (0, import_classnames2.default)({
1100
- [c]: !!c,
1101
- // only apply the class if it exists
1102
- ...prefixedModifiers
1103
- });
1104
- } else {
1105
- return baseClass + styles[rootClass] || "";
1106
- }
1107
- };
1108
- var get_class_name_factory_default2 = getClassNameFactory2;
1109
-
1110
- // ../platform-client/components/Modal/Modal.tsx
1111
- init_react_import();
1112
-
1113
- // css-module:/home/runner/work/platform/platform/packages/platform-client/components/Modal/Modal.module.css#css-module
1114
- init_react_import();
1115
- var Modal_module_default = { "Modal-background": "_Modal-background_1bedq_1", "Modal--visible": "_Modal--visible_1bedq_16", "Modal-modal": "_Modal-modal_1bedq_22" };
1116
-
1117
- // ../platform-client/components/Modal/Modal.tsx
1118
- import { createContext, useContext } from "react";
1119
-
1120
- // ../platform-client/lib/use-modal-visible.ts
1121
- init_react_import();
1122
- import { useEffect as useEffect3, useState as useState3, useRef as useRef4 } from "react";
1123
- var useModalVisible = (defaultVisible) => {
1124
- const [visible, setVisible] = useState3(defaultVisible ?? false);
1125
- const ref = useRef4(null);
1126
- useEffect3(() => {
1127
- if (!visible) {
1128
- return;
1129
- }
1130
- const handler = (e) => {
1131
- if (ref.current && !ref.current.contains(e.target)) {
1132
- setVisible(false);
1133
- }
1134
- };
1135
- document.body.addEventListener("click", handler);
1136
- return () => {
1137
- document.body.removeEventListener("click", handler);
1138
- };
1139
- }, [visible]);
1140
- return [visible, setVisible, ref];
575
+ var get_class_name_factory_default2 = getClassNameFactory2;
576
+
577
+ // ../platform-client/components/Modal/Modal.tsx
578
+ init_react_import();
579
+
580
+ // css-module:/home/runner/work/platform/platform/packages/platform-client/components/Modal/Modal.module.css#css-module
581
+ init_react_import();
582
+ var Modal_module_default = { "Modal-background": "_Modal-background_1bedq_1", "Modal--visible": "_Modal--visible_1bedq_16", "Modal-modal": "_Modal-modal_1bedq_22" };
583
+
584
+ // ../platform-client/components/Modal/Modal.tsx
585
+ import { createContext, useContext } from "react";
586
+
587
+ // ../platform-client/lib/use-modal-visible.ts
588
+ init_react_import();
589
+ import { useEffect, useState, useRef } from "react";
590
+ var useModalVisible = (defaultVisible) => {
591
+ const [visible, setVisible] = useState(defaultVisible ?? false);
592
+ const ref = useRef(null);
593
+ useEffect(() => {
594
+ if (!visible) {
595
+ return;
596
+ }
597
+ const handler = (e) => {
598
+ if (ref.current && !ref.current.contains(e.target)) {
599
+ setVisible(false);
600
+ }
601
+ };
602
+ document.body.addEventListener("click", handler);
603
+ return () => {
604
+ document.body.removeEventListener("click", handler);
605
+ };
606
+ }, [visible]);
607
+ return [visible, setVisible, ref];
1141
608
  };
1142
609
 
1143
610
  // ../platform-client/components/Button/index.ts
@@ -1145,7 +612,7 @@ init_react_import();
1145
612
 
1146
613
  // ../platform-client/components/Button/Button.tsx
1147
614
  init_react_import();
1148
- import { useEffect as useEffect4, useState as useState4 } from "react";
615
+ import { useEffect as useEffect2, useState as useState2 } from "react";
1149
616
 
1150
617
  // css-module:/home/runner/work/platform/platform/packages/platform-client/components/Button/Button.module.css#css-module
1151
618
  init_react_import();
@@ -1198,8 +665,8 @@ var Button = ({
1198
665
  size = "medium",
1199
666
  loading: loadingProp = false
1200
667
  }) => {
1201
- const [loading, setLoading] = useState4(loadingProp);
1202
- useEffect4(() => {
668
+ const [loading, setLoading] = useState2(loadingProp);
669
+ useEffect2(() => {
1203
670
  const resetLoading = () => setLoading(loadingProp);
1204
671
  resetLoading();
1205
672
  window.addEventListener("pageshow", resetLoading);
@@ -1388,7 +855,7 @@ init_react_import();
1388
855
  // ../platform-client/components/AutoForm/AutoForm.tsx
1389
856
  init_react_import();
1390
857
  import { AutoField, FieldLabel } from "@puckeditor/core";
1391
- import { useEffect as useEffect5, useRef as useRef5, useState as useState5 } from "react";
858
+ import { useEffect as useEffect3, useRef as useRef2, useState as useState3 } from "react";
1392
859
 
1393
860
  // css-module:/home/runner/work/platform/platform/packages/platform-client/components/AutoForm/AutoForm.module.css#css-module
1394
861
  init_react_import();
@@ -1436,11 +903,11 @@ var Code_module_default = { "Code": "_Code_d4378_1", "Code-body": "_Code-body_d4
1436
903
 
1437
904
  // ../platform-client/components/Code/CopyAction.tsx
1438
905
  init_react_import();
1439
- import { useEffect as useEffect6, useState as useState6 } from "react";
906
+ import { useEffect as useEffect4, useState as useState4 } from "react";
1440
907
  import { jsx as jsx11 } from "react/jsx-runtime";
1441
908
 
1442
909
  // ../platform-client/components/Code/Code.tsx
1443
- import { useRef as useRef6, useState as useState7 } from "react";
910
+ import { useRef as useRef3, useState as useState5 } from "react";
1444
911
  import { jsx as jsx12, jsxs as jsxs7 } from "react/jsx-runtime";
1445
912
  var getClassName9 = get_class_name_factory_default("Code", Code_module_default);
1446
913
  var getClassNameTab = get_class_name_factory_default("Tab", Code_module_default);
@@ -1450,7 +917,7 @@ init_react_import();
1450
917
 
1451
918
  // ../platform-client/components/IconButton/IconButton.tsx
1452
919
  init_react_import();
1453
- import { useState as useState8 } from "react";
920
+ import { useState as useState6 } from "react";
1454
921
 
1455
922
  // css-module:/home/runner/work/platform/platform/packages/platform-client/components/IconButton/IconButton.module.css#css-module
1456
923
  init_react_import();
@@ -1472,7 +939,7 @@ var IconButton = ({
1472
939
  title,
1473
940
  dark
1474
941
  }) => {
1475
- const [loading, setLoading] = useState8(false);
942
+ const [loading, setLoading] = useState6(false);
1476
943
  const ElementType = href ? "a" : onClick ? "button" : "div";
1477
944
  const el = /* @__PURE__ */ jsxs8(
1478
945
  ElementType,
@@ -1604,7 +1071,7 @@ var getClassName12 = get_class_name_factory_default2("Link", Link_module_default
1604
1071
 
1605
1072
  // ../platform-client/components/Menu/index.tsx
1606
1073
  init_react_import();
1607
- import { useState as useState9 } from "react";
1074
+ import { useState as useState7 } from "react";
1608
1075
 
1609
1076
  // css-module:/home/runner/work/platform/platform/packages/platform-client/components/Menu/styles.module.css#css-module
1610
1077
  init_react_import();
@@ -1733,7 +1200,7 @@ init_react_import();
1733
1200
 
1734
1201
  // ../platform-client/components/Table/Table.tsx
1735
1202
  init_react_import();
1736
- import { useEffect as useEffect7, useMemo as useMemo2, useRef as useRef7, useState as useState10 } from "react";
1203
+ import { useEffect as useEffect5, useMemo as useMemo2, useRef as useRef4, useState as useState8 } from "react";
1737
1204
 
1738
1205
  // css-module:/home/runner/work/platform/platform/packages/platform-client/components/Table/Table.module.css#css-module
1739
1206
  init_react_import();
@@ -1775,7 +1242,7 @@ var cx6 = getClassNameFactory("Viewport", styles_module_default6);
1775
1242
 
1776
1243
  // ../platform-client/context/editor.tsx
1777
1244
  init_react_import();
1778
- import { createContext as createContext2, useContext as useContext2, useState as useState11 } from "react";
1245
+ import { createContext as createContext2, useContext as useContext2, useState as useState9 } from "react";
1779
1246
  import { jsx as jsx27 } from "react/jsx-runtime";
1780
1247
  var ctx = createContext2({});
1781
1248
 
@@ -1786,10 +1253,10 @@ var styles_module_default7 = { "Chat": "_Chat_5z5yi_1", "Chat--hasMessages": "_C
1786
1253
  // src/components/PromptForm/index.tsx
1787
1254
  init_react_import();
1788
1255
  import {
1789
- useCallback as useCallback4,
1790
- useEffect as useEffect8,
1791
- useRef as useRef8,
1792
- useState as useState12
1256
+ useCallback,
1257
+ useEffect as useEffect6,
1258
+ useRef as useRef5,
1259
+ useState as useState10
1793
1260
  } from "react";
1794
1261
 
1795
1262
  // css-module:/home/runner/work/platform/platform/packages/plugin-ai/src/components/PromptForm/styles.module.css#css-module
@@ -1876,13 +1343,13 @@ function PromptForm({
1876
1343
  maxRows = 5,
1877
1344
  value = ""
1878
1345
  }) {
1879
- const hasSetInitialPrompt = useRef8(false);
1880
- const [prompt, setPrompt] = useState12(value);
1881
- const internalRef = useRef8(null);
1882
- const [isDragOver, setIsDragOver] = useState12(false);
1883
- const dragCounterRef = useRef8(0);
1346
+ const hasSetInitialPrompt = useRef5(false);
1347
+ const [prompt, setPrompt] = useState10(value);
1348
+ const internalRef = useRef5(null);
1349
+ const [isDragOver, setIsDragOver] = useState10(false);
1350
+ const dragCounterRef = useRef5(0);
1884
1351
  const canDrop = !!onFileDrop && !isDisabled && !isLoading;
1885
- const handleDragEnter = useCallback4(
1352
+ const handleDragEnter = useCallback(
1886
1353
  (e) => {
1887
1354
  e.preventDefault();
1888
1355
  dragCounterRef.current++;
@@ -1892,17 +1359,17 @@ function PromptForm({
1892
1359
  },
1893
1360
  [canDrop]
1894
1361
  );
1895
- const handleDragLeave = useCallback4((e) => {
1362
+ const handleDragLeave = useCallback((e) => {
1896
1363
  e.preventDefault();
1897
1364
  dragCounterRef.current--;
1898
1365
  if (dragCounterRef.current === 0) {
1899
1366
  setIsDragOver(false);
1900
1367
  }
1901
1368
  }, []);
1902
- const handleDragOver = useCallback4((e) => {
1369
+ const handleDragOver = useCallback((e) => {
1903
1370
  e.preventDefault();
1904
1371
  }, []);
1905
- const handleDrop = useCallback4(
1372
+ const handleDrop = useCallback(
1906
1373
  (e) => {
1907
1374
  e.preventDefault();
1908
1375
  dragCounterRef.current = 0;
@@ -1916,7 +1383,7 @@ function PromptForm({
1916
1383
  },
1917
1384
  [canDrop, onFileDrop]
1918
1385
  );
1919
- useEffect8(() => {
1386
+ useEffect6(() => {
1920
1387
  setPrompt(value);
1921
1388
  }, [setPrompt, value]);
1922
1389
  const sendPrompt = async () => {
@@ -1931,7 +1398,7 @@ function PromptForm({
1931
1398
  setPrompt("");
1932
1399
  }
1933
1400
  };
1934
- useEffect8(() => {
1401
+ useEffect6(() => {
1935
1402
  const currentUrl = new URL(location.href);
1936
1403
  const initialPrompt = currentUrl.searchParams.get("initialPrompt");
1937
1404
  if (!hasSetInitialPrompt.current && initialPrompt && prompt === "") {
@@ -2276,12 +1743,12 @@ function ChatMessageWrapper({
2276
1743
  return /* @__PURE__ */ jsx29("span", { children });
2277
1744
  }
2278
1745
  function ReasoningBlock({ part }) {
2279
- const startTimeRef = useRef9(null);
2280
- const [durationSecs, setDurationSecs] = useState13(null);
1746
+ const startTimeRef = useRef6(null);
1747
+ const [durationSecs, setDurationSecs] = useState11(null);
2281
1748
  if (part.state !== "done" && startTimeRef.current === null) {
2282
1749
  startTimeRef.current = Date.now();
2283
1750
  }
2284
- useEffect9(() => {
1751
+ useEffect7(() => {
2285
1752
  if (part.state === "done" && startTimeRef.current !== null) {
2286
1753
  setDurationSecs(Math.round((Date.now() - startTimeRef.current) / 1e3));
2287
1754
  }
@@ -2381,7 +1848,66 @@ function SubagentBlock({ toolCallId }) {
2381
1848
  const loading = state ? state.state !== "done" : toolStatus?.loading ?? true;
2382
1849
  const hasBody = !!state && state.parts.length > 0;
2383
1850
  const parts = state?.parts ?? [];
2384
- const [isOpen, setIsOpen] = useState13(false);
1851
+ const [isOpen, setIsOpen] = useState11(false);
1852
+ return /* @__PURE__ */ jsxs16(
1853
+ "details",
1854
+ {
1855
+ className: cxMessage("event"),
1856
+ onToggle: (e) => setIsOpen(e.currentTarget.open),
1857
+ children: [
1858
+ /* @__PURE__ */ jsxs16(
1859
+ "summary",
1860
+ {
1861
+ className: cxMessage("eventHeader"),
1862
+ style: hasBody ? {} : { color: "var(--puck-color-grey-05) !important", cursor: "unset" },
1863
+ children: [
1864
+ /* @__PURE__ */ jsx29("div", { className: cxMessage("eventIcon"), children: loading ? /* @__PURE__ */ jsx29(Loader, { size: 16 }) : /* @__PURE__ */ jsx29(Bot, { size: 18 }) }),
1865
+ /* @__PURE__ */ jsx29("div", { className: cxMessage("eventLabel"), children: label }),
1866
+ hasBody && /* @__PURE__ */ jsxs16(Fragment5, { children: [
1867
+ /* @__PURE__ */ jsx29("div", { className: cxMessage("eventExpand"), children: /* @__PURE__ */ jsx29(Plus, { size: 12 }) }),
1868
+ /* @__PURE__ */ jsx29("div", { className: cxMessage("eventCollapse"), children: /* @__PURE__ */ jsx29(Minus, { size: 12 }) })
1869
+ ] })
1870
+ ]
1871
+ }
1872
+ ),
1873
+ hasBody && isOpen && /* @__PURE__ */ jsx29("div", { className: cxMessage("eventBody"), children: parts.map((part, i) => /* @__PURE__ */ jsx29(SubagentChildPartRenderer, { part }, `${toolCallId}-${i}`)) })
1874
+ ]
1875
+ }
1876
+ );
1877
+ }
1878
+ function SubagentChildPartRenderer({ part }) {
1879
+ if (part.kind === "text") {
1880
+ return /* @__PURE__ */ jsx29("div", { className: cxMessage("text"), children: /* @__PURE__ */ jsx29(Markdown, { children: part.text }) });
1881
+ }
1882
+ if (part.kind === "reasoning") {
1883
+ return /* @__PURE__ */ jsx29(
1884
+ ReasoningBlock,
1885
+ {
1886
+ part: {
1887
+ type: "reasoning",
1888
+ text: part.text,
1889
+ state: part.state
1890
+ }
1891
+ }
1892
+ );
1893
+ }
1894
+ if (part.toolName === "subagent") {
1895
+ return /* @__PURE__ */ jsx29(SubagentBlock, { toolCallId: part.childToolCallId });
1896
+ }
1897
+ const synthesized = {
1898
+ toolCallId: part.childToolCallId,
1899
+ type: `tool-${part.toolName}`,
1900
+ state: part.output !== void 0 ? "output-available" : "input-available",
1901
+ input: part.input,
1902
+ output: part.output
1903
+ };
1904
+ return /* @__PURE__ */ jsx29(PuckTool, { ...synthesized });
1905
+ }
1906
+ function ChatEvent({
1907
+ status,
1908
+ icon = /* @__PURE__ */ jsx29(Check, { size: 18 })
1909
+ }) {
1910
+ const [isOpen, setIsOpen] = useState11(false);
2385
1911
  return /* @__PURE__ */ jsxs16(
2386
1912
  "details",
2387
1913
  {
@@ -2392,172 +1918,616 @@ function SubagentBlock({ toolCallId }) {
2392
1918
  "summary",
2393
1919
  {
2394
1920
  className: cxMessage("eventHeader"),
2395
- style: hasBody ? {} : { color: "var(--puck-color-grey-05) !important", cursor: "unset" },
1921
+ style: status.summary ? {} : { color: "var(--puck-color-grey-05) !important", cursor: "unset" },
2396
1922
  children: [
2397
- /* @__PURE__ */ jsx29("div", { className: cxMessage("eventIcon"), children: loading ? /* @__PURE__ */ jsx29(Loader, { size: 16 }) : /* @__PURE__ */ jsx29(Bot, { size: 18 }) }),
2398
- /* @__PURE__ */ jsx29("div", { className: cxMessage("eventLabel"), children: label }),
2399
- hasBody && /* @__PURE__ */ jsxs16(Fragment5, { children: [
1923
+ /* @__PURE__ */ jsx29("div", { className: cxMessage("eventIcon"), children: status.error ? /* @__PURE__ */ jsx29(TriangleAlert, { size: 18 }) : status.loading ? /* @__PURE__ */ jsx29(Loader, { size: 16 }) : icon }),
1924
+ /* @__PURE__ */ jsx29("div", { children: status.label }),
1925
+ status.summary && /* @__PURE__ */ jsxs16(Fragment5, { children: [
2400
1926
  /* @__PURE__ */ jsx29("div", { className: cxMessage("eventExpand"), children: /* @__PURE__ */ jsx29(Plus, { size: 12 }) }),
2401
1927
  /* @__PURE__ */ jsx29("div", { className: cxMessage("eventCollapse"), children: /* @__PURE__ */ jsx29(Minus, { size: 12 }) })
2402
1928
  ] })
2403
1929
  ]
2404
1930
  }
2405
1931
  ),
2406
- hasBody && isOpen && /* @__PURE__ */ jsx29("div", { className: cxMessage("eventBody"), children: parts.map((part, i) => /* @__PURE__ */ jsx29(SubagentChildPartRenderer, { part }, `${toolCallId}-${i}`)) })
1932
+ status.summary && isOpen && /* @__PURE__ */ jsx29("div", { className: cxMessage("eventBody"), children: /* @__PURE__ */ jsx29(Markdown, { children: status.summary }) })
2407
1933
  ]
2408
1934
  }
2409
1935
  );
2410
1936
  }
2411
- function SubagentChildPartRenderer({ part }) {
2412
- if (part.kind === "text") {
2413
- return /* @__PURE__ */ jsx29("div", { className: cxMessage("text"), children: /* @__PURE__ */ jsx29(Markdown, { children: part.text }) });
2414
- }
2415
- if (part.kind === "reasoning") {
1937
+ function ExamplePrompt({
1938
+ label,
1939
+ href,
1940
+ onClick,
1941
+ disabled
1942
+ }) {
1943
+ const content = /* @__PURE__ */ jsxs16(Fragment5, { children: [
1944
+ /* @__PURE__ */ jsx29("div", { children: label }),
1945
+ /* @__PURE__ */ jsx29("div", { className: cx8("examplePromptArrow"), children: /* @__PURE__ */ jsx29(ArrowUp, { size: "16" }) })
1946
+ ] });
1947
+ if (href) {
2416
1948
  return /* @__PURE__ */ jsx29(
2417
- ReasoningBlock,
1949
+ "a",
2418
1950
  {
2419
- part: {
2420
- type: "reasoning",
2421
- text: part.text,
2422
- state: part.state
2423
- }
1951
+ className: cx8("examplePrompt"),
1952
+ href: disabled ? void 0 : href,
1953
+ "aria-disabled": disabled || void 0,
1954
+ onClick: (e) => {
1955
+ if (disabled) {
1956
+ e.preventDefault();
1957
+ return;
1958
+ }
1959
+ onClick?.(e);
1960
+ },
1961
+ children: content
2424
1962
  }
2425
1963
  );
2426
1964
  }
2427
- if (part.toolName === "subagent") {
2428
- return /* @__PURE__ */ jsx29(SubagentBlock, { toolCallId: part.childToolCallId });
1965
+ return /* @__PURE__ */ jsx29(
1966
+ "button",
1967
+ {
1968
+ className: cx8("examplePrompt"),
1969
+ type: "button",
1970
+ disabled,
1971
+ onClick,
1972
+ children: content
1973
+ }
1974
+ );
1975
+ }
1976
+
1977
+ // src/lib/scroll-tracking-events.ts
1978
+ init_react_import();
1979
+ var listeners = /* @__PURE__ */ new Set();
1980
+ function dispatchScrollTrackingEvent(detail) {
1981
+ listeners.forEach((listener) => {
1982
+ listener(detail);
1983
+ });
1984
+ }
1985
+ function subscribeToScrollTrackingEvents(listener) {
1986
+ listeners.add(listener);
1987
+ return () => {
1988
+ listeners.delete(listener);
1989
+ };
1990
+ }
1991
+
1992
+ // src/components/DesignModeToggle/index.tsx
1993
+ init_react_import();
1994
+
1995
+ // css-module:/home/runner/work/platform/platform/packages/plugin-ai/src/components/DesignModeToggle/styles.module.css#css-module
1996
+ init_react_import();
1997
+ var styles_module_default9 = { "DesignModeToggle": "_DesignModeToggle_o5uty_1", "DesignModeToggle-button": "_DesignModeToggle-button_o5uty_8", "DesignModeToggle-button--active": "_DesignModeToggle-button--active_o5uty_28" };
1998
+
1999
+ // src/components/DesignModeToggle/index.tsx
2000
+ import { jsx as jsx30, jsxs as jsxs17 } from "react/jsx-runtime";
2001
+ var cx9 = getClassNameFactory2("DesignModeToggle", styles_module_default9);
2002
+ function DesignModeToggle({
2003
+ active,
2004
+ onToggle,
2005
+ disabled
2006
+ }) {
2007
+ return /* @__PURE__ */ jsx30("div", { className: cx9(), children: /* @__PURE__ */ jsxs17(
2008
+ "button",
2009
+ {
2010
+ className: `${cx9("button")} ${active ? cx9("button--active") : ""}`,
2011
+ onClick: onToggle,
2012
+ disabled,
2013
+ type: "button",
2014
+ title: active ? "Disable design mode" : "Enable design mode",
2015
+ children: [
2016
+ /* @__PURE__ */ jsx30(WandSparkles, { size: 12 }),
2017
+ "Design"
2018
+ ]
2019
+ }
2020
+ ) });
2021
+ }
2022
+
2023
+ // src/lib/use-puck-ai.ts
2024
+ init_react_import();
2025
+
2026
+ // ../../node_modules/.pnpm/@ai-sdk+react@3.0.232_react@19.2.8_zod@4.4.3/node_modules/@ai-sdk/react/dist/index.mjs
2027
+ init_react_import();
2028
+ var import_throttleit = __toESM(require_throttleit(), 1);
2029
+ import {
2030
+ DefaultChatTransport
2031
+ } from "ai";
2032
+ import { useCallback as useCallback2, useEffect as useEffect8, useRef as useRef7, useSyncExternalStore } from "react";
2033
+ import {
2034
+ AbstractChat
2035
+ } from "ai";
2036
+ import {
2037
+ callCompletionApi
2038
+ } from "ai";
2039
+ import { useCallback as useCallback22, useEffect as useEffect22, useId, useRef as useRef22, useState as useState12 } from "react";
2040
+ import {
2041
+ asSchema,
2042
+ isDeepEqualData,
2043
+ parsePartialJson
2044
+ } from "ai";
2045
+ import { useCallback as useCallback3, useId as useId2, useRef as useRef32, useState as useState22 } from "react";
2046
+ var __accessCheck = (obj, member, msg) => {
2047
+ if (!member.has(obj))
2048
+ throw TypeError("Cannot " + msg);
2049
+ };
2050
+ var __privateGet = (obj, member, getter) => {
2051
+ __accessCheck(obj, member, "read from private field");
2052
+ return getter ? getter.call(obj) : member.get(obj);
2053
+ };
2054
+ var __privateAdd = (obj, member, value) => {
2055
+ if (member.has(obj))
2056
+ throw TypeError("Cannot add the same private member more than once");
2057
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2058
+ };
2059
+ var __privateSet = (obj, member, value, setter) => {
2060
+ __accessCheck(obj, member, "write to private field");
2061
+ setter ? setter.call(obj, value) : member.set(obj, value);
2062
+ return value;
2063
+ };
2064
+ function throttle(fn, waitMs) {
2065
+ return waitMs != null ? (0, import_throttleit.default)(fn, waitMs) : fn;
2066
+ }
2067
+ var _messages;
2068
+ var _status;
2069
+ var _error;
2070
+ var _messagesCallbacks;
2071
+ var _statusCallbacks;
2072
+ var _errorCallbacks;
2073
+ var _callMessagesCallbacks;
2074
+ var _callStatusCallbacks;
2075
+ var _callErrorCallbacks;
2076
+ var ReactChatState = class {
2077
+ constructor(initialMessages = []) {
2078
+ __privateAdd(this, _messages, void 0);
2079
+ __privateAdd(this, _status, "ready");
2080
+ __privateAdd(this, _error, void 0);
2081
+ __privateAdd(this, _messagesCallbacks, /* @__PURE__ */ new Set());
2082
+ __privateAdd(this, _statusCallbacks, /* @__PURE__ */ new Set());
2083
+ __privateAdd(this, _errorCallbacks, /* @__PURE__ */ new Set());
2084
+ this.pushMessage = (message) => {
2085
+ __privateSet(this, _messages, __privateGet(this, _messages).concat(message));
2086
+ __privateGet(this, _callMessagesCallbacks).call(this);
2087
+ };
2088
+ this.popMessage = () => {
2089
+ __privateSet(this, _messages, __privateGet(this, _messages).slice(0, -1));
2090
+ __privateGet(this, _callMessagesCallbacks).call(this);
2091
+ };
2092
+ this.replaceMessage = (index, message) => {
2093
+ __privateSet(this, _messages, [
2094
+ ...__privateGet(this, _messages).slice(0, index),
2095
+ // We deep clone the message here to ensure the new React Compiler (currently in RC) detects deeply nested parts/metadata changes:
2096
+ this.snapshot(message),
2097
+ ...__privateGet(this, _messages).slice(index + 1)
2098
+ ]);
2099
+ __privateGet(this, _callMessagesCallbacks).call(this);
2100
+ };
2101
+ this.snapshot = (value) => structuredClone(value);
2102
+ this["~registerMessagesCallback"] = (onChange, throttleWaitMs) => {
2103
+ const callback = throttleWaitMs ? throttle(onChange, throttleWaitMs) : onChange;
2104
+ __privateGet(this, _messagesCallbacks).add(callback);
2105
+ return () => {
2106
+ __privateGet(this, _messagesCallbacks).delete(callback);
2107
+ };
2108
+ };
2109
+ this["~registerStatusCallback"] = (onChange) => {
2110
+ __privateGet(this, _statusCallbacks).add(onChange);
2111
+ return () => {
2112
+ __privateGet(this, _statusCallbacks).delete(onChange);
2113
+ };
2114
+ };
2115
+ this["~registerErrorCallback"] = (onChange) => {
2116
+ __privateGet(this, _errorCallbacks).add(onChange);
2117
+ return () => {
2118
+ __privateGet(this, _errorCallbacks).delete(onChange);
2119
+ };
2120
+ };
2121
+ __privateAdd(this, _callMessagesCallbacks, () => {
2122
+ __privateGet(this, _messagesCallbacks).forEach((callback) => callback());
2123
+ });
2124
+ __privateAdd(this, _callStatusCallbacks, () => {
2125
+ __privateGet(this, _statusCallbacks).forEach((callback) => callback());
2126
+ });
2127
+ __privateAdd(this, _callErrorCallbacks, () => {
2128
+ __privateGet(this, _errorCallbacks).forEach((callback) => callback());
2129
+ });
2130
+ __privateSet(this, _messages, initialMessages);
2131
+ }
2132
+ get status() {
2133
+ return __privateGet(this, _status);
2134
+ }
2135
+ set status(newStatus) {
2136
+ __privateSet(this, _status, newStatus);
2137
+ __privateGet(this, _callStatusCallbacks).call(this);
2138
+ }
2139
+ get error() {
2140
+ return __privateGet(this, _error);
2141
+ }
2142
+ set error(newError) {
2143
+ __privateSet(this, _error, newError);
2144
+ __privateGet(this, _callErrorCallbacks).call(this);
2145
+ }
2146
+ get messages() {
2147
+ return __privateGet(this, _messages);
2148
+ }
2149
+ set messages(newMessages) {
2150
+ __privateSet(this, _messages, [...newMessages]);
2151
+ __privateGet(this, _callMessagesCallbacks).call(this);
2152
+ }
2153
+ };
2154
+ _messages = /* @__PURE__ */ new WeakMap();
2155
+ _status = /* @__PURE__ */ new WeakMap();
2156
+ _error = /* @__PURE__ */ new WeakMap();
2157
+ _messagesCallbacks = /* @__PURE__ */ new WeakMap();
2158
+ _statusCallbacks = /* @__PURE__ */ new WeakMap();
2159
+ _errorCallbacks = /* @__PURE__ */ new WeakMap();
2160
+ _callMessagesCallbacks = /* @__PURE__ */ new WeakMap();
2161
+ _callStatusCallbacks = /* @__PURE__ */ new WeakMap();
2162
+ _callErrorCallbacks = /* @__PURE__ */ new WeakMap();
2163
+ var _state;
2164
+ var Chat = class extends AbstractChat {
2165
+ constructor({ messages, ...init }) {
2166
+ const state = new ReactChatState(messages);
2167
+ super({ ...init, state });
2168
+ __privateAdd(this, _state, void 0);
2169
+ this["~registerMessagesCallback"] = (onChange, throttleWaitMs) => __privateGet(this, _state)["~registerMessagesCallback"](onChange, throttleWaitMs);
2170
+ this["~registerStatusCallback"] = (onChange) => __privateGet(this, _state)["~registerStatusCallback"](onChange);
2171
+ this["~registerErrorCallback"] = (onChange) => __privateGet(this, _state)["~registerErrorCallback"](onChange);
2172
+ __privateSet(this, _state, state);
2173
+ }
2174
+ };
2175
+ _state = /* @__PURE__ */ new WeakMap();
2176
+ function useChat({
2177
+ experimental_throttle: throttleWaitMs,
2178
+ resume = false,
2179
+ ...options
2180
+ } = {}) {
2181
+ const latestRef = useRef7({});
2182
+ if (!("chat" in options)) {
2183
+ latestRef.current = {
2184
+ onToolCall: options.onToolCall,
2185
+ onData: options.onData,
2186
+ onFinish: options.onFinish,
2187
+ onError: options.onError,
2188
+ sendAutomaticallyWhen: options.sendAutomaticallyWhen,
2189
+ transport: options.transport
2190
+ };
2429
2191
  }
2430
- const synthesized = {
2431
- toolCallId: part.childToolCallId,
2432
- type: `tool-${part.toolName}`,
2433
- state: part.output !== void 0 ? "output-available" : "input-available",
2434
- input: part.input,
2435
- output: part.output
2192
+ let defaultTransport;
2193
+ const getTransport = () => {
2194
+ var _a;
2195
+ return (_a = latestRef.current.transport) != null ? _a : defaultTransport != null ? defaultTransport : defaultTransport = new DefaultChatTransport();
2436
2196
  };
2437
- return /* @__PURE__ */ jsx29(PuckTool, { ...synthesized });
2438
- }
2439
- function ChatEvent({
2440
- status,
2441
- icon = /* @__PURE__ */ jsx29(Check, { size: 18 })
2442
- }) {
2443
- const [isOpen, setIsOpen] = useState13(false);
2444
- return /* @__PURE__ */ jsxs16(
2445
- "details",
2446
- {
2447
- className: cxMessage("event"),
2448
- onToggle: (e) => setIsOpen(e.currentTarget.open),
2449
- children: [
2450
- /* @__PURE__ */ jsxs16(
2451
- "summary",
2452
- {
2453
- className: cxMessage("eventHeader"),
2454
- style: status.summary ? {} : { color: "var(--puck-color-grey-05) !important", cursor: "unset" },
2455
- children: [
2456
- /* @__PURE__ */ jsx29("div", { className: cxMessage("eventIcon"), children: status.error ? /* @__PURE__ */ jsx29(TriangleAlert, { size: 18 }) : status.loading ? /* @__PURE__ */ jsx29(Loader, { size: 16 }) : icon }),
2457
- /* @__PURE__ */ jsx29("div", { children: status.label }),
2458
- status.summary && /* @__PURE__ */ jsxs16(Fragment5, { children: [
2459
- /* @__PURE__ */ jsx29("div", { className: cxMessage("eventExpand"), children: /* @__PURE__ */ jsx29(Plus, { size: 12 }) }),
2460
- /* @__PURE__ */ jsx29("div", { className: cxMessage("eventCollapse"), children: /* @__PURE__ */ jsx29(Minus, { size: 12 }) })
2461
- ] })
2462
- ]
2463
- }
2464
- ),
2465
- status.summary && isOpen && /* @__PURE__ */ jsx29("div", { className: cxMessage("eventBody"), children: /* @__PURE__ */ jsx29(Markdown, { children: status.summary }) })
2466
- ]
2197
+ const chatOptions = {
2198
+ ...options,
2199
+ transport: {
2200
+ sendMessages: (sendOptions) => getTransport().sendMessages(sendOptions),
2201
+ reconnectToStream: (reconnectOptions) => getTransport().reconnectToStream(reconnectOptions)
2202
+ },
2203
+ onToolCall: (arg) => {
2204
+ var _a, _b;
2205
+ return (_b = (_a = latestRef.current).onToolCall) == null ? void 0 : _b.call(_a, arg);
2206
+ },
2207
+ onData: (arg) => {
2208
+ var _a, _b;
2209
+ return (_b = (_a = latestRef.current).onData) == null ? void 0 : _b.call(_a, arg);
2210
+ },
2211
+ onFinish: (arg) => {
2212
+ var _a, _b;
2213
+ return (_b = (_a = latestRef.current).onFinish) == null ? void 0 : _b.call(_a, arg);
2214
+ },
2215
+ onError: (arg) => {
2216
+ var _a, _b;
2217
+ return (_b = (_a = latestRef.current).onError) == null ? void 0 : _b.call(_a, arg);
2218
+ },
2219
+ sendAutomaticallyWhen: (arg) => {
2220
+ var _a, _b, _c;
2221
+ return (_c = (_b = (_a = latestRef.current).sendAutomaticallyWhen) == null ? void 0 : _b.call(_a, arg)) != null ? _c : false;
2467
2222
  }
2223
+ };
2224
+ const chatRef = useRef7(
2225
+ "chat" in options ? options.chat : new Chat(chatOptions)
2468
2226
  );
2469
- }
2470
- function ExamplePrompt({
2471
- label,
2472
- href,
2473
- onClick,
2474
- disabled
2475
- }) {
2476
- const content = /* @__PURE__ */ jsxs16(Fragment5, { children: [
2477
- /* @__PURE__ */ jsx29("div", { children: label }),
2478
- /* @__PURE__ */ jsx29("div", { className: cx8("examplePromptArrow"), children: /* @__PURE__ */ jsx29(ArrowUp, { size: "16" }) })
2479
- ] });
2480
- if (href) {
2481
- return /* @__PURE__ */ jsx29(
2482
- "a",
2483
- {
2484
- className: cx8("examplePrompt"),
2485
- href: disabled ? void 0 : href,
2486
- "aria-disabled": disabled || void 0,
2487
- onClick: (e) => {
2488
- if (disabled) {
2489
- e.preventDefault();
2490
- return;
2491
- }
2492
- onClick?.(e);
2493
- },
2494
- children: content
2495
- }
2496
- );
2227
+ const shouldRecreateChat = "chat" in options && options.chat !== chatRef.current || "id" in options && options.id != null && chatRef.current.id !== options.id;
2228
+ if (shouldRecreateChat) {
2229
+ chatRef.current = "chat" in options ? options.chat : new Chat(chatOptions);
2497
2230
  }
2498
- return /* @__PURE__ */ jsx29(
2499
- "button",
2500
- {
2501
- className: cx8("examplePrompt"),
2502
- type: "button",
2503
- disabled,
2504
- onClick,
2505
- children: content
2506
- }
2231
+ const subscribeToMessages = useCallback2(
2232
+ (update) => chatRef.current["~registerMessagesCallback"](update, throttleWaitMs),
2233
+ // `chatRef.current.id` is required to trigger re-subscription when the chat ID changes
2234
+ // eslint-disable-next-line react-hooks/exhaustive-deps
2235
+ [throttleWaitMs, chatRef.current.id]
2236
+ );
2237
+ const messages = useSyncExternalStore(
2238
+ subscribeToMessages,
2239
+ () => chatRef.current.messages,
2240
+ () => chatRef.current.messages
2241
+ );
2242
+ const status = useSyncExternalStore(
2243
+ chatRef.current["~registerStatusCallback"],
2244
+ () => chatRef.current.status,
2245
+ () => chatRef.current.status
2507
2246
  );
2247
+ const error = useSyncExternalStore(
2248
+ chatRef.current["~registerErrorCallback"],
2249
+ () => chatRef.current.error,
2250
+ () => chatRef.current.error
2251
+ );
2252
+ const setMessages = useCallback2(
2253
+ (messagesParam) => {
2254
+ if (typeof messagesParam === "function") {
2255
+ messagesParam = messagesParam(chatRef.current.messages);
2256
+ }
2257
+ chatRef.current.messages = messagesParam;
2258
+ },
2259
+ [chatRef]
2260
+ );
2261
+ useEffect8(() => {
2262
+ if (resume) {
2263
+ chatRef.current.resumeStream();
2264
+ }
2265
+ }, [resume, chatRef]);
2266
+ return {
2267
+ id: chatRef.current.id,
2268
+ messages,
2269
+ setMessages,
2270
+ sendMessage: chatRef.current.sendMessage,
2271
+ regenerate: chatRef.current.regenerate,
2272
+ clearError: chatRef.current.clearError,
2273
+ stop: chatRef.current.stop,
2274
+ error,
2275
+ resumeStream: chatRef.current.resumeStream,
2276
+ status,
2277
+ /**
2278
+ * @deprecated Use `addToolOutput` instead.
2279
+ */
2280
+ addToolResult: chatRef.current.addToolOutput,
2281
+ addToolOutput: chatRef.current.addToolOutput,
2282
+ addToolApprovalResponse: chatRef.current.addToolApprovalResponse
2283
+ };
2508
2284
  }
2509
2285
 
2510
- // src/components/Chat/index.tsx
2511
- var import_reducer = __toESM(require_dist());
2286
+ // src/lib/use-puck-ai.ts
2287
+ import {
2288
+ createUsePuck,
2289
+ useGetPuck as useGetPuck4
2290
+ } from "@puckeditor/core";
2291
+ import {
2292
+ DefaultChatTransport as DefaultChatTransport2
2293
+ } from "ai";
2294
+ import { useCallback as useCallback5, useEffect as useEffect12, useRef as useRef11, useState as useState15 } from "react";
2295
+ import { ulid } from "ulid";
2512
2296
  import qler from "qler";
2513
2297
  import html2canvas from "html2canvas-pro";
2514
2298
  import { useDebouncedCallback } from "use-debounce";
2515
2299
 
2516
- // src/lib/scroll-tracking-events.ts
2300
+ // ../reducer/index.ts
2517
2301
  init_react_import();
2518
- var listeners = /* @__PURE__ */ new Set();
2519
- function dispatchScrollTrackingEvent(detail) {
2520
- listeners.forEach((listener) => {
2521
- listener(detail);
2522
- });
2523
- }
2524
- function subscribeToScrollTrackingEvents(listener) {
2525
- listeners.add(listener);
2526
- return () => {
2527
- listeners.delete(listener);
2302
+ import { createReducer } from "@puckeditor/core/internal";
2303
+ var parseAppendPath = (path) => {
2304
+ const segments = [];
2305
+ const pattern = /([^.[\]]+)|\[(\d+)\]/g;
2306
+ let match;
2307
+ while ((match = pattern.exec(path)) !== null) {
2308
+ segments.push(match[2] !== void 0 ? Number(match[2]) : match[1]);
2309
+ }
2310
+ return segments;
2311
+ };
2312
+ var appendAtPath = (base, segments, tail) => {
2313
+ if (segments.length === 0) {
2314
+ return `${typeof base === "string" ? base : ""}${tail}`;
2315
+ }
2316
+ const [head, ...rest] = segments;
2317
+ if (typeof head === "number") {
2318
+ const arr = Array.isArray(base) ? [...base] : [];
2319
+ arr[head] = appendAtPath(arr[head], rest, tail);
2320
+ return arr;
2321
+ }
2322
+ const obj = typeof base === "object" && base !== null && !Array.isArray(base) ? { ...base } : {};
2323
+ obj[head] = appendAtPath(obj[head], rest, tail);
2324
+ return obj;
2325
+ };
2326
+ var resolveAppends = (existingProps, props, appends) => {
2327
+ if (!appends) return props;
2328
+ const resolved = { ...props };
2329
+ for (const [path, tail] of Object.entries(appends)) {
2330
+ const [rootKey, ...rest] = parseAppendPath(path);
2331
+ if (typeof rootKey !== "string") continue;
2332
+ const base = rootKey in resolved ? resolved[rootKey] : existingProps?.[rootKey];
2333
+ resolved[rootKey] = appendAtPath(base, rest, tail);
2334
+ }
2335
+ return resolved;
2336
+ };
2337
+ var getSelectorForId = (state, id) => {
2338
+ const node = state.indexes.nodes[id];
2339
+ if (!node) return;
2340
+ const zoneCompound = `${node.parentId}:${node.zone}`;
2341
+ const zone = state.indexes.zones[zoneCompound];
2342
+ if (!zone) return;
2343
+ const index = zone.contentIds.indexOf(id);
2344
+ return { zone: zoneCompound, index };
2345
+ };
2346
+ var getItemById = (state, id) => state.indexes.nodes[id]?.data;
2347
+ var applyArrayDefaults = (oldProps, newProps, fields) => {
2348
+ const updatedProps = {
2349
+ ...oldProps,
2350
+ ...newProps
2528
2351
  };
2529
- }
2530
-
2531
- // src/components/DesignModeToggle/index.tsx
2532
- init_react_import();
2533
-
2534
- // css-module:/home/runner/work/platform/platform/packages/plugin-ai/src/components/DesignModeToggle/styles.module.css#css-module
2535
- init_react_import();
2536
- var styles_module_default9 = { "DesignModeToggle": "_DesignModeToggle_o5uty_1", "DesignModeToggle-button": "_DesignModeToggle-button_o5uty_8", "DesignModeToggle-button--active": "_DesignModeToggle-button--active_o5uty_28" };
2537
-
2538
- // src/components/DesignModeToggle/index.tsx
2539
- import { jsx as jsx30, jsxs as jsxs17 } from "react/jsx-runtime";
2540
- var cx9 = getClassNameFactory2("DesignModeToggle", styles_module_default9);
2541
- function DesignModeToggle({
2542
- active,
2543
- onToggle,
2544
- disabled
2545
- }) {
2546
- return /* @__PURE__ */ jsx30("div", { className: cx9(), children: /* @__PURE__ */ jsxs17(
2547
- "button",
2548
- {
2549
- className: `${cx9("button")} ${active ? cx9("button--active") : ""}`,
2550
- onClick: onToggle,
2551
- disabled,
2552
- type: "button",
2553
- title: active ? "Disable design mode" : "Enable design mode",
2554
- children: [
2555
- /* @__PURE__ */ jsx30(WandSparkles, { size: 12 }),
2556
- "Design"
2557
- ]
2352
+ for (const fieldName in fields) {
2353
+ const field = fields[fieldName];
2354
+ if (field.type === "array") {
2355
+ const arrayField = field;
2356
+ const arrayFields = arrayField.arrayFields;
2357
+ const value = updatedProps[fieldName];
2358
+ if (value === void 0) continue;
2359
+ if (!Array.isArray(value)) {
2360
+ const oldValue = oldProps[fieldName];
2361
+ if (Array.isArray(oldValue)) {
2362
+ updatedProps[fieldName] = oldValue;
2363
+ } else {
2364
+ delete updatedProps[fieldName];
2365
+ }
2366
+ continue;
2367
+ }
2368
+ updatedProps[fieldName] = value.map(
2369
+ (item, index) => {
2370
+ const newItem = {};
2371
+ const defaultValue = typeof arrayField.defaultItemProps === "function" ? arrayField.defaultItemProps(index) : arrayField.defaultItemProps;
2372
+ for (const arrayFieldName in arrayFields) {
2373
+ const subField = arrayFields[arrayFieldName];
2374
+ if (subField.type === "slot") {
2375
+ newItem[arrayFieldName] = item[arrayFieldName] ?? oldProps[fieldName]?.[index]?.[arrayFieldName] ?? defaultValue?.[arrayFieldName];
2376
+ } else {
2377
+ newItem[arrayFieldName] = item[arrayFieldName] ?? defaultValue?.[arrayFieldName];
2378
+ }
2379
+ }
2380
+ return newItem;
2381
+ }
2382
+ );
2383
+ }
2384
+ }
2385
+ return updatedProps;
2386
+ };
2387
+ var dispatchOp = (operation, {
2388
+ getState,
2389
+ dispatchAction,
2390
+ config
2391
+ }) => {
2392
+ const state = getState();
2393
+ try {
2394
+ if (operation.op === "add") {
2395
+ if (operation.zone) {
2396
+ dispatchAction({
2397
+ type: "insert",
2398
+ destinationIndex: operation.index,
2399
+ destinationZone: operation.zone,
2400
+ componentType: operation.type,
2401
+ id: operation.id,
2402
+ recordHistory: false
2403
+ });
2404
+ const existing = getItemById(getState(), operation.id);
2405
+ if (!existing) {
2406
+ throw new Error(
2407
+ `Tried to update an item that doesn't exist: ${operation.id}`
2408
+ );
2409
+ }
2410
+ const newData = {
2411
+ ...existing,
2412
+ props: applyArrayDefaults(
2413
+ existing.props,
2414
+ operation.props,
2415
+ config.components[existing.type].fields
2416
+ )
2417
+ };
2418
+ newData.props.id ||= operation.id;
2419
+ const selector = getSelectorForId(getState(), operation.id);
2420
+ if (!selector) {
2421
+ throw new Error(
2422
+ `Tried to replace an item that doesn't exist: ${operation.id}`
2423
+ );
2424
+ }
2425
+ dispatchAction({
2426
+ type: "replace",
2427
+ destinationIndex: selector.index,
2428
+ destinationZone: selector.zone,
2429
+ data: newData,
2430
+ recordHistory: false
2431
+ });
2432
+ }
2433
+ } else if (operation.op === "update") {
2434
+ const selector = getSelectorForId(state, operation.id);
2435
+ const existing = getItemById(state, operation.id);
2436
+ if (!selector || !existing) {
2437
+ throw new Error(
2438
+ `Tried to update an item that doesn't exist: ${operation.id}`
2439
+ );
2440
+ }
2441
+ const newData = {
2442
+ ...existing,
2443
+ props: applyArrayDefaults(
2444
+ existing.props,
2445
+ resolveAppends(
2446
+ existing.props,
2447
+ operation.props,
2448
+ operation.appends
2449
+ ),
2450
+ config.components[existing.type].fields
2451
+ )
2452
+ };
2453
+ dispatchAction({
2454
+ type: "replace",
2455
+ destinationIndex: selector.index,
2456
+ destinationZone: selector.zone,
2457
+ data: newData,
2458
+ recordHistory: false
2459
+ });
2460
+ } else if (operation.op === "updateRoot") {
2461
+ const existing = state.data.root;
2462
+ const defaultProps = config.root?.defaultProps ?? {};
2463
+ dispatchAction({
2464
+ type: "replaceRoot",
2465
+ root: {
2466
+ ...existing,
2467
+ props: {
2468
+ ...defaultProps,
2469
+ ...existing.props,
2470
+ ...resolveAppends(
2471
+ existing.props ?? {},
2472
+ operation.props,
2473
+ operation.appends
2474
+ )
2475
+ }
2476
+ },
2477
+ recordHistory: false
2478
+ });
2479
+ } else if (operation.op === "delete") {
2480
+ const selector = getSelectorForId(state, operation.id);
2481
+ if (selector) {
2482
+ dispatchAction({
2483
+ type: "remove",
2484
+ zone: selector.zone,
2485
+ index: selector.index,
2486
+ recordHistory: false
2487
+ });
2488
+ }
2489
+ } else if (operation.op === "duplicate") {
2490
+ const selector = getSelectorForId(state, operation.id);
2491
+ if (!selector) {
2492
+ throw new Error(
2493
+ `Tried to duplicate an item that doesn't exist: ${operation.id}`
2494
+ );
2495
+ }
2496
+ dispatchAction({
2497
+ type: "duplicate",
2498
+ sourceZone: selector.zone,
2499
+ sourceIndex: selector.index,
2500
+ recordHistory: false
2501
+ });
2502
+ } else if (operation.op === "move") {
2503
+ const selector = getSelectorForId(state, operation.id);
2504
+ if (!selector) {
2505
+ throw new Error(
2506
+ `Tried to move an item that doesn't exist: ${operation.id}`
2507
+ );
2508
+ }
2509
+ dispatchAction({
2510
+ type: "move",
2511
+ sourceZone: selector.zone,
2512
+ sourceIndex: selector.index,
2513
+ destinationIndex: operation.index,
2514
+ destinationZone: operation.zone,
2515
+ recordHistory: false
2516
+ });
2517
+ } else if (operation.op === "reset") {
2518
+ const defaultRootProps = config.root?.defaultProps ?? {};
2519
+ dispatchAction({
2520
+ type: "setData",
2521
+ data: { content: [], root: defaultRootProps },
2522
+ recordHistory: false
2523
+ });
2524
+ } else {
2525
+ throw new Error(`Unknown operation: ${operation.op}`);
2558
2526
  }
2559
- ) });
2560
- }
2527
+ } catch (e) {
2528
+ console.error("Error applying operation, skipping...", operation, e);
2529
+ }
2530
+ };
2561
2531
 
2562
2532
  // src/lib/design/runtime.tsx
2563
2533
  init_react_import();
@@ -2571,12 +2541,12 @@ import {
2571
2541
  useGetPuck as useGetPuck2
2572
2542
  } from "@puckeditor/core";
2573
2543
  import {
2574
- useCallback as useCallback5,
2575
- useEffect as useEffect11,
2544
+ useCallback as useCallback4,
2545
+ useEffect as useEffect10,
2576
2546
  useLayoutEffect,
2577
2547
  useMemo as useMemo5,
2578
- useRef as useRef11,
2579
- useState as useState15,
2548
+ useRef as useRef9,
2549
+ useState as useState14,
2580
2550
  useSyncExternalStore as useSyncExternalStore2
2581
2551
  } from "react";
2582
2552
 
@@ -3476,9 +3446,9 @@ var attachInlineEditing = (el, {
3476
3446
  nextValue = parsed;
3477
3447
  lastValidNumberText = String(parsed);
3478
3448
  }
3479
- const { dispatch, getSelectorForId, getItemById, resolveDataById } = getPuck();
3480
- const selector = getSelectorForId(componentId);
3481
- const item = getItemById(componentId);
3449
+ const { dispatch, getSelectorForId: getSelectorForId2, getItemById: getItemById2, resolveDataById } = getPuck();
3450
+ const selector = getSelectorForId2(componentId);
3451
+ const item = getItemById2(componentId);
3482
3452
  if (!selector || !item) return;
3483
3453
  dispatch({
3484
3454
  type: "replace",
@@ -3491,8 +3461,8 @@ var attachInlineEditing = (el, {
3491
3461
  const handleClick = (e) => {
3492
3462
  e.preventDefault();
3493
3463
  e.stopPropagation();
3494
- const { getSelectorForId, dispatch } = getPuck();
3495
- const itemSelector = getSelectorForId(componentId);
3464
+ const { getSelectorForId: getSelectorForId2, dispatch } = getPuck();
3465
+ const itemSelector = getSelectorForId2(componentId);
3496
3466
  if (itemSelector) {
3497
3467
  dispatch({ type: "setUi", ui: { itemSelector } });
3498
3468
  }
@@ -3720,7 +3690,7 @@ var htmlToReactTree = (html, slots) => {
3720
3690
 
3721
3691
  // src/lib/design/slot-portal.tsx
3722
3692
  init_react_import();
3723
- import { useEffect as useEffect10, useMemo as useMemo4, useRef as useRef10, useState as useState14 } from "react";
3693
+ import { useEffect as useEffect9, useMemo as useMemo4, useRef as useRef8, useState as useState13 } from "react";
3724
3694
  import { createPortal } from "react-dom";
3725
3695
  import { jsx as jsx31 } from "react/jsx-runtime";
3726
3696
  var parseInlineStyle = (cssText) => {
@@ -3744,13 +3714,13 @@ var SlotPortal = ({
3744
3714
  slotClassName,
3745
3715
  SlotContent
3746
3716
  }) => {
3747
- const [target, setTarget] = useState14(null);
3748
- const lastTarget = useRef10(null);
3717
+ const [target, setTarget] = useState13(null);
3718
+ const lastTarget = useRef8(null);
3749
3719
  const style = useMemo4(
3750
3720
  () => slotStyle ? parseInlineStyle(slotStyle) : void 0,
3751
3721
  [slotStyle]
3752
3722
  );
3753
- useEffect10(() => {
3723
+ useEffect9(() => {
3754
3724
  const el = entry.querySelector(`[data-puck-slot="${cssEscape2(slotName)}"]`);
3755
3725
  if (el !== lastTarget.current) {
3756
3726
  el?.replaceChildren();
@@ -3867,7 +3837,7 @@ function createDesignComponentConfig(registration) {
3867
3837
  style,
3868
3838
  ...props
3869
3839
  }) {
3870
- const getSnapshot = useCallback5(
3840
+ const getSnapshot = useCallback4(
3871
3841
  () => registrationStore.get(name) ?? registration,
3872
3842
  []
3873
3843
  );
@@ -3879,8 +3849,8 @@ function createDesignComponentConfig(registration) {
3879
3849
  const html = reg.html ?? "";
3880
3850
  const styles = reg.styles;
3881
3851
  const script = reg.script;
3882
- const [entryEl, setEntryEl] = useState15(null);
3883
- const scriptRef = useRef11(null);
3852
+ const [entryEl, setEntryEl] = useState14(null);
3853
+ const scriptRef = useRef9(null);
3884
3854
  const annotations = useMemo5(() => getAnnotations(html), [html]);
3885
3855
  const { attrFields, arrayFields, attrSig, arraySig } = useMemo5(() => {
3886
3856
  const attr = [];
@@ -3923,12 +3893,12 @@ function createDesignComponentConfig(registration) {
3923
3893
  () => puck.isEditing ? /* @__PURE__ */ jsx32("div", { ref: setEntryEl }) : null,
3924
3894
  [puck.isEditing]
3925
3895
  );
3926
- useEffect11(() => {
3896
+ useEffect10(() => {
3927
3897
  if (!puck.isEditing || !getPuck) return;
3928
3898
  getPuck().resolveDataById(id, "force");
3929
3899
  }, [reg, puck.isEditing, getPuck, id]);
3930
- const fieldWiring = useRef11(/* @__PURE__ */ new Map());
3931
- const morphed = useRef11(null);
3900
+ const fieldWiring = useRef9(/* @__PURE__ */ new Map());
3901
+ const morphed = useRef9(null);
3932
3902
  useLayoutEffect(() => {
3933
3903
  if (!puck.isEditing || !entryEl) return;
3934
3904
  if (morphed.current?.el !== entryEl || morphed.current?.html !== html || morphed.current?.attrSig !== attrSig) {
@@ -3946,14 +3916,14 @@ function createDesignComponentConfig(registration) {
3946
3916
  });
3947
3917
  }
3948
3918
  });
3949
- useEffect11(
3919
+ useEffect10(
3950
3920
  () => () => {
3951
3921
  fieldWiring.current.forEach((cleanup) => cleanup());
3952
3922
  fieldWiring.current.clear();
3953
3923
  },
3954
3924
  []
3955
3925
  );
3956
- useEffect11(() => {
3926
+ useEffect10(() => {
3957
3927
  if (!entryEl || !puck.isEditing) return;
3958
3928
  for (const attr of Array.from(entryEl.attributes)) {
3959
3929
  if ((attr.name === "data-puck-design" || attr.name.startsWith("data-puck-field-value-")) && !(attr.name in fieldValueAttrs)) {
@@ -3966,10 +3936,10 @@ function createDesignComponentConfig(registration) {
3966
3936
  }
3967
3937
  }
3968
3938
  }, [entryEl, fieldValueAttrs]);
3969
- const appliedArrayHtml = useRef11(/* @__PURE__ */ new WeakMap());
3970
- const arrayItemWiring = useRef11({});
3971
- const appliedArrays = useRef11(null);
3972
- useEffect11(() => {
3939
+ const appliedArrayHtml = useRef9(/* @__PURE__ */ new WeakMap());
3940
+ const arrayItemWiring = useRef9({});
3941
+ const appliedArrays = useRef9(null);
3942
+ useEffect10(() => {
3973
3943
  if (!puck.isEditing || !entryEl || !getPuck) return;
3974
3944
  if (appliedArrays.current?.el === entryEl && appliedArrays.current?.html === html && appliedArrays.current?.sig === arraySig) {
3975
3945
  return;
@@ -4021,7 +3991,7 @@ function createDesignComponentConfig(registration) {
4021
3991
  id,
4022
3992
  getPuck
4023
3993
  ]);
4024
- useEffect11(
3994
+ useEffect10(
4025
3995
  () => () => {
4026
3996
  Object.values(arrayItemWiring.current).forEach(
4027
3997
  (wiring) => wiring.forEach(({ cleanup }) => cleanup())
@@ -4029,7 +3999,7 @@ function createDesignComponentConfig(registration) {
4029
3999
  },
4030
4000
  []
4031
4001
  );
4032
- useEffect11(() => {
4002
+ useEffect10(() => {
4033
4003
  if (!script || !entryEl) return;
4034
4004
  scriptRef.current?.remove();
4035
4005
  const doc = entryEl.ownerDocument;
@@ -4084,7 +4054,7 @@ function createDesignComponentConfig(registration) {
4084
4054
 
4085
4055
  // src/lib/design/globals.tsx
4086
4056
  init_react_import();
4087
- import { useEffect as useEffect12, useRef as useRef12 } from "react";
4057
+ import { useEffect as useEffect11, useRef as useRef10 } from "react";
4088
4058
  import { Fragment as Fragment8, jsx as jsx33, jsxs as jsxs19 } from "react/jsx-runtime";
4089
4059
  function getDynamicConfigGlobals(dynamicConfig) {
4090
4060
  if (typeof dynamicConfig !== "object" || dynamicConfig === null) return {};
@@ -4098,9 +4068,9 @@ function DesignGlobals({
4098
4068
  styles,
4099
4069
  script
4100
4070
  }) {
4101
- const scriptRef = useRef12(null);
4102
- const hostRef = useRef12(null);
4103
- useEffect12(() => {
4071
+ const scriptRef = useRef10(null);
4072
+ const hostRef = useRef10(null);
4073
+ useEffect11(() => {
4104
4074
  if (!script) return;
4105
4075
  scriptRef.current?.remove();
4106
4076
  const doc = hostRef.current?.ownerDocument ?? document;
@@ -4400,85 +4370,68 @@ var waitForIframeReady = async (root, imageTimeout = 1e4) => {
4400
4370
  await waitForNextPaint(document2);
4401
4371
  };
4402
4372
 
4403
- // src/components/Chat/index.tsx
4404
- import { Fragment as Fragment9, jsx as jsx35, jsxs as jsxs20 } from "react/jsx-runtime";
4373
+ // ../utils/lib/iterate-sse.ts
4374
+ init_react_import();
4375
+ async function* iterateSSE(body) {
4376
+ const reader = body.getReader();
4377
+ const dec = new TextDecoder();
4378
+ let buf = "";
4379
+ try {
4380
+ while (true) {
4381
+ const { done, value } = await reader.read();
4382
+ if (done) break;
4383
+ buf += dec.decode(value, { stream: true });
4384
+ let idx;
4385
+ while ((idx = buf.indexOf("\n\n")) >= 0) {
4386
+ const chunk = buf.slice(0, idx).trim();
4387
+ buf = buf.slice(idx + 2);
4388
+ if (!chunk) continue;
4389
+ const line = chunk.startsWith("data: ") ? chunk.slice(6) : chunk;
4390
+ try {
4391
+ yield JSON.parse(line);
4392
+ } catch {
4393
+ }
4394
+ }
4395
+ }
4396
+ } finally {
4397
+ reader.cancel().catch(() => {
4398
+ });
4399
+ reader.releaseLock();
4400
+ }
4401
+ }
4402
+
4403
+ // src/lib/use-puck-ai.ts
4405
4404
  var q = qler();
4405
+ var usePuck = createUsePuck();
4406
4406
  var DEFAULT_API_VERSION = "v2";
4407
4407
  var BUILD_OP_DEBOUNCE_MS = 1e3 / 60;
4408
- var PLUGIN_AI_VERSION = true ? "0.8.2" : "unknown";
4409
- var BENCHMARK = false;
4408
+ var PLUGIN_AI_VERSION = true ? "0.9.0-canary.50fad349" : "unknown";
4410
4409
  var prefixedUlid = (prefix = "") => `${prefix ? `${prefix}_` : ""}${ulid()}`;
4411
- var getClassName18 = getClassNameFactory("Chat", styles_module_default);
4412
- var usePuck = createUsePuck();
4413
- function Chat2(props) {
4414
- const {
4415
- apiVersion = DEFAULT_API_VERSION,
4416
- chat,
4417
- designMode = false,
4418
- defaultMode = "assembly",
4419
- host = "/api/puck/chat",
4420
- prepareRequest,
4421
- scrollTrackingId
4422
- } = props;
4423
- const {
4424
- attachments,
4425
- examplePrompts,
4426
- actions: chatActions,
4427
- placeholder
4428
- } = chat ?? {};
4410
+ function usePuckAi({
4411
+ host = "/api/puck/chat",
4412
+ streamHost = "/api/puck/stream",
4413
+ mode = "assembly",
4414
+ apiVersion = DEFAULT_API_VERSION,
4415
+ prepareRequest,
4416
+ onFinish,
4417
+ onError
4418
+ } = {}) {
4429
4419
  const puckDispatch = usePuck((s) => s.dispatch);
4430
4420
  const getPuck = useGetPuck4();
4431
- const localChatId = useRef13("");
4432
- const inputRef = useRef13(null);
4433
- const pluginRef = useRef13(null);
4434
- const [mode, setMode] = useState16(defaultMode);
4435
- const modeRef = useRef13(mode);
4436
- const designModeVisible = typeof designMode === "boolean" ? designMode : designMode.visible ?? false;
4437
- useEffect13(() => {
4421
+ const localChatId = useRef11("");
4422
+ const pendingBuildOpsRef = useRef11([]);
4423
+ const [error, setError] = useState15();
4424
+ const [toolStatus, setToolStatus] = useState15({});
4425
+ const [subagentState, setSubagentState] = useState15({});
4426
+ const modeRef = useRef11(mode);
4427
+ useEffect12(() => {
4438
4428
  modeRef.current = mode;
4439
4429
  }, [mode]);
4440
4430
  const puckData = usePuck((s) => s.appState.data);
4441
- useEffect13(() => {
4431
+ useEffect12(() => {
4442
4432
  syncDesignComponents(getPuck);
4443
4433
  }, [puckData, getPuck]);
4444
- const [error, setError] = useState16();
4445
- const [userError, setUserError] = useState16();
4446
- const [composerAttachments, setComposerAttachments] = useState16([]);
4447
- const removedAttachmentClientIdsRef = useRef13(/* @__PURE__ */ new Set());
4448
- const uploadControllersRef = useRef13(/* @__PURE__ */ new Map());
4449
- const pendingBuildOpsRef = useRef13([]);
4450
- const [toolStatus, setToolStatus] = useState16({});
4451
- const [subagentState, setSubagentState] = useState16({});
4452
- const attachmentConfig = useMemo6(
4453
- () => ({
4454
- accept: attachments?.accept ?? defaultAttachmentAccept,
4455
- enabled: attachments?.enabled ?? true,
4456
- endpoint: `${host.replace(/\/$/, "")}/attachments`,
4457
- maxFiles: attachments?.maxFiles ?? defaultAttachmentConfig.maxFiles,
4458
- maxSizeBytes: attachments?.maxSizeBytes ?? defaultAttachmentConfig.maxSizeBytes
4459
- }),
4460
- [attachments, host]
4461
- );
4462
- useEffect13(
4463
- () => () => {
4464
- uploadControllersRef.current.forEach((controller) => controller.abort());
4465
- uploadControllersRef.current.clear();
4466
- },
4467
- []
4468
- );
4469
- const deleteAttachment = useCallback6(
4470
- async (attachmentId) => {
4471
- try {
4472
- await fetch(`${attachmentConfig.endpoint}/${attachmentId}`, {
4473
- method: "DELETE"
4474
- });
4475
- } catch (e) {
4476
- console.error(e);
4477
- }
4478
- },
4479
- [attachmentConfig.endpoint]
4480
- );
4481
- const uploadScreenshot = useCallback6(
4434
+ const uploadScreenshot = useCallback5(
4482
4435
  async (width, bucketUrl) => {
4483
4436
  try {
4484
4437
  const iframeDocument = document?.getElementById("preview-frame")?.contentDocument?.documentElement ?? null;
@@ -4527,7 +4480,7 @@ function Chat2(props) {
4527
4480
  nextFrame(() => {
4528
4481
  const { dispatch, config, resolveDataById } = getPuck();
4529
4482
  operations.forEach((queuedOperation) => {
4530
- (0, import_reducer.dispatchOp)(queuedOperation, {
4483
+ dispatchOp(queuedOperation, {
4531
4484
  getState: () => {
4532
4485
  const { __private } = getPuck();
4533
4486
  return __private.appState;
@@ -4550,15 +4503,18 @@ function Chat2(props) {
4550
4503
  BUILD_OP_DEBOUNCE_MS,
4551
4504
  { maxWait: BUILD_OP_DEBOUNCE_MS }
4552
4505
  );
4553
- const queueBuildOp = useCallback6(
4506
+ const queueBuildOp = useCallback5(
4554
4507
  (operation) => {
4555
4508
  pendingBuildOpsRef.current.push(operation);
4556
4509
  debouncedFlushBuildOps();
4557
4510
  },
4558
4511
  [debouncedFlushBuildOps]
4559
4512
  );
4560
- const processData = useCallback6(
4513
+ const processData = useCallback5(
4561
4514
  (dataPart) => {
4515
+ if (dataPart.type.indexOf("data-") !== 0) {
4516
+ return;
4517
+ }
4562
4518
  switch (dataPart.type) {
4563
4519
  case "data-new-chat-created": {
4564
4520
  localChatId.current = dataPart.data.chatId;
@@ -4676,6 +4632,9 @@ function Chat2(props) {
4676
4632
  debouncedFlushBuildOps.flush();
4677
4633
  return;
4678
4634
  }
4635
+ case "data-page": {
4636
+ return;
4637
+ }
4679
4638
  case "data-version-notice": {
4680
4639
  console.warn(dataPart.data.message);
4681
4640
  return;
@@ -4693,32 +4652,54 @@ function Chat2(props) {
4693
4652
  uploadScreenshot
4694
4653
  ]
4695
4654
  );
4696
- const { messages, status, sendMessage, regenerate, setMessages, stop } = useChat({
4655
+ const getRequestConfig = useCallback5(() => {
4656
+ const { config, appState } = getPuck();
4657
+ const root = config.root ?? {
4658
+ fields: {
4659
+ title: {
4660
+ type: "text",
4661
+ ai: { instructions: "The title for the page" }
4662
+ }
4663
+ }
4664
+ };
4665
+ return {
4666
+ ...config,
4667
+ root,
4668
+ components: {
4669
+ ...config.components,
4670
+ ...getRequestComponentConfigs(appState.data)
4671
+ }
4672
+ };
4673
+ }, [getPuck]);
4674
+ const settle = useCallback5(
4675
+ async ({ isAbort } = {}) => {
4676
+ debouncedFlushBuildOps.flush();
4677
+ await q.wait();
4678
+ if (!isAbort) {
4679
+ puckDispatch({
4680
+ type: "set",
4681
+ state: getPuck().appState,
4682
+ recordHistory: true
4683
+ });
4684
+ }
4685
+ },
4686
+ [debouncedFlushBuildOps, getPuck, puckDispatch]
4687
+ );
4688
+ const {
4689
+ messages,
4690
+ status: chatStatus,
4691
+ sendMessage: chatSendMessage,
4692
+ regenerate,
4693
+ setMessages,
4694
+ stop
4695
+ } = useChat({
4697
4696
  generateId: () => prefixedUlid("msg"),
4698
4697
  messages: [],
4699
4698
  transport: new DefaultChatTransport2({
4700
4699
  api: host,
4701
4700
  prepareSendMessagesRequest: async (opts) => {
4702
- const { config, appState } = getPuck();
4703
- if (BENCHMARK) {
4704
- console.time("chat");
4705
- }
4706
- const root = config.root ?? {
4707
- fields: {
4708
- title: {
4709
- type: "text",
4710
- ai: { instructions: "The title for the page" }
4711
- }
4712
- }
4713
- };
4714
- const configWithRoot = {
4715
- ...config,
4716
- root,
4717
- components: {
4718
- ...config.components,
4719
- ...getRequestComponentConfigs(appState.data)
4720
- }
4721
- };
4701
+ const { appState } = getPuck();
4702
+ const configWithRoot = getRequestConfig();
4722
4703
  const defaultOptions = {
4723
4704
  headers: {
4724
4705
  ...opts.headers,
@@ -4735,56 +4716,340 @@ function Chat2(props) {
4735
4716
  config: configWithRoot,
4736
4717
  mode: modeRef.current
4737
4718
  }
4738
- };
4739
- if (prepareRequest) {
4740
- const userOptions = await prepareRequest(defaultOptions);
4741
- return {
4742
- headers: {
4743
- ...defaultOptions.headers,
4744
- ...userOptions.headers
4745
- },
4746
- credentials: userOptions.credentials ?? defaultOptions.credentials,
4747
- body: {
4748
- ...defaultOptions.body,
4749
- ...userOptions.body
4750
- }
4751
- };
4752
- }
4753
- return defaultOptions;
4719
+ };
4720
+ if (prepareRequest) {
4721
+ const userOptions = await prepareRequest(defaultOptions);
4722
+ return {
4723
+ headers: {
4724
+ ...defaultOptions.headers,
4725
+ ...userOptions.headers
4726
+ },
4727
+ credentials: userOptions.credentials ?? defaultOptions.credentials,
4728
+ body: {
4729
+ ...defaultOptions.body,
4730
+ ...userOptions.body
4731
+ }
4732
+ };
4733
+ }
4734
+ return defaultOptions;
4735
+ }
4736
+ }),
4737
+ onData: processData,
4738
+ onError: (e) => {
4739
+ console.error(e);
4740
+ setError(e.message);
4741
+ onError?.(e);
4742
+ },
4743
+ onFinish: (options) => {
4744
+ settle(options).then(() => onFinish?.(options));
4745
+ }
4746
+ });
4747
+ const sendMessage = useCallback5(
4748
+ async (prompt, opts = {}) => {
4749
+ const text = prompt.trim();
4750
+ const files = opts.files ?? [];
4751
+ if (!text && files.length === 0) return;
4752
+ if (opts.mode) modeRef.current = opts.mode;
4753
+ setError(void 0);
4754
+ await chatSendMessage({
4755
+ role: "user",
4756
+ parts: [...text ? [{ type: "text", text }] : [], ...files]
4757
+ });
4758
+ },
4759
+ [chatSendMessage]
4760
+ );
4761
+ const [isStreaming, setIsStreaming] = useState15(false);
4762
+ const streamAbortRef = useRef11(null);
4763
+ const stream = useCallback5(
4764
+ async (prompt, opts = {}) => {
4765
+ const text = prompt.trim();
4766
+ if (!text) return;
4767
+ streamAbortRef.current?.abort();
4768
+ const controller = new AbortController();
4769
+ streamAbortRef.current = controller;
4770
+ setError(void 0);
4771
+ setIsStreaming(true);
4772
+ try {
4773
+ const { appState } = getPuck();
4774
+ const response = await fetch(streamHost, {
4775
+ method: "POST",
4776
+ headers: {
4777
+ "Content-Type": "application/json",
4778
+ "puck-api-version": apiVersion,
4779
+ "x-puck-plugin-ai-version": PLUGIN_AI_VERSION
4780
+ },
4781
+ body: JSON.stringify({
4782
+ prompt: text,
4783
+ config: getRequestConfig(),
4784
+ pageData: appState.data,
4785
+ mode: opts.mode ?? modeRef.current,
4786
+ context: opts.context
4787
+ }),
4788
+ signal: controller.signal
4789
+ });
4790
+ if (!response.ok || !response.body) {
4791
+ throw new Error(
4792
+ `Puck AI request failed: ${response.status} ${response.statusText}`
4793
+ );
4794
+ }
4795
+ for await (const part of iterateSSE(response.body)) {
4796
+ if (controller.signal.aborted) return;
4797
+ if (part.type === "error") throw new Error(part.errorText);
4798
+ processData(part);
4799
+ }
4800
+ await settle();
4801
+ } catch (e) {
4802
+ if (controller.signal.aborted) return;
4803
+ const err = e instanceof Error ? e : new Error(String(e));
4804
+ console.error(err);
4805
+ setError(err.message);
4806
+ onError?.(err);
4807
+ } finally {
4808
+ if (streamAbortRef.current === controller) {
4809
+ streamAbortRef.current = null;
4810
+ setIsStreaming(false);
4811
+ }
4812
+ }
4813
+ },
4814
+ [
4815
+ apiVersion,
4816
+ getPuck,
4817
+ getRequestConfig,
4818
+ onError,
4819
+ processData,
4820
+ settle,
4821
+ streamHost
4822
+ ]
4823
+ );
4824
+ const stopAll = useCallback5(() => {
4825
+ streamAbortRef.current?.abort();
4826
+ streamAbortRef.current = null;
4827
+ setIsStreaming(false);
4828
+ stop();
4829
+ }, [stop]);
4830
+ useEffect12(() => () => stopAll(), [stopAll]);
4831
+ return {
4832
+ /**
4833
+ * Send a prompt as the next turn of a conversation. The agent sees the
4834
+ * history, and can write, check its work and correct itself.
4835
+ */
4836
+ sendMessage,
4837
+ /**
4838
+ * Run a one-shot generation from a prompt, with no conversation. Cheaper
4839
+ * and more predictable than `sendMessage`, but it stops after its first
4840
+ * write rather than reviewing the result.
4841
+ */
4842
+ stream,
4843
+ /** Abort whichever request is in flight */
4844
+ stop: stopAll,
4845
+ status: isStreaming ? "streaming" : chatStatus,
4846
+ /** The conversation so far, for building a transcript */
4847
+ messages,
4848
+ setMessages,
4849
+ regenerate,
4850
+ error,
4851
+ /** Live per-tool progress, keyed by tool call id */
4852
+ toolStatus,
4853
+ /** Live subagent progress, keyed by tool call id */
4854
+ subagentState,
4855
+ /**
4856
+ * @internal Apply a single stream part to the editor. Exposed for
4857
+ * replaying a recorded stream (the marketing demo) — a real agent should
4858
+ * go through `stream`.
4859
+ */
4860
+ processData
4861
+ };
4862
+ }
4863
+ function finalizeReasoningParts(parts) {
4864
+ return parts.map(
4865
+ (part) => part.kind === "reasoning" && part.state !== "done" ? { ...part, state: "done" } : part
4866
+ );
4867
+ }
4868
+ function reduceSubagentEvent(current, event) {
4869
+ if (event.kind === "start") {
4870
+ if (current[event.toolCallId]) return current;
4871
+ return {
4872
+ ...current,
4873
+ [event.toolCallId]: {
4874
+ toolCallId: event.toolCallId,
4875
+ parentToolCallId: event.parentToolCallId,
4876
+ agentType: event.agentType,
4877
+ depth: event.depth,
4878
+ label: event.label,
4879
+ state: "running",
4880
+ parts: []
4881
+ }
4882
+ };
4883
+ }
4884
+ const existing = current[event.toolCallId];
4885
+ if (!existing) return current;
4886
+ if (event.kind === "finish") {
4887
+ return {
4888
+ ...current,
4889
+ [event.toolCallId]: {
4890
+ ...existing,
4891
+ state: "done",
4892
+ parts: finalizeReasoningParts(existing.parts)
4893
+ }
4894
+ };
4895
+ }
4896
+ if (event.kind === "reasoning-delta") {
4897
+ const parts = [...existing.parts];
4898
+ const last = parts[parts.length - 1];
4899
+ if (last && last.kind === "reasoning" && last.state !== "done") {
4900
+ const separator = last.blockId !== event.blockId ? "\n\n" : "";
4901
+ parts[parts.length - 1] = {
4902
+ ...last,
4903
+ blockId: event.blockId,
4904
+ text: last.text + separator + event.text
4905
+ };
4906
+ } else {
4907
+ parts.push({
4908
+ kind: "reasoning",
4909
+ blockId: event.blockId,
4910
+ text: event.text,
4911
+ state: "streaming"
4912
+ });
4913
+ }
4914
+ return {
4915
+ ...current,
4916
+ [event.toolCallId]: { ...existing, parts }
4917
+ };
4918
+ }
4919
+ if (event.kind === "text-delta") {
4920
+ const parts = finalizeReasoningParts(existing.parts);
4921
+ const last = parts[parts.length - 1];
4922
+ if (last && last.kind === "text" && last.blockId === event.blockId) {
4923
+ parts[parts.length - 1] = { ...last, text: last.text + event.text };
4924
+ } else {
4925
+ parts.push({ kind: "text", blockId: event.blockId, text: event.text });
4926
+ }
4927
+ return {
4928
+ ...current,
4929
+ [event.toolCallId]: { ...existing, parts }
4930
+ };
4931
+ }
4932
+ if (event.kind === "tool-call") {
4933
+ return {
4934
+ ...current,
4935
+ [event.toolCallId]: {
4936
+ ...existing,
4937
+ parts: [
4938
+ ...finalizeReasoningParts(existing.parts),
4939
+ {
4940
+ kind: "tool",
4941
+ childToolCallId: event.childToolCallId,
4942
+ toolName: event.toolName,
4943
+ input: event.input
4944
+ }
4945
+ ]
4754
4946
  }
4755
- }),
4756
- onData: processData,
4757
- onError: (e) => {
4758
- console.error(e);
4759
- if (BENCHMARK) {
4760
- console.timeEnd("chat");
4947
+ };
4948
+ }
4949
+ if (event.kind === "tool-result") {
4950
+ return {
4951
+ ...current,
4952
+ [event.toolCallId]: {
4953
+ ...existing,
4954
+ parts: existing.parts.map(
4955
+ (part) => part.kind === "tool" && part.childToolCallId === event.childToolCallId ? { ...part, output: event.output } : part
4956
+ )
4761
4957
  }
4762
- setError(e.message);
4763
- },
4764
- onFinish: (options) => {
4765
- debouncedFlushBuildOps.flush();
4766
- q.wait().then(() => {
4767
- if (!options.isAbort) {
4768
- puckDispatch({
4769
- type: "set",
4770
- state: getPuck().appState,
4771
- recordHistory: true
4772
- });
4773
- }
4774
- chat?.onFinish?.(options);
4775
- }).finally(() => {
4776
- if (BENCHMARK) {
4777
- console.timeEnd("chat");
4778
- }
4779
- });
4780
- }
4781
- });
4958
+ };
4959
+ }
4960
+ return current;
4961
+ }
4962
+ function nextFrame(cb) {
4963
+ let ran = false;
4964
+ const run = () => {
4965
+ if (ran) return;
4966
+ ran = true;
4967
+ cb();
4968
+ };
4969
+ if (typeof document !== "undefined" && document.hidden) {
4970
+ queueMicrotask(run);
4971
+ return;
4972
+ }
4973
+ requestAnimationFrame(run);
4974
+ setTimeout(run, 100);
4975
+ }
4976
+
4977
+ // src/components/Chat/index.tsx
4978
+ import { Fragment as Fragment9, jsx as jsx35, jsxs as jsxs20 } from "react/jsx-runtime";
4979
+ var getClassName18 = getClassNameFactory("Chat", styles_module_default);
4980
+ var usePuck2 = createUsePuck2();
4981
+ function Chat2(props) {
4982
+ const {
4983
+ apiVersion = DEFAULT_API_VERSION,
4984
+ chat,
4985
+ designMode = false,
4986
+ defaultMode = "assembly",
4987
+ host = "/api/puck/chat",
4988
+ prepareRequest,
4989
+ scrollTrackingId
4990
+ } = props;
4991
+ const {
4992
+ attachments,
4993
+ examplePrompts,
4994
+ actions: chatActions,
4995
+ placeholder
4996
+ } = chat ?? {};
4997
+ const puckDispatch = usePuck2((s) => s.dispatch);
4998
+ const inputRef = useRef12(null);
4999
+ const pluginRef = useRef12(null);
5000
+ const [mode, setMode] = useState16(defaultMode);
5001
+ const designModeVisible = typeof designMode === "boolean" ? designMode : designMode.visible ?? false;
5002
+ const [error, setError] = useState16();
5003
+ const [userError, setUserError] = useState16();
5004
+ const [composerAttachments, setComposerAttachments] = useState16([]);
5005
+ const removedAttachmentClientIdsRef = useRef12(/* @__PURE__ */ new Set());
5006
+ const uploadControllersRef = useRef12(/* @__PURE__ */ new Map());
5007
+ const attachmentConfig = useMemo6(
5008
+ () => ({
5009
+ accept: attachments?.accept ?? defaultAttachmentAccept,
5010
+ enabled: attachments?.enabled ?? true,
5011
+ endpoint: `${host.replace(/\/$/, "")}/attachments`,
5012
+ maxFiles: attachments?.maxFiles ?? defaultAttachmentConfig.maxFiles,
5013
+ maxSizeBytes: attachments?.maxSizeBytes ?? defaultAttachmentConfig.maxSizeBytes
5014
+ }),
5015
+ [attachments, host]
5016
+ );
4782
5017
  useEffect13(
4783
5018
  () => () => {
4784
- stop();
5019
+ uploadControllersRef.current.forEach((controller) => controller.abort());
5020
+ uploadControllersRef.current.clear();
5021
+ },
5022
+ []
5023
+ );
5024
+ const deleteAttachment = useCallback6(
5025
+ async (attachmentId) => {
5026
+ try {
5027
+ await fetch(`${attachmentConfig.endpoint}/${attachmentId}`, {
5028
+ method: "DELETE"
5029
+ });
5030
+ } catch (e) {
5031
+ console.error(e);
5032
+ }
4785
5033
  },
4786
- [stop]
5034
+ [attachmentConfig.endpoint]
4787
5035
  );
5036
+ const {
5037
+ sendMessage,
5038
+ status,
5039
+ messages,
5040
+ setMessages,
5041
+ regenerate,
5042
+ error: aiError,
5043
+ toolStatus,
5044
+ subagentState,
5045
+ processData
5046
+ } = usePuckAi({
5047
+ host,
5048
+ mode,
5049
+ apiVersion,
5050
+ prepareRequest,
5051
+ onFinish: chat?.onFinish
5052
+ });
4788
5053
  const [forcedStatus, setForcedStatus] = useState16();
4789
5054
  const resolvedStatus = useMemo6(
4790
5055
  () => forcedStatus ?? status,
@@ -4808,7 +5073,11 @@ function Chat2(props) {
4808
5073
  processData,
4809
5074
  setMessages,
4810
5075
  setStatus: setForcedStatus,
4811
- sendMessage,
5076
+ sendMessage: (message) => sendMessage(
5077
+ message.parts.filter(
5078
+ (part) => Boolean(part && part.type === "text")
5079
+ ).map((part) => part.text).join("")
5080
+ ),
4812
5081
  focus: () => inputRef?.current?.focus()
4813
5082
  };
4814
5083
  }, [processData]);
@@ -4850,13 +5119,7 @@ function Chat2(props) {
4850
5119
  }
4851
5120
  setComposerAttachments([]);
4852
5121
  removedAttachmentClientIdsRef.current.clear();
4853
- sendMessage({
4854
- role: "user",
4855
- parts: [
4856
- ...text ? [{ type: "text", text }] : [],
4857
- ...readyAttachments
4858
- ]
4859
- }).catch((e) => {
5122
+ sendMessage(text, { files: readyAttachments }).catch((e) => {
4860
5123
  console.error(e);
4861
5124
  setError("Failed to send message.");
4862
5125
  setComposerAttachments(composerAttachments);
@@ -5072,7 +5335,7 @@ function Chat2(props) {
5072
5335
  label
5073
5336
  )
5074
5337
  ),
5075
- error,
5338
+ error: error ?? aiError,
5076
5339
  handleRetry: () => {
5077
5340
  setError("");
5078
5341
  regenerate();
@@ -5090,105 +5353,6 @@ function Chat2(props) {
5090
5353
  }
5091
5354
  ) }) }) }) });
5092
5355
  }
5093
- function finalizeReasoningParts(parts) {
5094
- return parts.map(
5095
- (part) => part.kind === "reasoning" && part.state !== "done" ? { ...part, state: "done" } : part
5096
- );
5097
- }
5098
- function reduceSubagentEvent(current, event) {
5099
- if (event.kind === "start") {
5100
- if (current[event.toolCallId]) return current;
5101
- return {
5102
- ...current,
5103
- [event.toolCallId]: {
5104
- toolCallId: event.toolCallId,
5105
- parentToolCallId: event.parentToolCallId,
5106
- agentType: event.agentType,
5107
- depth: event.depth,
5108
- label: event.label,
5109
- state: "running",
5110
- parts: []
5111
- }
5112
- };
5113
- }
5114
- const existing = current[event.toolCallId];
5115
- if (!existing) return current;
5116
- if (event.kind === "finish") {
5117
- return {
5118
- ...current,
5119
- [event.toolCallId]: {
5120
- ...existing,
5121
- state: "done",
5122
- parts: finalizeReasoningParts(existing.parts)
5123
- }
5124
- };
5125
- }
5126
- if (event.kind === "reasoning-delta") {
5127
- const parts = [...existing.parts];
5128
- const last = parts[parts.length - 1];
5129
- if (last && last.kind === "reasoning" && last.state !== "done") {
5130
- const separator = last.blockId !== event.blockId ? "\n\n" : "";
5131
- parts[parts.length - 1] = {
5132
- ...last,
5133
- blockId: event.blockId,
5134
- text: last.text + separator + event.text
5135
- };
5136
- } else {
5137
- parts.push({
5138
- kind: "reasoning",
5139
- blockId: event.blockId,
5140
- text: event.text,
5141
- state: "streaming"
5142
- });
5143
- }
5144
- return {
5145
- ...current,
5146
- [event.toolCallId]: { ...existing, parts }
5147
- };
5148
- }
5149
- if (event.kind === "text-delta") {
5150
- const parts = finalizeReasoningParts(existing.parts);
5151
- const last = parts[parts.length - 1];
5152
- if (last && last.kind === "text" && last.blockId === event.blockId) {
5153
- parts[parts.length - 1] = { ...last, text: last.text + event.text };
5154
- } else {
5155
- parts.push({ kind: "text", blockId: event.blockId, text: event.text });
5156
- }
5157
- return {
5158
- ...current,
5159
- [event.toolCallId]: { ...existing, parts }
5160
- };
5161
- }
5162
- if (event.kind === "tool-call") {
5163
- return {
5164
- ...current,
5165
- [event.toolCallId]: {
5166
- ...existing,
5167
- parts: [
5168
- ...finalizeReasoningParts(existing.parts),
5169
- {
5170
- kind: "tool",
5171
- childToolCallId: event.childToolCallId,
5172
- toolName: event.toolName,
5173
- input: event.input
5174
- }
5175
- ]
5176
- }
5177
- };
5178
- }
5179
- if (event.kind === "tool-result") {
5180
- return {
5181
- ...current,
5182
- [event.toolCallId]: {
5183
- ...existing,
5184
- parts: existing.parts.map(
5185
- (part) => part.kind === "tool" && part.childToolCallId === event.childToolCallId ? { ...part, output: event.output } : part
5186
- )
5187
- }
5188
- };
5189
- }
5190
- return current;
5191
- }
5192
5356
  function AttachmentComposer({
5193
5357
  accept,
5194
5358
  attachments,
@@ -5274,20 +5438,6 @@ function Placeholder({
5274
5438
  ] })
5275
5439
  ] });
5276
5440
  }
5277
- function nextFrame(cb) {
5278
- let ran = false;
5279
- const run = () => {
5280
- if (ran) return;
5281
- ran = true;
5282
- cb();
5283
- };
5284
- if (typeof document !== "undefined" && document.hidden) {
5285
- queueMicrotask(run);
5286
- return;
5287
- }
5288
- requestAnimationFrame(run);
5289
- setTimeout(run, 100);
5290
- }
5291
5441
  function isScrolledIntoView(el) {
5292
5442
  const rect = el.getBoundingClientRect();
5293
5443
  const elemTop = rect.top;
@@ -5297,7 +5447,7 @@ function isScrolledIntoView(el) {
5297
5447
 
5298
5448
  // src/components/ScrollTracking/ScrollTracking.tsx
5299
5449
  init_react_import();
5300
- import { useEffect as useEffect14, useRef as useRef14 } from "react";
5450
+ import { useEffect as useEffect14, useRef as useRef13 } from "react";
5301
5451
 
5302
5452
  // src/lib/scroll-into-view-local.ts
5303
5453
  init_react_import();
@@ -5367,8 +5517,8 @@ var ScrollTracking = ({
5367
5517
  children,
5368
5518
  trackingId
5369
5519
  }) => {
5370
- const followedRefs = useRef14([]);
5371
- const enabledRef = useRef14(false);
5520
+ const followedRefs = useRef13([]);
5521
+ const enabledRef = useRef13(false);
5372
5522
  useEffect14(() => {
5373
5523
  return subscribeToScrollTrackingEvents(({ id, enabled }) => {
5374
5524
  if (id !== trackingId) return;
@@ -5396,7 +5546,7 @@ var ScrollTracking = ({
5396
5546
 
5397
5547
  // src/components/Drawer/index.tsx
5398
5548
  init_react_import();
5399
- import { createUsePuck as createUsePuck2 } from "@puckeditor/core";
5549
+ import { createUsePuck as createUsePuck3 } from "@puckeditor/core";
5400
5550
 
5401
5551
  // src/components/ManageComponents/index.tsx
5402
5552
  init_react_import();
@@ -5494,10 +5644,10 @@ var styles_module_default11 = { "Drawer--empty": "_Drawer--empty_8e8cs_1" };
5494
5644
 
5495
5645
  // src/components/Drawer/index.tsx
5496
5646
  import { jsx as jsx37, jsxs as jsxs22 } from "react/jsx-runtime";
5497
- var usePuck2 = createUsePuck2();
5647
+ var usePuck3 = createUsePuck3();
5498
5648
  var cx11 = get_class_name_factory_default("Drawer", styles_module_default11);
5499
5649
  var createDrawer = (designModeVisible) => function Drawer({ children }) {
5500
- const config = usePuck2((s) => s.config);
5650
+ const config = usePuck3((s) => s.config);
5501
5651
  if (Object.keys(config.components).length === 0) {
5502
5652
  return /* @__PURE__ */ jsx37("div", { className: cx11({ empty: true }), children: "No blocks" });
5503
5653
  }
@@ -5507,8 +5657,8 @@ var createDrawer = (designModeVisible) => function Drawer({ children }) {
5507
5657
  ] });
5508
5658
  };
5509
5659
 
5510
- // src/index.tsx
5511
- import { Fragment as Fragment11, jsx as jsx38 } from "react/jsx-runtime";
5660
+ // src/lib/design/with-dynamic-config.ts
5661
+ init_react_import();
5512
5662
  function withDynamicConfig(config, data) {
5513
5663
  const registrations = getPersistedRegistrations(data);
5514
5664
  const dynamicConfig = {};
@@ -5538,6 +5688,9 @@ function withDynamicConfig(config, data) {
5538
5688
  applyConfigFieldMetadata(result, dynamicConfig);
5539
5689
  return result;
5540
5690
  }
5691
+
5692
+ // src/index.tsx
5693
+ import { Fragment as Fragment11, jsx as jsx38 } from "react/jsx-runtime";
5541
5694
  function createAiPlugin(opts) {
5542
5695
  const { scrollTracking = true, ...rest } = opts || {};
5543
5696
  const scrollTrackingId = `puck-ai-scroll-${ulid2()}`;
@@ -5561,6 +5714,7 @@ function createAiPlugin(opts) {
5561
5714
  }
5562
5715
  export {
5563
5716
  createAiPlugin,
5717
+ usePuckAi,
5564
5718
  withDynamicConfig
5565
5719
  };
5566
5720
  /*! Bundled license information: