@copilotkit/core 2.0.0-rc.8 → 2.0.0-rc.9

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.umd.js CHANGED
@@ -1,9 +1,37 @@
1
1
  (function(global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@tanstack/pacer'), require('@ag-ui/client'), require('@copilotkit/shared'), require('rxjs'), require('rxjs/operators'), require('phoenix'), require('zod-to-json-schema'), require('@copilotkit/learning')) :
3
- typeof define === 'function' && define.amd ? define(['exports', '@tanstack/pacer', '@ag-ui/client', '@copilotkit/shared', 'rxjs', 'rxjs/operators', 'phoenix', 'zod-to-json-schema', '@copilotkit/learning'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.CopilotKitCore = {}), global._tanstack_pacer,global.AgUIClient,global.CopilotKitShared,global.rxjs,global.rxjs.operators,global.phoenix,global.zodToJsonSchema,global._copilotkit_learning));
5
- })(this, function(exports, _tanstack_pacer, _ag_ui_client, _copilotkit_shared, rxjs, rxjs_operators, phoenix, zod_to_json_schema, _copilotkit_learning) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@tanstack/pacer'), require('@ag-ui/client'), require('@copilotkit/shared'), require('rxjs'), require('rxjs/operators'), require('phoenix'), require('@copilotkit/learning')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', '@tanstack/pacer', '@ag-ui/client', '@copilotkit/shared', 'rxjs', 'rxjs/operators', 'phoenix', '@copilotkit/learning'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.CopilotKitCore = {}), global._tanstack_pacer,global.AgUIClient,global.CopilotKitShared,global.rxjs,global.rxjs.operators,global.phoenix,global._copilotkit_learning));
5
+ })(this, function(exports, _tanstack_pacer, _ag_ui_client, _copilotkit_shared, rxjs, rxjs_operators, phoenix, _copilotkit_learning) {
6
6
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
7
+ //#region \0rolldown/runtime.js
8
+ var __create = Object.create;
9
+ var __defProp = Object.defineProperty;
10
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
11
+ var __getOwnPropNames = Object.getOwnPropertyNames;
12
+ var __getProtoOf = Object.getPrototypeOf;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
18
+ key = keys[i];
19
+ if (!__hasOwnProp.call(to, key) && key !== except) {
20
+ __defProp(to, key, {
21
+ get: ((k) => from[k]).bind(null, key),
22
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
23
+ });
24
+ }
25
+ }
26
+ }
27
+ return to;
28
+ };
29
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
30
+ value: mod,
31
+ enumerable: true
32
+ }) : target, mod));
33
+
34
+ //#endregion
7
35
 
8
36
  //#region src/utils/http-agent.ts
9
37
  /**
@@ -3855,7 +3883,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3855
3883
  */
3856
3884
  function createToolSchema(tool) {
3857
3885
  if (!tool.parameters) return { ...EMPTY_TOOL_SCHEMA };
3858
- const rawSchema = (0, _copilotkit_shared.schemaToJsonSchema)(tool.parameters, { zodToJsonSchema: (schema, options) => (0, zod_to_json_schema.zodToJsonSchema)(schema, options) });
3886
+ const rawSchema = (0, _copilotkit_shared.schemaToJsonSchema)(tool.parameters);
3859
3887
  if (!rawSchema || typeof rawSchema !== "object") return { ...EMPTY_TOOL_SCHEMA };
3860
3888
  const { $schema: _$schema, ...schema } = rawSchema;
3861
3889
  if (typeof schema.type !== "string") schema.type = "object";
@@ -3990,8 +4018,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3990
4018
  }
3991
4019
  /** Reject ambiguous assistant definitions before executing or answering a call. */
3992
4020
  validateToolCalls(messages) {
3993
- var _classPrivateFieldGet2$1;
3994
- if (((_classPrivateFieldGet2$1 = _classPrivateFieldGet2(_pending, this)) === null || _classPrivateFieldGet2$1 === void 0 ? void 0 : _classPrivateFieldGet2$1.kind) !== "standard") return;
4021
+ var _classPrivateFieldGet2$2;
4022
+ if (((_classPrivateFieldGet2$2 = _classPrivateFieldGet2(_pending, this)) === null || _classPrivateFieldGet2$2 === void 0 ? void 0 : _classPrivateFieldGet2$2.kind) !== "standard") return;
3995
4023
  const pendingCalls = new Set(_classPrivateFieldGet2(_pending, this).interrupts.filter((interrupt) => interrupt.reason === "tool_call").map((interrupt) => interrupt.toolCallId));
3996
4024
  const seen = /* @__PURE__ */ new Set();
3997
4025
  for (const message of messages) {
@@ -12661,6 +12689,844 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
12661
12689
  "stroke-linejoin": "round"
12662
12690
  };
12663
12691
 
12692
+ //#endregion
12693
+ //#region src/open-generative-ui/content.ts
12694
+ /**
12695
+ * Open Generative UI content: the activity the agent streams while it
12696
+ * generates a sandboxed UI, and the rules for when a new snapshot must reach
12697
+ * the sandbox at once.
12698
+ */
12699
+ /** The activity type of Open Generative UI messages. */
12700
+ const OPEN_GENERATIVE_UI_ACTIVITY_TYPE = "open-generative-ui";
12701
+ /** The name of the frontend tool the agent calls to generate a sandboxed UI. */
12702
+ const GENERATE_SANDBOXED_UI_TOOL_NAME = "generateSandboxedUi";
12703
+ /** The design guidance sent to the agent when no `designSkill` is set. */
12704
+ const DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL = `When generating UI with generateSandboxedUi, follow these design principles inspired by shadcn/ui:
12705
+
12706
+ - Use a minimal, flat aesthetic. Avoid drop shadows and gradients — rely on subtle borders (1px solid, light gray like #e5e7eb) to define surfaces.
12707
+ - Neutral base palette: white backgrounds, zinc/slate gray text (#09090b for headings, #71717a for secondary text). One accent color for interactive elements.
12708
+ - Use system font stacks (system-ui, -apple-system, sans-serif) at readable sizes (14px body, 600 weight for headings). Tight line-heights.
12709
+ - Small, consistent border-radius (6–8px). Cards and containers use border, not shadow, for separation.
12710
+ - Buttons: solid fill for primary (dark bg, white text), outline for secondary (border + transparent bg). Subtle hover state (slight opacity or background shift).
12711
+ - Use CSS Grid or Flexbox for layout. Ensure the UI looks good at any width.
12712
+ - Minimal transitions (150ms) for hover/focus states only. No decorative animations.
12713
+ - Keep the UI focused and dense — avoid excessive padding. Use compact spacing (8–12px gaps, 10–14px padding in controls).`;
12714
+ /** `true` when the content has HTML that a preview or final sandbox shows. */
12715
+ function hasRenderableContent(content) {
12716
+ var _content$html;
12717
+ if (!content) return false;
12718
+ const hasHtml = !!((_content$html = content.html) === null || _content$html === void 0 ? void 0 : _content$html.join("").trim());
12719
+ const hasFinalHtml = content.htmlComplete && hasHtml;
12720
+ const hasPreviewHtml = content.cssComplete && !content.htmlComplete && hasHtml;
12721
+ return !!hasFinalHtml || !!hasPreviewHtml;
12722
+ }
12723
+ /**
12724
+ * `true` when `next` must replace `previous` at once instead of waiting for
12725
+ * the throttle window: the UI restarts, a stage completes, or new JavaScript
12726
+ * arrives.
12727
+ */
12728
+ function shouldFlushImmediately(previous, next) {
12729
+ var _next$jsExpressions$l, _next$jsExpressions, _previous$jsExpressio, _previous$jsExpressio2, _next$html, _previous$html;
12730
+ if (hasRenderableContent(previous) && !hasRenderableContent(next)) return true;
12731
+ if (next.cssComplete && !(previous === null || previous === void 0 ? void 0 : previous.cssComplete)) return true;
12732
+ if (next.htmlComplete) return true;
12733
+ if (next.generating === false) return true;
12734
+ if (next.jsFunctions && !(previous === null || previous === void 0 ? void 0 : previous.jsFunctions)) return true;
12735
+ if (((_next$jsExpressions$l = (_next$jsExpressions = next.jsExpressions) === null || _next$jsExpressions === void 0 ? void 0 : _next$jsExpressions.length) !== null && _next$jsExpressions$l !== void 0 ? _next$jsExpressions$l : 0) > ((_previous$jsExpressio = previous === null || previous === void 0 || (_previous$jsExpressio2 = previous.jsExpressions) === null || _previous$jsExpressio2 === void 0 ? void 0 : _previous$jsExpressio2.length) !== null && _previous$jsExpressio !== void 0 ? _previous$jsExpressio : 0)) return true;
12736
+ if (((_next$html = next.html) === null || _next$html === void 0 ? void 0 : _next$html.length) && !(previous === null || previous === void 0 || (_previous$html = previous.html) === null || _previous$html === void 0 ? void 0 : _previous$html.length)) return true;
12737
+ return false;
12738
+ }
12739
+
12740
+ //#endregion
12741
+ //#region src/open-generative-ui/html.ts
12742
+ /**
12743
+ * Pure string helpers that turn streamed HTML into sandbox content.
12744
+ * No DOM access.
12745
+ */
12746
+ /**
12747
+ * Extracts all complete `<style>` blocks from the raw HTML.
12748
+ * Returns the concatenated style tags, suitable for injection into `<head>`.
12749
+ */
12750
+ function extractCompleteStyles(html) {
12751
+ const matches = html.match(/<style\b[^>]*>[\s\S]*?<\/style>/gi);
12752
+ return matches ? matches.join("") : "";
12753
+ }
12754
+ /**
12755
+ * Processes raw accumulated HTML for safe preview via innerHTML injection.
12756
+ *
12757
+ * Pipeline (order matters):
12758
+ * 1. Strip incomplete tag at end
12759
+ * 2. Strip complete <style>, <script>, and <head> blocks
12760
+ * 3. Strip incomplete <style>/<script>/<head> blocks
12761
+ * 4. Strip incomplete HTML entities
12762
+ * 5. Extract body content (or use full string if no <body>)
12763
+ */
12764
+ function processPartialHtml(html) {
12765
+ let result = html;
12766
+ result = result.replace(/<[^>]*$/, "");
12767
+ result = result.replace(/<(style|script|head)\b[^>]*>[\s\S]*?<\/\1>/gi, "");
12768
+ result = result.replace(/<(style|script|head)\b[^>]*>[\s\S]*$/gi, "");
12769
+ result = result.replace(/&[a-zA-Z0-9#]*$/, "");
12770
+ const bodyMatch = result.match(/<body[^>]*>([\s\S]*)/i);
12771
+ if (bodyMatch) {
12772
+ result = bodyMatch[1];
12773
+ result = result.replace(/<\/body>[\s\S]*/i, "");
12774
+ }
12775
+ return result;
12776
+ }
12777
+ /** Builds the final sandbox document: the HTML with the CSS in its `<head>`. */
12778
+ function buildFinalFrameContent(html, css) {
12779
+ const withCss = css ? injectCssIntoHtml(html, css) : html;
12780
+ return /<head[\s>]/i.test(withCss) ? withCss : `<head></head>${withCss}`;
12781
+ }
12782
+ function injectCssIntoHtml(html, css) {
12783
+ const headCloseIdx = html.indexOf("</head>");
12784
+ if (headCloseIdx !== -1) return html.slice(0, headCloseIdx) + `<style>${css}</style>` + html.slice(headCloseIdx);
12785
+ return `<head><style>${css}</style></head>${html}`;
12786
+ }
12787
+
12788
+ //#endregion
12789
+ //#region ../../node_modules/.pnpm/@jetbrains+websandbox@1.1.3/node_modules/@jetbrains/websandbox/dist/websandbox.js
12790
+ var require_websandbox = /* @__PURE__ */ __commonJSMin(((exports, module) => {
12791
+ (function webpackUniversalModuleDefinition(root, factory) {
12792
+ if (typeof exports === "object" && typeof module === "object") module.exports = factory();
12793
+ else if (typeof define === "function" && define.amd) define([], factory);
12794
+ else if (typeof exports === "object") exports["Websandbox"] = factory();
12795
+ else root["Websandbox"] = factory();
12796
+ })(self, () => {
12797
+ return (() => {
12798
+ var __webpack_modules__ = { 466: ((module$1) => {
12799
+ module$1.exports = "/******/ (() => { // webpackBootstrap\n/******/ \"use strict\";\n\n// UNUSED EXPORTS: default\n\n;// ./lib/object-path.ts\nconst PATH_REG = /([.[\\]:;'\"\\s])/;\nfunction escapePathPart(pathPart) {\n if (!PATH_REG.test(pathPart)) {\n return pathPart;\n }\n const escaped = pathPart.replace(new RegExp(PATH_REG.source, 'g'), '\\\\$1');\n return `[\"${escaped}\"]`;\n}\nfunction unescapePathPart(pathPart) {\n return pathPart.replace(/^\\[\"/, '').replace(/\"]$/, '').replace(/\\\\/, '');\n}\nfunction splitPath(path) {\n const result = [];\n let lastEnd = 0;\n for (let i = 0; i < path.length; i++) {\n const char = path[i];\n if (PATH_REG.test(char) && path[i - 1] !== '\\\\') {\n result.push(path.substring(lastEnd, i));\n lastEnd = i + 1;\n }\n }\n result.push(path.substring(lastEnd, path.length));\n return result.filter(pathPart => !!pathPart).map(pathPart => pathPart.replace(/\\\\/g, ''));\n}\n/**\n * Extracts object property value by given path. Supports nested and array values: 'foo[0].bar'\n * @param {Object} object source object\n * @param {string} path path to value\n * @return {any | null} value by given path\n * */\nfunction propertyByPath(object, path) {\n return splitPath(path).reduce((acc, pathPart) => {\n if (acc) {\n return acc[pathPart];\n }\n return null;\n }, object);\n}\n\n;// ./lib/connection.ts\n\nconst TYPE_MESSAGE = 'message';\nconst TYPE_RESPONSE = 'response';\nconst TYPE_SET_INTERFACE = 'set-interface';\nconst TYPE_SERVICE_MESSAGE = 'service-message';\n// @ts-expect-error this is IE11 obsolete check. It is not typed\nconst isIE11 = !!window.MSInputMethodContext && !!document.documentMode;\nconst defaultOptions = {\n //Will not affect IE11 because there sandboxed iframe has not 'null' origin\n //but base URL of iframe's src\n allowedSenderOrigin: undefined\n};\nclass Connection {\n constructor(postMessage, registerOnMessageListener, options = {}) {\n this.remote = {};\n this.serviceMethods = {};\n this.localApi = {};\n this.callbacks = {};\n this._resolveRemoteMethodsPromise = null;\n this.options = Object.assign(Object.assign({}, defaultOptions), options);\n //Random number between 0 and 100000\n this.incrementalID = Math.floor(Math.random() * 100000);\n this.postMessage = postMessage;\n this.remoteMethodsWaitPromise = new Promise(resolve => {\n this._resolveRemoteMethodsPromise = resolve;\n });\n registerOnMessageListener((e) => this.onMessageListener(e));\n }\n /**\n * Listens to remote messages. Calls local method if it is called outside or call stored callback if it is response.\n * @param e - onMessage event\n */\n onMessageListener(e) {\n const data = e.data;\n const { allowedSenderOrigin } = this.options;\n if (allowedSenderOrigin && e.origin !== allowedSenderOrigin && !isIE11) {\n return;\n }\n if (data.type === TYPE_RESPONSE) {\n this.popCallback(data.callId, data.success, data.result);\n }\n else if (data.type === TYPE_MESSAGE) {\n this\n .callLocalApi(data.methodName, data.arguments)\n .then(res => this.responseOtherSide(data.callId, res))\n .catch(err => this.responseOtherSide(data.callId, err, false));\n }\n else if (data.type === TYPE_SET_INTERFACE) {\n this.setInterface(data.apiMethods);\n this.responseOtherSide(data.callId);\n }\n else if (data.type === TYPE_SERVICE_MESSAGE) {\n this\n .callLocalServiceMethod(data.methodName, data.arguments)\n .then(res => this.responseOtherSide(data.callId, res))\n .catch(err => this.responseOtherSide(data.callId, err, false));\n }\n }\n postMessageToOtherSide(dataToPost) {\n this.postMessage(dataToPost, '*');\n }\n /**\n * Sets remote interface methods\n * @param remote - hash with keys of remote API methods. Values is ignored\n */\n setInterface(remoteMethods) {\n var _a;\n this.remote = {};\n remoteMethods.forEach((key) => {\n // If key is nested, we need to create nested structure\n const parts = splitPath(key);\n let current = this.remote;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (!current[part] || typeof current[part] !== 'object') {\n current[part] = {};\n }\n current = current[part];\n }\n current[parts[parts.length - 1]] = this.createMethodWrapper(key);\n });\n (_a = this._resolveRemoteMethodsPromise) === null || _a === void 0 ? void 0 : _a.call(this);\n }\n getMethodsFromInterface(api) {\n return Object.keys(api).reduce((acc, key) => {\n if (typeof api[key] === 'object') {\n acc.push(...this.getMethodsFromInterface(api[key]).map(subKey => `${key}.${subKey}`));\n }\n else {\n acc.push(key);\n }\n return acc;\n }, []);\n }\n setLocalApi(api) {\n return new Promise((resolve, reject) => {\n const id = this.registerCallback(resolve, reject);\n this.postMessageToOtherSide({\n callId: id,\n apiMethods: this.getMethodsFromInterface(api),\n type: TYPE_SET_INTERFACE\n });\n }).then(() => this.localApi = api);\n }\n setServiceMethods(api) {\n this.serviceMethods = api;\n }\n /**\n * Calls local method\n * @param methodName\n * @param args\n * @returns {Promise.<*>|string}\n */\n callLocalApi(methodName, args) {\n const method = propertyByPath(this.localApi, methodName);\n if (!method) {\n throw new Error(`Local method \"${methodName}\" is not registered`);\n }\n return Promise.resolve(method.call(this, ...args));\n }\n /**\n * Calls local method registered as \"service method\"\n * @param methodName\n * @param args\n * @returns {Promise.<*>}\n */\n callLocalServiceMethod(methodName, args) {\n const method = propertyByPath(this.serviceMethods, methodName);\n if (!method) {\n throw new Error(`Service method ${methodName} is not registered`);\n }\n return Promise.resolve(method.call(this, ...args));\n }\n /**\n * Wraps remote method with callback storing code\n * @param methodName - method to wrap\n * @returns {Function} - function to call as remote API interface\n */\n createMethodWrapper(methodName) {\n return (...args) => {\n return this.callRemoteMethod(methodName, ...args);\n };\n }\n /**\n * Calls other side with arguments provided\n * @param id\n * @param methodName\n * @param args\n */\n callRemoteMethod(methodName, ...args) {\n return new Promise((resolve, reject) => {\n const id = this.registerCallback(resolve, reject);\n this.postMessageToOtherSide({\n callId: id,\n methodName: methodName,\n type: TYPE_MESSAGE,\n arguments: args\n });\n });\n }\n /**\n * Calls remote service method\n * @param methodName\n * @param args\n * @returns {*}\n */\n callRemoteServiceMethod(methodName, ...args) {\n return new Promise((resolve, reject) => {\n const id = this.registerCallback(resolve, reject);\n this.postMessageToOtherSide({\n callId: id,\n methodName: methodName,\n type: TYPE_SERVICE_MESSAGE,\n arguments: args\n });\n });\n }\n /**\n * Respond to remote call\n * @param id - remote call ID\n * @param result - result to pass to calling function\n */\n responseOtherSide(id, result, success = true) {\n if (result instanceof Error) {\n // Error could be non-serializable, so we copy properties manually\n result = [...Object.keys(result), 'message'].reduce((acc, it) => {\n acc[it] = result[it];\n return acc;\n }, {});\n }\n const doPost = () => this.postMessage({\n callId: id,\n type: TYPE_RESPONSE,\n success,\n result\n }, '*');\n try {\n doPost();\n }\n catch (err) {\n console.error('Failed to post response, recovering...', err); // eslint-disable-line no-console\n if (err instanceof DOMException) {\n result = JSON.parse(JSON.stringify(result));\n doPost();\n }\n }\n }\n /*\n * Stores callbacks to call later when remote call will be answered\n */\n registerCallback(successCallback, failureCallback) {\n const id = (++this.incrementalID).toString();\n this.callbacks[id] = { successCallback, failureCallback };\n return id;\n }\n /**\n * Calls and delete stored callback\n * @param id - call id\n * @param success - was call successful\n * @param result - result of remote call\n */\n popCallback(id, success, result) {\n const callback = this.callbacks[id];\n if (!callback) {\n return;\n }\n if (success) {\n callback.successCallback(result);\n }\n else {\n callback.failureCallback(result);\n }\n delete this.callbacks[id];\n }\n}\n/* harmony default export */ const connection = (Connection);\n\n;// ./node_modules/ts-loader/index.js??ruleSet[1].rules[0]!./lib/frame.ts\n\nclass Frame {\n constructor() {\n this.connection = new connection(window.parent.postMessage.bind(window.parent), listener => {\n const sourceCheckListener = (event) => {\n if (event.source !== window.parent) {\n return;\n }\n return listener(event);\n };\n window.addEventListener('message', sourceCheckListener);\n });\n this.connection.setServiceMethods({\n runCode: (code) => this.runCode(code),\n importScript: (path) => this.importScript(path),\n injectStyle: (style) => this.injectStyle(style),\n importStyle: (path) => this.importStyle(path)\n });\n this.connection.callRemoteServiceMethod('iframeInitialized');\n }\n /**\n * Creates script tag with passed code and attaches it. Runs synchronous\n * @param code\n */\n runCode(code) {\n const scriptTag = document.createElement('script');\n scriptTag.innerHTML = code;\n document.getElementsByTagName('head')[0].appendChild(scriptTag);\n }\n importScript(scriptUrl) {\n const scriptTag = document.createElement('script');\n scriptTag.src = scriptUrl;\n document.getElementsByTagName('head')[0].appendChild(scriptTag);\n return new Promise(resolve => scriptTag.onload = () => resolve());\n }\n injectStyle(style) {\n const styleTag = document.createElement('style');\n styleTag.innerHTML = style;\n document.getElementsByTagName('head')[0].appendChild(styleTag);\n }\n importStyle(styleUrl) {\n const linkTag = document.createElement('link');\n linkTag.rel = 'stylesheet';\n linkTag.href = styleUrl;\n document.getElementsByTagName('head')[0].appendChild(linkTag);\n }\n}\n// @ts-expect-error we explicitly export library to global namespace because\nconst Websandbox = window.Websandbox || new Frame();\n// @ts-expect-error we explicitly export library to global namespace because\n// Webpack won't do it for us when this file is loaded via code-loader\nwindow.Websandbox = Websandbox;\n/* harmony default export */ const ts_loader_ruleSet_1_rules_0_lib_frame = ((/* unused pure expression or super */ null && (Websandbox)));\n\n/******/ })()\n;\n//# sourceMappingURL=compile-loader-file-name.js.map";
12800
+ }) };
12801
+ var __webpack_module_cache__ = {};
12802
+ function __webpack_require__(moduleId) {
12803
+ var cachedModule = __webpack_module_cache__[moduleId];
12804
+ if (cachedModule !== void 0) return cachedModule.exports;
12805
+ var module$2 = __webpack_module_cache__[moduleId] = { exports: {} };
12806
+ __webpack_modules__[moduleId](module$2, module$2.exports, __webpack_require__);
12807
+ return module$2.exports;
12808
+ }
12809
+ __webpack_require__.n = (module$3) => {
12810
+ var getter = module$3 && module$3.__esModule ? () => module$3["default"] : () => module$3;
12811
+ __webpack_require__.d(getter, { a: getter });
12812
+ return getter;
12813
+ };
12814
+ __webpack_require__.d = (exports$1, definition) => {
12815
+ for (var key in definition) if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports$1, key)) Object.defineProperty(exports$1, key, {
12816
+ enumerable: true,
12817
+ get: definition[key]
12818
+ });
12819
+ };
12820
+ __webpack_require__.o = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop);
12821
+ __webpack_require__.r = (exports$2) => {
12822
+ if (typeof Symbol !== "undefined" && Symbol.toStringTag) Object.defineProperty(exports$2, Symbol.toStringTag, { value: "Module" });
12823
+ Object.defineProperty(exports$2, "__esModule", { value: true });
12824
+ };
12825
+ var __webpack_exports__ = {};
12826
+ (() => {
12827
+ "use strict";
12828
+ __webpack_require__.r(__webpack_exports__);
12829
+ __webpack_require__.d(__webpack_exports__, {
12830
+ BaseOptions: () => BaseOptions,
12831
+ "default": () => websandbox
12832
+ });
12833
+ const PATH_REG = /([.[\]:;'"\s])/;
12834
+ function splitPath(path) {
12835
+ const result = [];
12836
+ let lastEnd = 0;
12837
+ for (let i = 0; i < path.length; i++) {
12838
+ const char = path[i];
12839
+ if (PATH_REG.test(char) && path[i - 1] !== "\\") {
12840
+ result.push(path.substring(lastEnd, i));
12841
+ lastEnd = i + 1;
12842
+ }
12843
+ }
12844
+ result.push(path.substring(lastEnd, path.length));
12845
+ return result.filter((pathPart) => !!pathPart).map((pathPart) => pathPart.replace(/\\/g, ""));
12846
+ }
12847
+ /**
12848
+ * Extracts object property value by given path. Supports nested and array values: 'foo[0].bar'
12849
+ * @param {Object} object source object
12850
+ * @param {string} path path to value
12851
+ * @return {any | null} value by given path
12852
+ * */
12853
+ function propertyByPath(object, path) {
12854
+ return splitPath(path).reduce((acc, pathPart) => {
12855
+ if (acc) return acc[pathPart];
12856
+ return null;
12857
+ }, object);
12858
+ }
12859
+ const TYPE_MESSAGE = "message";
12860
+ const TYPE_RESPONSE = "response";
12861
+ const TYPE_SET_INTERFACE = "set-interface";
12862
+ const TYPE_SERVICE_MESSAGE = "service-message";
12863
+ const isIE11 = !!window.MSInputMethodContext && !!document.documentMode;
12864
+ const defaultOptions = { allowedSenderOrigin: void 0 };
12865
+ class Connection {
12866
+ constructor(postMessage, registerOnMessageListener, options = {}) {
12867
+ this.remote = {};
12868
+ this.serviceMethods = {};
12869
+ this.localApi = {};
12870
+ this.callbacks = {};
12871
+ this._resolveRemoteMethodsPromise = null;
12872
+ this.options = Object.assign(Object.assign({}, defaultOptions), options);
12873
+ this.incrementalID = Math.floor(Math.random() * 1e5);
12874
+ this.postMessage = postMessage;
12875
+ this.remoteMethodsWaitPromise = new Promise((resolve) => {
12876
+ this._resolveRemoteMethodsPromise = resolve;
12877
+ });
12878
+ registerOnMessageListener((e) => this.onMessageListener(e));
12879
+ }
12880
+ /**
12881
+ * Listens to remote messages. Calls local method if it is called outside or call stored callback if it is response.
12882
+ * @param e - onMessage event
12883
+ */
12884
+ onMessageListener(e) {
12885
+ const data = e.data;
12886
+ const { allowedSenderOrigin } = this.options;
12887
+ if (allowedSenderOrigin && e.origin !== allowedSenderOrigin && !isIE11) return;
12888
+ if (data.type === TYPE_RESPONSE) this.popCallback(data.callId, data.success, data.result);
12889
+ else if (data.type === TYPE_MESSAGE) this.callLocalApi(data.methodName, data.arguments).then((res) => this.responseOtherSide(data.callId, res)).catch((err) => this.responseOtherSide(data.callId, err, false));
12890
+ else if (data.type === TYPE_SET_INTERFACE) {
12891
+ this.setInterface(data.apiMethods);
12892
+ this.responseOtherSide(data.callId);
12893
+ } else if (data.type === TYPE_SERVICE_MESSAGE) this.callLocalServiceMethod(data.methodName, data.arguments).then((res) => this.responseOtherSide(data.callId, res)).catch((err) => this.responseOtherSide(data.callId, err, false));
12894
+ }
12895
+ postMessageToOtherSide(dataToPost) {
12896
+ this.postMessage(dataToPost, "*");
12897
+ }
12898
+ /**
12899
+ * Sets remote interface methods
12900
+ * @param remote - hash with keys of remote API methods. Values is ignored
12901
+ */
12902
+ setInterface(remoteMethods) {
12903
+ var _a;
12904
+ this.remote = {};
12905
+ remoteMethods.forEach((key) => {
12906
+ const parts = splitPath(key);
12907
+ let current = this.remote;
12908
+ for (let i = 0; i < parts.length - 1; i++) {
12909
+ const part = parts[i];
12910
+ if (!current[part] || typeof current[part] !== "object") current[part] = {};
12911
+ current = current[part];
12912
+ }
12913
+ current[parts[parts.length - 1]] = this.createMethodWrapper(key);
12914
+ });
12915
+ (_a = this._resolveRemoteMethodsPromise) === null || _a === void 0 || _a.call(this);
12916
+ }
12917
+ getMethodsFromInterface(api) {
12918
+ return Object.keys(api).reduce((acc, key) => {
12919
+ if (typeof api[key] === "object") acc.push(...this.getMethodsFromInterface(api[key]).map((subKey) => `${key}.${subKey}`));
12920
+ else acc.push(key);
12921
+ return acc;
12922
+ }, []);
12923
+ }
12924
+ setLocalApi(api) {
12925
+ return new Promise((resolve, reject) => {
12926
+ const id = this.registerCallback(resolve, reject);
12927
+ this.postMessageToOtherSide({
12928
+ callId: id,
12929
+ apiMethods: this.getMethodsFromInterface(api),
12930
+ type: TYPE_SET_INTERFACE
12931
+ });
12932
+ }).then(() => this.localApi = api);
12933
+ }
12934
+ setServiceMethods(api) {
12935
+ this.serviceMethods = api;
12936
+ }
12937
+ /**
12938
+ * Calls local method
12939
+ * @param methodName
12940
+ * @param args
12941
+ * @returns {Promise.<*>|string}
12942
+ */
12943
+ callLocalApi(methodName, args) {
12944
+ const method = propertyByPath(this.localApi, methodName);
12945
+ if (!method) throw new Error(`Local method "${methodName}" is not registered`);
12946
+ return Promise.resolve(method.call(this, ...args));
12947
+ }
12948
+ /**
12949
+ * Calls local method registered as "service method"
12950
+ * @param methodName
12951
+ * @param args
12952
+ * @returns {Promise.<*>}
12953
+ */
12954
+ callLocalServiceMethod(methodName, args) {
12955
+ const method = propertyByPath(this.serviceMethods, methodName);
12956
+ if (!method) throw new Error(`Service method ${methodName} is not registered`);
12957
+ return Promise.resolve(method.call(this, ...args));
12958
+ }
12959
+ /**
12960
+ * Wraps remote method with callback storing code
12961
+ * @param methodName - method to wrap
12962
+ * @returns {Function} - function to call as remote API interface
12963
+ */
12964
+ createMethodWrapper(methodName) {
12965
+ return (...args) => {
12966
+ return this.callRemoteMethod(methodName, ...args);
12967
+ };
12968
+ }
12969
+ /**
12970
+ * Calls other side with arguments provided
12971
+ * @param id
12972
+ * @param methodName
12973
+ * @param args
12974
+ */
12975
+ callRemoteMethod(methodName, ...args) {
12976
+ return new Promise((resolve, reject) => {
12977
+ const id = this.registerCallback(resolve, reject);
12978
+ this.postMessageToOtherSide({
12979
+ callId: id,
12980
+ methodName,
12981
+ type: TYPE_MESSAGE,
12982
+ arguments: args
12983
+ });
12984
+ });
12985
+ }
12986
+ /**
12987
+ * Calls remote service method
12988
+ * @param methodName
12989
+ * @param args
12990
+ * @returns {*}
12991
+ */
12992
+ callRemoteServiceMethod(methodName, ...args) {
12993
+ return new Promise((resolve, reject) => {
12994
+ const id = this.registerCallback(resolve, reject);
12995
+ this.postMessageToOtherSide({
12996
+ callId: id,
12997
+ methodName,
12998
+ type: TYPE_SERVICE_MESSAGE,
12999
+ arguments: args
13000
+ });
13001
+ });
13002
+ }
13003
+ /**
13004
+ * Respond to remote call
13005
+ * @param id - remote call ID
13006
+ * @param result - result to pass to calling function
13007
+ */
13008
+ responseOtherSide(id, result, success = true) {
13009
+ if (result instanceof Error) result = [...Object.keys(result), "message"].reduce((acc, it) => {
13010
+ acc[it] = result[it];
13011
+ return acc;
13012
+ }, {});
13013
+ const doPost = () => this.postMessage({
13014
+ callId: id,
13015
+ type: TYPE_RESPONSE,
13016
+ success,
13017
+ result
13018
+ }, "*");
13019
+ try {
13020
+ doPost();
13021
+ } catch (err) {
13022
+ console.error("Failed to post response, recovering...", err);
13023
+ if (err instanceof DOMException) {
13024
+ result = JSON.parse(JSON.stringify(result));
13025
+ doPost();
13026
+ }
13027
+ }
13028
+ }
13029
+ registerCallback(successCallback, failureCallback) {
13030
+ const id = (++this.incrementalID).toString();
13031
+ this.callbacks[id] = {
13032
+ successCallback,
13033
+ failureCallback
13034
+ };
13035
+ return id;
13036
+ }
13037
+ /**
13038
+ * Calls and delete stored callback
13039
+ * @param id - call id
13040
+ * @param success - was call successful
13041
+ * @param result - result of remote call
13042
+ */
13043
+ popCallback(id, success, result) {
13044
+ const callback = this.callbacks[id];
13045
+ if (!callback) return;
13046
+ if (success) callback.successCallback(result);
13047
+ else callback.failureCallback(result);
13048
+ delete this.callbacks[id];
13049
+ }
13050
+ }
13051
+ const connection = Connection;
13052
+ var index_js_lib_frame = __webpack_require__(466);
13053
+ var frame_default = /* @__PURE__ */ __webpack_require__.n(index_js_lib_frame);
13054
+ const BaseOptions = {
13055
+ frameContainer: "body",
13056
+ frameClassName: "websandbox__frame",
13057
+ frameSrc: null,
13058
+ frameContent: `
13059
+ <!DOCTYPE html>
13060
+ <html>
13061
+ <head><meta charset="UTF-8"></head>
13062
+ <body></body>
13063
+ </html>
13064
+ `,
13065
+ codeToRunBeforeInit: null,
13066
+ initialStyles: null,
13067
+ baseUrl: null,
13068
+ allowPointerLock: false,
13069
+ allowFullScreen: false,
13070
+ sandboxAdditionalAttributes: ""
13071
+ };
13072
+ class Websandbox {
13073
+ /**
13074
+ * Creates sandbox instancea
13075
+ * @param localApi Api of this side. Will be available for sandboxed code as remoteApi
13076
+ * @param options Options of created sandbox
13077
+ */
13078
+ static create(localApi, options = {}) {
13079
+ return new Websandbox(localApi, options);
13080
+ }
13081
+ /**
13082
+ * {Constructor}
13083
+ * @param localApi
13084
+ * @param options
13085
+ */
13086
+ constructor(localApi, options) {
13087
+ this.connection = null;
13088
+ this.removeMessageListener = () => {};
13089
+ this.validateOptions(options);
13090
+ this.options = Object.assign(Object.assign({}, BaseOptions), options);
13091
+ this.iframe = this.createIframe();
13092
+ this.promise = new Promise((resolve) => {
13093
+ this.connection = new connection(this.iframe.contentWindow.postMessage.bind(this.iframe.contentWindow), (listener) => {
13094
+ const sourceCheckListener = (event) => {
13095
+ if (event.source !== this.iframe.contentWindow) return;
13096
+ return listener(event);
13097
+ };
13098
+ window.addEventListener("message", sourceCheckListener);
13099
+ this.removeMessageListener = () => window.removeEventListener("message", sourceCheckListener);
13100
+ }, { allowedSenderOrigin: "null" });
13101
+ this.connection.setServiceMethods({ iframeInitialized: () => {
13102
+ return this.connection.setLocalApi(localApi).then(() => resolve(this));
13103
+ } });
13104
+ });
13105
+ }
13106
+ validateOptions(options) {
13107
+ var _a;
13108
+ if (options.frameSrc && (options.frameContent || options.initialStyles || options.baseUrl || options.codeToRunBeforeInit)) throw new Error("You can not set both \"frameSrc\" and any of frameContent,initialStyles,baseUrl,codeToRunBeforeInit options");
13109
+ if ("frameContent" in options && !((_a = options.frameContent) === null || _a === void 0 ? void 0 : _a.includes("<head>"))) throw new Error("Websandbox: iFrame content must have \"<head>\" tag.");
13110
+ }
13111
+ _prepareFrameContent(options) {
13112
+ var _a, _b, _c;
13113
+ let frameContent = (_a = options.frameContent) !== null && _a !== void 0 ? _a : "";
13114
+ if (options.codeToRunBeforeInit) frameContent = (_b = frameContent.replace("<head>", `<head>\n<script>${options.codeToRunBeforeInit}<\/script>`)) !== null && _b !== void 0 ? _b : "";
13115
+ frameContent = (_c = frameContent.replace("<head>", `<head>\n<script>${frame_default()}<\/script>`)) !== null && _c !== void 0 ? _c : "";
13116
+ if (options.initialStyles) frameContent = frameContent.replace("</head>", `<style>${options.initialStyles}</style>\n</head>`);
13117
+ if (options.baseUrl) frameContent = frameContent.replace("<head>", `<head>\n<base target="_parent" href="${options.baseUrl}"/>`);
13118
+ return frameContent;
13119
+ }
13120
+ createIframe() {
13121
+ var _a;
13122
+ const containerSelector = this.options.frameContainer;
13123
+ const container = typeof containerSelector === "string" ? document.querySelector(containerSelector) : containerSelector;
13124
+ if (!container) throw new Error("Websandbox: Cannot find container for sandbox " + container);
13125
+ const frame = document.createElement("iframe");
13126
+ frame.sandbox = `allow-scripts ${this.options.sandboxAdditionalAttributes}`;
13127
+ frame.allow = `${this.options.allowAdditionalAttributes}`;
13128
+ frame.className = (_a = this.options.frameClassName) !== null && _a !== void 0 ? _a : "";
13129
+ if (this.options.allowFullScreen) frame.allowFullscreen = true;
13130
+ if (this.options.frameSrc) {
13131
+ frame.src = this.options.frameSrc;
13132
+ container.appendChild(frame);
13133
+ return frame;
13134
+ }
13135
+ frame.setAttribute("srcdoc", this._prepareFrameContent(this.options));
13136
+ container.appendChild(frame);
13137
+ return frame;
13138
+ }
13139
+ destroy() {
13140
+ this.iframe.remove();
13141
+ this.removeMessageListener();
13142
+ }
13143
+ _runCode(code) {
13144
+ return this.connection.callRemoteServiceMethod("runCode", code);
13145
+ }
13146
+ _runFunction(fn) {
13147
+ return this._runCode(`(${fn.toString()})()`);
13148
+ }
13149
+ run(codeOrFunction) {
13150
+ if (codeOrFunction.name) return this._runFunction(codeOrFunction);
13151
+ return this._runCode(codeOrFunction);
13152
+ }
13153
+ importScript(path) {
13154
+ return this.connection.callRemoteServiceMethod("importScript", path);
13155
+ }
13156
+ injectStyle(style) {
13157
+ return this.connection.callRemoteServiceMethod("injectStyle", style);
13158
+ }
13159
+ }
13160
+ const websandbox = Websandbox;
13161
+ })();
13162
+ return __webpack_exports__;
13163
+ })();
13164
+ });
13165
+ }));
13166
+
13167
+ //#endregion
13168
+ //#region src/open-generative-ui/websandbox.ts
13169
+ /**
13170
+ * Imports `@jetbrains/websandbox` on demand. The import is dynamic because
13171
+ * the package touches `self` when it loads, which breaks server rendering.
13172
+ */
13173
+ const loadWebsandbox = async () => {
13174
+ const defaultExport = (await Promise.resolve().then(() => /* @__PURE__ */ __toESM(require_websandbox(), 1))).default;
13175
+ return "default" in defaultExport ? defaultExport.default : defaultExport;
13176
+ };
13177
+
13178
+ //#endregion
13179
+ //#region src/open-generative-ui/controller.ts
13180
+ /** Non-immediate content updates reach the sandbox at most this often. */
13181
+ const OPEN_GENERATIVE_UI_THROTTLE_MS = 1e3;
13182
+ const DEFAULT_HEIGHT = 200;
13183
+ const HIDE_SCROLLBARS = `
13184
+ var s = document.createElement('style');
13185
+ s.textContent = 'html, body { overflow: hidden !important; }';
13186
+ document.head.appendChild(s);
13187
+ `;
13188
+ const HIDE_SCROLLBARS_STYLE = "<style>html, body { overflow: hidden !important; }</style>";
13189
+ const MEASURE_HEIGHT = `
13190
+ (function() {
13191
+ var s = document.createElement('style');
13192
+ s.textContent = 'body { height: auto !important; min-height: 0 !important; }';
13193
+ document.head.appendChild(s);
13194
+ var h = document.body.scrollHeight;
13195
+ var cs = getComputedStyle(document.body);
13196
+ h += parseFloat(cs.marginTop) || 0;
13197
+ h += parseFloat(cs.marginBottom) || 0;
13198
+ s.remove();
13199
+ parent.postMessage({ type: "__ck_resize", height: Math.ceil(h) }, "*");
13200
+ })();
13201
+ `;
13202
+ function deriveContent(content) {
13203
+ var _content$html;
13204
+ const html = ((_content$html = content.html) === null || _content$html === void 0 ? void 0 : _content$html.join("")) || void 0;
13205
+ const css = content.cssComplete ? content.css : void 0;
13206
+ if (content.htmlComplete) return {
13207
+ fullHtml: html,
13208
+ css,
13209
+ previewStyles: ""
13210
+ };
13211
+ const previewBody = html && content.cssComplete ? processPartialHtml(html) : void 0;
13212
+ return {
13213
+ css,
13214
+ previewBody: (previewBody === null || previewBody === void 0 ? void 0 : previewBody.trim()) ? previewBody : void 0,
13215
+ previewStyles: html ? extractCompleteStyles(html) : ""
13216
+ };
13217
+ }
13218
+ function prepareIframe(iframe, testId) {
13219
+ iframe.setAttribute("data-testid", testId);
13220
+ iframe.style.width = "100%";
13221
+ iframe.style.height = "100%";
13222
+ iframe.style.border = "none";
13223
+ iframe.style.backgroundColor = "transparent";
13224
+ }
13225
+ function logLoadError(error) {
13226
+ console.error("[OpenGenerativeUI] Failed to load sandbox module:", error);
13227
+ }
13228
+ function sameFunctions(a, b) {
13229
+ return a.length === b.length && a.every((fn, i) => fn.name === b[i].name && fn.handler === b[i].handler);
13230
+ }
13231
+ var _load = /* @__PURE__ */ new WeakMap();
13232
+ var _listeners = /* @__PURE__ */ new WeakMap();
13233
+ var _content = /* @__PURE__ */ new WeakMap();
13234
+ var _latest = /* @__PURE__ */ new WeakMap();
13235
+ var _derived = /* @__PURE__ */ new WeakMap();
13236
+ var _timer = /* @__PURE__ */ new WeakMap();
13237
+ var _host = /* @__PURE__ */ new WeakMap();
13238
+ var _functions = /* @__PURE__ */ new WeakMap();
13239
+ var _localApi = /* @__PURE__ */ new WeakMap();
13240
+ var _preview = /* @__PURE__ */ new WeakMap();
13241
+ var _final = /* @__PURE__ */ new WeakMap();
13242
+ var _measuredHeight = /* @__PURE__ */ new WeakMap();
13243
+ var _state = /* @__PURE__ */ new WeakMap();
13244
+ var _OpenGenerativeUIController_brand = /* @__PURE__ */ new WeakSet();
13245
+ /**
13246
+ * Runs Open Generative UI content in websandbox iframes inside a host element.
13247
+ *
13248
+ * Give it content snapshots with `setContent()` and a host element with
13249
+ * `setHost()`. It throttles the snapshots, streams a preview while HTML
13250
+ * arrives, swaps in the final sandbox once HTML is complete, runs
13251
+ * `jsFunctions` and `jsExpressions` in it once each, and measures the final
13252
+ * height. Frameworks render the container from `getState()` and re-render
13253
+ * when `subscribe()` notifies.
13254
+ *
13255
+ * @example
13256
+ * ```ts
13257
+ * const controller = new ɵOpenGenerativeUIController();
13258
+ * controller.subscribe(() => render(controller.getState()));
13259
+ * controller.setContent(content);
13260
+ * controller.setHost(containerElement);
13261
+ * // On unmount:
13262
+ * controller.destroy();
13263
+ * ```
13264
+ */
13265
+ var OpenGenerativeUIController = class {
13266
+ constructor(options = {}) {
13267
+ var _options$loadWebsandb;
13268
+ _classPrivateMethodInitSpec(this, _OpenGenerativeUIController_brand);
13269
+ _classPrivateFieldInitSpec(this, _load, void 0);
13270
+ _classPrivateFieldInitSpec(this, _listeners, /* @__PURE__ */ new Set());
13271
+ _classPrivateFieldInitSpec(this, _content, void 0);
13272
+ _classPrivateFieldInitSpec(this, _latest, void 0);
13273
+ _classPrivateFieldInitSpec(this, _derived, { previewStyles: "" });
13274
+ _classPrivateFieldInitSpec(this, _timer, void 0);
13275
+ _classPrivateFieldInitSpec(this, _host, null);
13276
+ _classPrivateFieldInitSpec(this, _functions, []);
13277
+ _classPrivateFieldInitSpec(this, _localApi, {});
13278
+ _classPrivateFieldInitSpec(this, _preview, void 0);
13279
+ _classPrivateFieldInitSpec(this, _final, void 0);
13280
+ _classPrivateFieldInitSpec(this, _measuredHeight, void 0);
13281
+ _classPrivateFieldInitSpec(this, _state, {
13282
+ phase: "placeholder",
13283
+ generating: true,
13284
+ height: DEFAULT_HEIGHT
13285
+ });
13286
+ _defineProperty(
13287
+ this,
13288
+ /** The current state. The same object until something changes. */
13289
+ "getState",
13290
+ () => _classPrivateFieldGet2(_state, this)
13291
+ );
13292
+ _defineProperty(
13293
+ this,
13294
+ /** Calls `listener` when the state changes. Returns the unsubscribe function. */
13295
+ "subscribe",
13296
+ (listener) => {
13297
+ _classPrivateFieldGet2(_listeners, this).add(listener);
13298
+ return () => {
13299
+ _classPrivateFieldGet2(_listeners, this).delete(listener);
13300
+ };
13301
+ }
13302
+ );
13303
+ _classPrivateFieldSet2(_load, this, (_options$loadWebsandb = options.loadWebsandbox) !== null && _options$loadWebsandb !== void 0 ? _options$loadWebsandb : loadWebsandbox);
13304
+ }
13305
+ /**
13306
+ * Sets the latest content snapshot. The first snapshot and snapshots that
13307
+ * finish a stage apply at once; others apply at most once per second.
13308
+ */
13309
+ setContent(content) {
13310
+ _classPrivateFieldSet2(_latest, this, content);
13311
+ if (_classPrivateFieldGet2(_content, this) === void 0 || shouldFlushImmediately(_classPrivateFieldGet2(_content, this), content)) {
13312
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _clearTimer).call(this);
13313
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _commit).call(this, content);
13314
+ return;
13315
+ }
13316
+ if (content === _classPrivateFieldGet2(_content, this) || _classPrivateFieldGet2(_timer, this) !== void 0) return;
13317
+ _classPrivateFieldSet2(_timer, this, setTimeout(() => {
13318
+ _classPrivateFieldSet2(_timer, this, void 0);
13319
+ if (_classPrivateFieldGet2(_latest, this)) _assertClassBrand(_OpenGenerativeUIController_brand, this, _commit).call(this, _classPrivateFieldGet2(_latest, this));
13320
+ }, OPEN_GENERATIVE_UI_THROTTLE_MS));
13321
+ }
13322
+ /** Sets the element the sandbox iframes go into. `null` removes them. */
13323
+ setHost(host) {
13324
+ if (host === _classPrivateFieldGet2(_host, this)) return;
13325
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _destroyPreview).call(this);
13326
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _destroyFinal).call(this);
13327
+ _classPrivateFieldSet2(_host, this, host);
13328
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _reconcile).call(this);
13329
+ }
13330
+ /**
13331
+ * Sets the host functions sandboxed code can call. A change recreates the
13332
+ * final sandbox.
13333
+ */
13334
+ setSandboxFunctions(functions) {
13335
+ if (sameFunctions(functions, _classPrivateFieldGet2(_functions, this))) return;
13336
+ _classPrivateFieldSet2(_functions, this, functions);
13337
+ const localApi = {};
13338
+ for (const fn of functions) localApi[fn.name] = fn.handler;
13339
+ _classPrivateFieldSet2(_localApi, this, localApi);
13340
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _reconcile).call(this);
13341
+ }
13342
+ /**
13343
+ * Removes the sandboxes and stops pending work. A later `setHost()`
13344
+ * starts again from the current content.
13345
+ */
13346
+ destroy() {
13347
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _clearTimer).call(this);
13348
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _destroyPreview).call(this);
13349
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _destroyFinal).call(this);
13350
+ _classPrivateFieldSet2(_host, this, null);
13351
+ }
13352
+ };
13353
+ function _commit(content) {
13354
+ if (content === _classPrivateFieldGet2(_content, this)) return;
13355
+ _classPrivateFieldSet2(_content, this, content);
13356
+ _classPrivateFieldSet2(_derived, this, deriveContent(content));
13357
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _reconcile).call(this);
13358
+ }
13359
+ function _reconcile() {
13360
+ const host = _classPrivateFieldGet2(_host, this);
13361
+ const content = _classPrivateFieldGet2(_content, this);
13362
+ const derived = _classPrivateFieldGet2(_derived, this);
13363
+ if (host && content) if (derived.fullHtml) {
13364
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _destroyPreview).call(this);
13365
+ const frameContent = buildFinalFrameContent(derived.fullHtml, derived.css);
13366
+ let final = _classPrivateFieldGet2(_final, this);
13367
+ if ((final === null || final === void 0 ? void 0 : final.frameContent) !== frameContent || final.localApi !== _classPrivateFieldGet2(_localApi, this)) {
13368
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _destroyFinal).call(this);
13369
+ final = _classPrivateFieldSet2(_final, this, _assertClassBrand(_OpenGenerativeUIController_brand, this, _createFinal).call(this, host, frameContent));
13370
+ }
13371
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _runScripts).call(this, final, content);
13372
+ } else {
13373
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _destroyFinal).call(this);
13374
+ if (derived.previewBody) {
13375
+ var _classPrivateFieldGet2$1;
13376
+ (_classPrivateFieldGet2$1 = _classPrivateFieldGet2(_preview, this)) !== null && _classPrivateFieldGet2$1 !== void 0 || _classPrivateFieldSet2(_preview, this, _assertClassBrand(_OpenGenerativeUIController_brand, this, _createPreview).call(this, host));
13377
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _writePreview).call(this);
13378
+ } else _assertClassBrand(_OpenGenerativeUIController_brand, this, _destroyPreview).call(this);
13379
+ }
13380
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _updateState).call(this);
13381
+ }
13382
+ function _createPreview(host) {
13383
+ const slot = {
13384
+ ready: false,
13385
+ cancelled: false
13386
+ };
13387
+ _classPrivateFieldGet2(_load, this).call(this).then((Websandbox) => {
13388
+ if (slot.cancelled) return;
13389
+ const sandbox = Websandbox.create({}, {
13390
+ frameContainer: host,
13391
+ frameContent: "<head></head><body></body>",
13392
+ allowAdditionalAttributes: ""
13393
+ });
13394
+ slot.sandbox = sandbox;
13395
+ prepareIframe(sandbox.iframe, "open-generative-ui-preview-sandbox");
13396
+ sandbox.promise.then(() => {
13397
+ if (slot.cancelled) return;
13398
+ slot.ready = true;
13399
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _writePreview).call(this);
13400
+ });
13401
+ }).catch(logLoadError);
13402
+ return slot;
13403
+ }
13404
+ function _writePreview() {
13405
+ const slot = _classPrivateFieldGet2(_preview, this);
13406
+ if (!(slot === null || slot === void 0 ? void 0 : slot.sandbox) || !slot.ready) return;
13407
+ const { css, previewStyles, previewBody } = _classPrivateFieldGet2(_derived, this);
13408
+ const head = HIDE_SCROLLBARS_STYLE + (css ? `<style>${css}</style>` : "") + previewStyles;
13409
+ if (head !== slot.head) {
13410
+ slot.head = head;
13411
+ slot.sandbox.run(`document.head.innerHTML = ${JSON.stringify(head)}`);
13412
+ }
13413
+ if (previewBody && previewBody !== slot.body) {
13414
+ slot.body = previewBody;
13415
+ slot.sandbox.run(`document.body.innerHTML = ${JSON.stringify(previewBody)}`);
13416
+ }
13417
+ }
13418
+ function _createFinal(host, frameContent) {
13419
+ const slot = {
13420
+ frameContent,
13421
+ localApi: _classPrivateFieldGet2(_localApi, this),
13422
+ ready: false,
13423
+ cancelled: false,
13424
+ queue: [],
13425
+ jsFunctionsInjected: false,
13426
+ executedExpressions: 0,
13427
+ heightRequested: false
13428
+ };
13429
+ _classPrivateFieldGet2(_load, this).call(this).then((Websandbox) => {
13430
+ if (slot.cancelled) return;
13431
+ const sandbox = Websandbox.create(slot.localApi, {
13432
+ frameContainer: host,
13433
+ frameContent,
13434
+ allowAdditionalAttributes: ""
13435
+ });
13436
+ slot.sandbox = sandbox;
13437
+ prepareIframe(sandbox.iframe, "open-generative-ui-final-sandbox");
13438
+ sandbox.promise.then(() => {
13439
+ if (slot.cancelled) return;
13440
+ slot.ready = true;
13441
+ sandbox.run(HIDE_SCROLLBARS);
13442
+ const queue = slot.queue;
13443
+ slot.queue = [];
13444
+ for (const code of queue) sandbox.run(code);
13445
+ });
13446
+ }).catch(logLoadError);
13447
+ return slot;
13448
+ }
13449
+ /** Runs new `jsFunctions`, new `jsExpressions`, and the height measurement. */
13450
+ function _runScripts(slot, content) {
13451
+ var _content$jsExpression;
13452
+ if (content.jsFunctions && !slot.jsFunctionsInjected) {
13453
+ slot.jsFunctionsInjected = true;
13454
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _runOrQueue).call(this, slot, content.jsFunctions);
13455
+ }
13456
+ const expressions = (_content$jsExpression = content.jsExpressions) !== null && _content$jsExpression !== void 0 ? _content$jsExpression : [];
13457
+ if (expressions.length > slot.executedExpressions) {
13458
+ const newExpressions = expressions.slice(slot.executedExpressions);
13459
+ slot.executedExpressions = expressions.length;
13460
+ const sandbox = slot.sandbox;
13461
+ if (slot.ready && sandbox) (async () => {
13462
+ for (const expression of newExpressions) await sandbox.run(expression);
13463
+ })();
13464
+ else slot.queue.push(...newExpressions);
13465
+ }
13466
+ if (content.generating === false && !slot.heightRequested) {
13467
+ slot.heightRequested = true;
13468
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _listenForHeight).call(this, slot);
13469
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _runOrQueue).call(this, slot, MEASURE_HEIGHT);
13470
+ }
13471
+ }
13472
+ function _runOrQueue(slot, code) {
13473
+ if (slot.ready && slot.sandbox) slot.sandbox.run(code);
13474
+ else slot.queue.push(code);
13475
+ }
13476
+ function _listenForHeight(slot) {
13477
+ if (typeof window === "undefined") return;
13478
+ const onMessage = (event) => {
13479
+ var _slot$stopHeightListe;
13480
+ const data = event.data;
13481
+ if (!slot.sandbox || event.source !== slot.sandbox.iframe.contentWindow || (data === null || data === void 0 ? void 0 : data.type) !== "__ck_resize" || typeof data.height !== "number") return;
13482
+ (_slot$stopHeightListe = slot.stopHeightListener) === null || _slot$stopHeightListe === void 0 || _slot$stopHeightListe.call(slot);
13483
+ _classPrivateFieldSet2(_measuredHeight, this, data.height);
13484
+ _assertClassBrand(_OpenGenerativeUIController_brand, this, _updateState).call(this);
13485
+ };
13486
+ window.addEventListener("message", onMessage);
13487
+ slot.stopHeightListener = () => {
13488
+ window.removeEventListener("message", onMessage);
13489
+ slot.stopHeightListener = void 0;
13490
+ };
13491
+ }
13492
+ function _destroyPreview() {
13493
+ var _slot$sandbox;
13494
+ const slot = _classPrivateFieldGet2(_preview, this);
13495
+ if (!slot) return;
13496
+ slot.cancelled = true;
13497
+ (_slot$sandbox = slot.sandbox) === null || _slot$sandbox === void 0 || _slot$sandbox.destroy();
13498
+ _classPrivateFieldSet2(_preview, this, void 0);
13499
+ }
13500
+ function _destroyFinal() {
13501
+ var _slot$stopHeightListe2, _slot$sandbox2;
13502
+ const slot = _classPrivateFieldGet2(_final, this);
13503
+ if (!slot) return;
13504
+ slot.cancelled = true;
13505
+ (_slot$stopHeightListe2 = slot.stopHeightListener) === null || _slot$stopHeightListe2 === void 0 || _slot$stopHeightListe2.call(slot);
13506
+ (_slot$sandbox2 = slot.sandbox) === null || _slot$sandbox2 === void 0 || _slot$sandbox2.destroy();
13507
+ _classPrivateFieldSet2(_final, this, void 0);
13508
+ _classPrivateFieldSet2(_measuredHeight, this, void 0);
13509
+ }
13510
+ function _clearTimer() {
13511
+ if (_classPrivateFieldGet2(_timer, this) === void 0) return;
13512
+ clearTimeout(_classPrivateFieldGet2(_timer, this));
13513
+ _classPrivateFieldSet2(_timer, this, void 0);
13514
+ }
13515
+ function _updateState() {
13516
+ var _this$content, _ref, _this$measuredHeight;
13517
+ const content = (_this$content = _classPrivateFieldGet2(_content, this)) !== null && _this$content !== void 0 ? _this$content : {};
13518
+ const derived = _classPrivateFieldGet2(_derived, this);
13519
+ const next = {
13520
+ phase: derived.fullHtml ? "final" : derived.previewBody ? "preview" : "placeholder",
13521
+ generating: content.generating !== false,
13522
+ height: (_ref = (_this$measuredHeight = _classPrivateFieldGet2(_measuredHeight, this)) !== null && _this$measuredHeight !== void 0 ? _this$measuredHeight : content.initialHeight) !== null && _ref !== void 0 ? _ref : DEFAULT_HEIGHT
13523
+ };
13524
+ const current = _classPrivateFieldGet2(_state, this);
13525
+ if (next.phase === current.phase && next.generating === current.generating && next.height === current.height) return;
13526
+ _classPrivateFieldSet2(_state, this, next);
13527
+ for (const listener of _classPrivateFieldGet2(_listeners, this)) listener();
13528
+ }
13529
+
12664
13530
  //#endregion
12665
13531
  exports.A2UI_FENCE_LANGUAGE = A2UI_FENCE_LANGUAGE;
12666
13532
  exports.AgentRegistry = AgentRegistry;
@@ -12671,11 +13537,14 @@ exports.CopilotKitCore = CopilotKitCore;
12671
13537
  exports.CopilotKitCoreErrorCode = CopilotKitCoreErrorCode;
12672
13538
  exports.CopilotKitCoreRuntimeConnectionStatus = CopilotKitCoreRuntimeConnectionStatus;
12673
13539
  exports.CopilotKitHeaderResolutionError = CopilotKitHeaderResolutionError;
13540
+ exports.DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL = DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL;
13541
+ exports.GENERATE_SANDBOXED_UI_TOOL_NAME = GENERATE_SANDBOXED_UI_TOOL_NAME;
12674
13542
  exports.INSPECTOR_THREAD_BRIDGE_PLUGIN_ID = INSPECTOR_THREAD_BRIDGE_PLUGIN_ID;
12675
13543
  exports.INTERRUPT_EVENT_NAME = INTERRUPT_EVENT_NAME;
12676
13544
  exports.IntelligenceAgent = IntelligenceAgent;
12677
13545
  exports.MEMORY_ERROR_REGISTRY = MEMORY_ERROR_REGISTRY;
12678
13546
  exports.MemoryError = MemoryError;
13547
+ exports.OPEN_GENERATIVE_UI_ACTIVITY_TYPE = OPEN_GENERATIVE_UI_ACTIVITY_TYPE;
12679
13548
  exports.ProxiedCopilotRuntimeAgent = ProxiedCopilotRuntimeAgent;
12680
13549
  exports.RunHandler = RunHandler;
12681
13550
  exports.StateManager = StateManager;
@@ -12722,6 +13591,7 @@ exports.splitA2UIMarkdown = splitA2UIMarkdown;
12722
13591
  exports.ɵCOPILOTKIT_FEATURES = ɵCOPILOTKIT_FEATURES;
12723
13592
  exports.ɵInterruptState = ɵInterruptState;
12724
13593
  exports.ɵMAX_SOCKET_RETRIES = ɵMAX_SOCKET_RETRIES;
13594
+ exports.ɵOpenGenerativeUIController = OpenGenerativeUIController;
12725
13595
  exports.ɵRUNTIME_PROBE_TIMEOUT_MS = ɵRUNTIME_PROBE_TIMEOUT_MS;
12726
13596
  exports.ɵTHREAD_REQUEST_TIMEOUT_MS = ɵTHREAD_REQUEST_TIMEOUT_MS;
12727
13597
  exports.ɵclearAgentInterruptState = ɵclearAgentInterruptState;
@@ -12733,6 +13603,7 @@ exports.ɵcreateMemoryStore = createMemoryStore;
12733
13603
  exports.ɵcreateThreadSelectors = ɵcreateThreadSelectors;
12734
13604
  exports.ɵcreateThreadStore = createThreadStore;
12735
13605
  exports.ɵdeduplicateMessages = ɵdeduplicateMessages;
13606
+ exports.ɵextractCompleteStyles = extractCompleteStyles;
12736
13607
  exports.ɵformatCountLabel = ɵformatCountLabel;
12737
13608
  exports.ɵformatLabel = ɵformatLabel;
12738
13609
  exports.ɵformatReasoningDuration = formatReasoningDuration;
@@ -12754,6 +13625,7 @@ exports.ɵisRetryableMemoryStatus = isRetryableStatus;
12754
13625
  exports.ɵisTurnWorkOpen = isTurnWorkOpen;
12755
13626
  exports.ɵisTurnWorking = isTurnWorking;
12756
13627
  exports.ɵjoinPhoenixChannel$ = ɵjoinPhoenixChannel$;
13628
+ exports.ɵloadWebsandbox = loadWebsandbox;
12757
13629
  exports.ɵmapMemoryMetadataEvent = ɵmapMemoryMetadataEvent;
12758
13630
  exports.ɵmemoryAdapterEvents = ɵmemoryAdapterEvents;
12759
13631
  exports.ɵmemoryDomainEvents = ɵmemoryDomainEvents;
@@ -12767,6 +13639,7 @@ exports.ɵobservePhoenixSocketSignals$ = ɵobservePhoenixSocketSignals$;
12767
13639
  exports.ɵphoenixChannel$ = ɵphoenixChannel$;
12768
13640
  exports.ɵphoenixSocket$ = ɵphoenixSocket$;
12769
13641
  exports.ɵpluralize = pluralize;
13642
+ exports.ɵprocessPartialHtml = processPartialHtml;
12770
13643
  exports.ɵrecordWorkTime = recordWorkTime;
12771
13644
  exports.ɵresolveActivityRenderer = ɵresolveActivityRenderer;
12772
13645
  exports.ɵresolveComposerKey = ɵresolveComposerKey;