cozyclay 3.0.1 → 3.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/THIRD_PARTY_NOTICES.md +10 -0
  3. package/bin/agent/pi-tools.mjs +12 -1
  4. package/bin/agent/studio-context-budget.mjs +8 -2
  5. package/bin/agent/studio-prompt.mjs +1 -1
  6. package/bin/agent/studio-tools.mjs +1 -1
  7. package/dist/app/index.html +4 -4
  8. package/dist/assets/analytics-DbKG0NgD.js +6 -0
  9. package/dist/assets/app-34i-iUy1.js +5088 -0
  10. package/dist/assets/compile-worker-DYpa2nvO.js +5 -0
  11. package/dist/assets/{first-shot-handoff-DNO8kv_N.js → first-shot-handoff-CrGZ3n_O.js} +1 -1
  12. package/dist/assets/helvetiker-bold.typeface-BUlyMz0-.js +13 -0
  13. package/dist/assets/{landing-yfZaJkWc.js → landing-mq5bnqFE.js} +1 -1
  14. package/dist/assets/scene-asset-sync-7J-w5oNh.js +20 -0
  15. package/dist/assets/{workflow-D78eiKTa.js → workflow-dUhurYUc.js} +1 -1
  16. package/dist/cozyclay-package.json +1 -1
  17. package/dist/index.html +3 -3
  18. package/dist/workflow/index.html +3 -3
  19. package/package.json +1 -1
  20. package/src/agent-turn-mark.js +33 -0
  21. package/src/command-bus.js +8 -9
  22. package/src/commands/elements/character.js +2 -1
  23. package/src/commands/elements/motion.js +7 -1
  24. package/src/commands/elements/scene.js +3 -0
  25. package/src/commands/elements/stage.js +2 -1
  26. package/src/commands/elements/take-read.js +31 -0
  27. package/src/commands/elements.js +16 -2
  28. package/src/commands/motion3.js +3 -1
  29. package/src/commands/objects.js +2 -2
  30. package/src/motion3/compiler/anchors.js +60 -4
  31. package/src/motion3/compiler/compile.js +5 -1
  32. package/src/motion3/compiler/grip.js +8 -2
  33. package/src/motion3/compiler/socket-grip.js +107 -0
  34. package/src/motion3/compiler/validate-parts.js +7 -2
  35. package/src/motion3/compiler/vocab.js +6 -0
  36. package/src/motion3/free-motion.js +12 -4
  37. package/src/motion3/object-keys.js +36 -5
  38. package/src/motion3/object-pose.js +38 -5
  39. package/src/motion3/scene.js +4 -3
  40. package/src/motion3/schema/fields.js +1 -1
  41. package/src/motion3/schema/topics.js +3 -2
  42. package/src/motion3/schema/types.js +2 -2
  43. package/src/motion3/skills/basic.js +8 -2
  44. package/src/motion3/skills/info.js +4 -4
  45. package/src/motion3/sockets.js +104 -0
  46. package/src/motion3/take-edit.js +1 -1
  47. package/src/motion3/take.js +6 -4
  48. package/src/object-catalog.jsx +3 -1
  49. package/src/object-grasp.js +38 -0
  50. package/src/object-look.js +2 -0
  51. package/src/object-travel.js +6 -3
  52. package/src/panels/ObjectLookPanel.jsx +24 -3
  53. package/src/props.jsx +5 -5
  54. package/src/scene-objects.js +19 -11
  55. package/src/shell/details-selection.js +2 -1
  56. package/src/studio-agent-protocol.js +5 -6
  57. package/src/studio-app-binding.js +1 -1
  58. package/src/studio-elements.js +3 -1
  59. package/src/text/fonts/helvetiker-LICENSE.txt +13 -0
  60. package/src/text/fonts/helvetiker-bold.typeface.json +1 -0
  61. package/src/text/text-object.jsx +106 -0
  62. package/src/text/text-record.js +122 -0
  63. package/tools/run-tests.mjs +1 -1
  64. package/dist/assets/analytics-BWCqdgWA.js +0 -1
  65. package/dist/assets/app-DfTCxaKk.js +0 -5087
  66. package/dist/assets/compile-worker-BxKXh07s.js +0 -5
  67. package/dist/assets/scene-asset-sync-U3kS2rvK.js +0 -20
@@ -0,0 +1,122 @@
1
+ /**
2
+ * The `object.text` record: words standing in the set (a sign, a logo on a
3
+ * truck's side). Pure data and clamps, shared by the object store, the agent
4
+ * schema and the renderer (text-object.jsx).
5
+ *
6
+ * The record's box is measured from the words, never stored as a fact: x is
7
+ * the centre, y = 0 the bottom of the lowest line, the letters face +z and
8
+ * read toward +x. `size` is the height of a capital letter in metres.
9
+ * `depth` 0 draws flat lettering in any script; above 0 the letters are
10
+ * solid, extruded from the bundled typeface (Latin, digits, punctuation);
11
+ * words with other characters stay flat.
12
+ */
13
+ import { GREY_BOX } from "../object-colors.js";
14
+
15
+ export const TEXT_KIND = "text";
16
+
17
+ /** Advance widths of the bundled typeface (fonts/helvetiker-bold.typeface.json,
18
+ * `ha` per glyph at resolution 1000, where a capital is 1013 tall) for the
19
+ * printable ASCII characters 32..126. test/verify-text-object.mjs checks them
20
+ * against the font file. */
21
+ const ASCII_ADVANCE = [375, 307, 454, 1117, 800, 1213, 1007, 289, 486, 486, 828, 828, 303, 525, 303, 828, 828, 828, 828, 828, 828, 828, 828, 828, 828, 828, 304, 306, 828, 828, 828, 785, 1374, 1069, 938, 1043, 968, 824, 778, 1057, 953, 365, 760, 996, 763, 1135, 949, 1094, 838, 1096, 947, 915, 894, 926, 997, 1399, 999, 931, 906, 444, 532, 446, 828, 828, 288, 786, 822, 828, 836, 808, 525, 839, 782, 326, 361, 771, 363, 1174, 782, 871, 824, 833, 513, 775, 511, 782, 828, 1150, 826, 828, 753, 599, 240, 597, 949];
22
+ /** The font's units per size (a capital is ~1 size tall), and the extent of
23
+ * its ASCII glyphs above and below the baseline. */
24
+ export const TEXT_FONT = Object.freeze({ resolution: 1000, ascent: 1090, descent: 333 });
25
+ /** Baseline to baseline, in sizes. */
26
+ export const TEXT_LINE_PITCH = 1.5;
27
+ /** A wide (CJK, Hangul) character and any other character the font lacks, in sizes. */
28
+ const WIDE_ADVANCE = 1.25, OTHER_ADVANCE = 0.8;
29
+ /** Flat lettering is a card this thick (m): enough for a footprint and a pick. */
30
+ export const TEXT_FLAT_DEPTH = 0.005;
31
+
32
+ const LIMITS = { size: [0.02, 10], depth: [0, 2] };
33
+ const MAX_CHARS = 200, MAX_LINES = 8;
34
+ const ALIGNS = ["left", "center", "right"];
35
+ const DEFAULT_TEXT = Object.freeze({ value: "Text", size: 0.3, depth: 0, align: "center" });
36
+
37
+ export const TEXT_ENTRY = { kind: TEXT_KIND, label: "Text", group: "Text", footprint: { width: 1, depth: TEXT_FLAT_DEPTH }, height: 0.3, color: GREY_BOX };
38
+
39
+ /** The value schema the agent's object.set and object.add carry. */
40
+ export const TEXT_VALUE_SCHEMA = Object.freeze({
41
+ type: "object",
42
+ properties: {
43
+ value: { type: "string", minLength: 1, maxLength: MAX_CHARS },
44
+ size: { type: "number", minimum: LIMITS.size[0], maximum: LIMITS.size[1] },
45
+ depth: { type: "number", minimum: LIMITS.depth[0], maximum: LIMITS.depth[1] },
46
+ align: { type: "string", enum: ALIGNS },
47
+ },
48
+ required: [],
49
+ additionalProperties: false,
50
+ });
51
+
52
+ const clampTo = ([min, max], value, fallback) => {
53
+ const n = Number(value);
54
+ return Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : fallback;
55
+ };
56
+
57
+ /** The stored text: every field present and repaired. Up to MAX_LINES lines of
58
+ * MAX_CHARS characters in all; blank words fall back to the default. */
59
+ export function normalizeText(value) {
60
+ const given = value && typeof value === "object" && !Array.isArray(value) ? value : {};
61
+ const lines = typeof given.value === "string" ? given.value.replace(/\r\n?/g, "\n").split("\n").slice(0, MAX_LINES) : [];
62
+ const words = [...lines.join("\n")].slice(0, MAX_CHARS).join("");
63
+ return {
64
+ value: words.trim() ? words : DEFAULT_TEXT.value,
65
+ size: clampTo(LIMITS.size, given.size, DEFAULT_TEXT.size),
66
+ depth: clampTo(LIMITS.depth, given.depth, DEFAULT_TEXT.depth),
67
+ align: ALIGNS.includes(given.align) ? given.align : DEFAULT_TEXT.align,
68
+ };
69
+ }
70
+
71
+ const isWide = (code) => (code >= 0x1100 && code <= 0x11ff) || (code >= 0x2e80 && code <= 0xa4cf) || (code >= 0xac00 && code <= 0xd7af) || (code >= 0xf900 && code <= 0xfaff) || (code >= 0xff00 && code <= 0xffef);
72
+
73
+ /** One character's advance in sizes. */
74
+ function advance(char) {
75
+ const code = char.codePointAt(0);
76
+ if (code >= 32 && code <= 126) return ASCII_ADVANCE[code - 32] / TEXT_FONT.resolution;
77
+ return isWide(code) ? WIDE_ADVANCE : OTHER_ADVANCE;
78
+ }
79
+
80
+ /** True when the bundled typeface draws every character (solid letters). */
81
+ export function textIsSolid(text) {
82
+ return text.depth > 0 && [...text.value].every((char) => char === "\n" || (char.codePointAt(0) >= 32 && char.codePointAt(0) <= 126));
83
+ }
84
+
85
+ /**
86
+ * Where each line sits, in metres: `width` of the widest line, `height` from
87
+ * the lowest line's descender to the top line's ascender, and per line its
88
+ * text, its left edge x (the box is centred on x = 0) and its baseline y.
89
+ */
90
+ export function textLayout(text) {
91
+ const { size, align } = text;
92
+ const lines = text.value.split("\n");
93
+ const widths = lines.map((line) => [...line].reduce((sum, char) => sum + advance(char), 0) * size);
94
+ const width = Math.max(...widths, size * 0.2);
95
+ const descent = (TEXT_FONT.descent / TEXT_FONT.resolution) * size;
96
+ const height = (lines.length - 1) * TEXT_LINE_PITCH * size + ((TEXT_FONT.ascent + TEXT_FONT.descent) / TEXT_FONT.resolution) * size;
97
+ const rows = lines.map((line, i) => ({
98
+ text: line,
99
+ width: widths[i],
100
+ x: align === "left" ? -width / 2 : align === "right" ? width / 2 - widths[i] : -widths[i] / 2,
101
+ baseline: descent + (lines.length - 1 - i) * TEXT_LINE_PITCH * size,
102
+ }));
103
+ return { width, height, rows };
104
+ }
105
+
106
+ /** The record fields a text carries (none for any other renderer): the
107
+ * repaired words and the box measured from them, which override the entry's. */
108
+ export function textFields(record) {
109
+ if (record?.renderer !== TEXT_KIND) return {};
110
+ const text = normalizeText(record.text);
111
+ const { width, height } = textLayout(text);
112
+ const round = (n) => Number(n.toFixed(4));
113
+ return { text, footprint: { width: round(width), depth: round(Math.max(text.depth, TEXT_FLAT_DEPTH)) }, height: round(height), supportY: round(height) };
114
+ }
115
+
116
+ /** An update patch's `text` merged over the record's own and re-measured, or
117
+ * nothing when the record is no text or the words do not change. */
118
+ export function textPatch(object, patch) {
119
+ if (object?.renderer !== TEXT_KIND || patch?.text === undefined || !patch.text || typeof patch.text !== "object") return {};
120
+ const fields = textFields({ renderer: TEXT_KIND, text: { ...object.text, ...patch.text } });
121
+ return JSON.stringify(fields.text) === JSON.stringify(object.text) ? {} : fields;
122
+ }
@@ -14,7 +14,7 @@ if (!process.env.COZYCLAY_AGENT_SESSIONS_DIR) {
14
14
  }
15
15
 
16
16
  const NODE_FILES = [
17
- "test/motion3/verify-motion3-core.mjs", "test/motion3/verify-motion3-idle.mjs", "test/motion3/verify-motion3-flip.mjs", "test/motion3/verify-motion3-timing.mjs", "test/motion3/verify-motion3-self.mjs", "test/motion3/verify-motion3-commands.mjs", "test/motion3/verify-motion3-exitcar.mjs", "test/motion3/verify-motion3-agentloop.mjs", "test/motion3/verify-motion3-search.mjs", "test/motion3/verify-motion3-skills.mjs", "test/motion3/verify-motion3-carried.mjs", "test/motion3/verify-motion3-people.mjs", "test/motion3/verify-motion3-hit.mjs", "test/motion3/verify-motion3-contracts.mjs", "test/motion3/verify-motion3-describe.mjs", "test/motion3/verify-motion3-timeline.mjs", "test/motion3/verify-motion3-probes.mjs", "test/motion3/verify-motion3-grab.mjs", "test/motion3/verify-motion3-patch.mjs", "test/motion3/verify-motion3-repair.mjs", "test/motion3/verify-motion3-specstore.mjs", "test/motion3/verify-motion3-visual.mjs", "test/motion3/verify-motion3-goals.mjs", "test/motion3/verify-motion3-prompt.mjs", "test/motion3/verify-motion3-cup.mjs", "test/verify-proxy-figure.mjs",
17
+ "test/motion3/verify-motion3-core.mjs", "test/motion3/verify-motion3-idle.mjs", "test/motion3/verify-motion3-flip.mjs", "test/motion3/verify-motion3-timing.mjs", "test/motion3/verify-motion3-self.mjs", "test/motion3/verify-motion3-commands.mjs", "test/motion3/verify-motion3-exitcar.mjs", "test/motion3/verify-motion3-agentloop.mjs", "test/motion3/verify-motion3-search.mjs", "test/motion3/verify-motion3-skills.mjs", "test/motion3/verify-motion3-carried.mjs", "test/motion3/verify-motion3-people.mjs", "test/motion3/verify-motion3-hit.mjs", "test/motion3/verify-motion3-socket.mjs", "test/motion3/verify-motion3-contracts.mjs", "test/motion3/verify-motion3-describe.mjs", "test/motion3/verify-motion3-timeline.mjs", "test/motion3/verify-motion3-probes.mjs", "test/motion3/verify-motion3-grab.mjs", "test/motion3/verify-motion3-grab-blend.mjs", "test/motion3/verify-motion3-patch.mjs", "test/motion3/verify-motion3-repair.mjs", "test/motion3/verify-motion3-specstore.mjs", "test/motion3/verify-motion3-visual.mjs", "test/motion3/verify-motion3-goals.mjs", "test/motion3/verify-motion3-prompt.mjs", "test/motion3/verify-motion3-cup.mjs", "test/verify-proxy-figure.mjs", "test/verify-text-object.mjs",
18
18
  "test/verify-proxy-figure-bounds.mjs",
19
19
  "test/verify-character-capabilities.mjs",
20
20
  "test/verify-root-path.mjs",
@@ -1 +0,0 @@
1
- (function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e=.02,t=(e,t,n)=>Math.min(n,Math.max(t,e)),n=(e,t=0)=>typeof e==`number`&&Number.isFinite(e)?e:t;function r(e){let t=0;for(let n=0;n<e.length-1;n+=1)t+=(e[n]+e[n+1])/2;return t}function i(e,n){let r=t(n,0,1)*(e.length-1),i=Math.min(e.length-2,Math.floor(r)),a=r-i;return e[i]*(1-a)+e[i+1]*a}function a(e,t=24){if(!e.length)return Array(t).fill(1);if(e.length===1)return Array(t).fill(e[0]);let n=Array(t);for(let r=0;r<t;r+=1)n[r]=i(e,r/(t-1));return n}function o(e){let t=e.map(e=>Math.max(0,n(e,0))),i=r(t)/(t.length-1);return i<=1e-9?t.map(()=>1):t.map(e=>e/i)}function s(e){return e.every(e=>Math.abs(e-1)<1e-6)}function c(){return{cuts:[],envelopes:[Array(24).fill(1)]}}function l(e){return!e||e.cuts.length===0&&e.envelopes.every(s)}function u(e){if(!e||typeof e!=`object`)return null;let t=Array.isArray(e.cuts)?e.cuts:[],r=[];for(let e of t){let t=n(e?.t,NaN),i=n(e?.d,NaN);if(!(t>0&&t<1&&i>0&&i<1))continue;let a=r[r.length-1];a&&(t<=a.t+1e-6||i<=a.d+1e-6)||r.push({t,d:i})}let i=Array.isArray(e.envelopes)?e.envelopes:[],s=[];for(let e=0;e<=r.length;e+=1){let t=Array.isArray(i[e])?i[e].map(e=>n(e,1)):[];s.push(o(a(t.length>=2?t:[1,1])))}return{cuts:r,envelopes:s}}function d(e,r,i,a=.18){let o=e.length,s=Math.max(0,n(i,0)),c=t(n(r,0),0,1),l=a/3,u=Array(o);for(let e=0;e<o;e+=1){let t=Math.abs(e/(o-1)-c);u[e]=t<=l?1:t>=a?0:.5*(1+Math.cos((t-l)/(a-l)*Math.PI))}let d=e.map((e,t)=>Math.max(0,e*(1-u[t])+s*u[t])),f=e=>e===0||e===o-1?.5:1,p=o-1,m=0,h=0;for(let e=0;e<o;e+=1)u[e]>1e-9?m+=f(e)*d[e]:h+=f(e)*d[e];if(h>1e-9){let e=Math.max(0,(p-m)/h);for(let t=0;t<o;t+=1)u[t]<=1e-9&&(d[t]*=e);if(p-m<0){let e=p/m;for(let t=0;t<o;t+=1)u[t]>1e-9&&(d[t]*=e)}}else if(m>1e-9){let e=p/m;for(let t=0;t<o;t+=1)d[t]*=e}else return Array(o).fill(1);return d}function f(e,n){let i=e.length,a=r(e);if(a<=1e-9)return t(n,0,1);let o=t(n,0,1)*(i-1),s=Math.min(i-2,Math.floor(o)),c=o-s,l=0;for(let t=0;t<s;t+=1)l+=(e[t]+e[t+1])/2;let u=e[s]*(1-c)+e[s+1]*c;return l+=(e[s]+u)/2*c,l/a}function p(e,r){let i=t(n(r,0),0,1);if(!e)return i;let a=[{t:0,d:0},...e.cuts,{t:1,d:1}],o=0;for(;o<a.length-2&&i>a[o+1].t;)o+=1;let s=a[o],c=a[o+1],l=c.t-s.t,u=l>1e-9?(i-s.t)/l:1;return s.d+(c.d-s.d)*f(e.envelopes[o],u)}function m(e,t,n){let r=Array(24);for(let a=0;a<24;a+=1)r[a]=i(e,t+(n-t)*(a/23));return r}function h(e,t){let r=e??c(),i=n(t,NaN);if(!(i>.02&&i<.98))return e;for(let t of r.cuts)if(Math.abs(t.t-i)<.02)return e;let a=p(r,i);if(!(a>1e-6&&a<1-1e-6))return e;let s=0;for(;s<r.cuts.length&&i>r.cuts[s].t;)s+=1;let l=s===0?{t:0}:r.cuts[s-1],u=s===r.cuts.length?{t:1}:r.cuts[s],d=(i-l.t)/(u.t-l.t),f=r.envelopes[s];return{cuts:[...r.cuts.slice(0,s),{t:i,d:a},...r.cuts.slice(s)],envelopes:[...r.envelopes.slice(0,s),o(m(f,0,d)),o(m(f,d,1)),...r.envelopes.slice(s+1)]}}function g(e,t){if(!e||!e.cuts[t])return e;let n=[{t:0,d:0},...e.cuts,{t:1,d:1}],r=n[t],a=n[t+1],s=n[t+2],c=(a.t-r.t)/(s.t-r.t),l=(a.d-r.d)/(s.d-r.d),u=1-c,d=1-l,f=e.envelopes[t],p=e.envelopes[t+1],m=Array(24);for(let e=0;e<24;e+=1){let t=e/23;if(t<=c){let n=i(f,c>1e-9?t/c:0);m[e]=l/Math.max(1e-9,c)*n}else{let n=i(p,u>1e-9?(t-c)/u:0);m[e]=d/Math.max(1e-9,u)*n}}return{cuts:[...e.cuts.slice(0,t),...e.cuts.slice(t+1)],envelopes:[...e.envelopes.slice(0,t),o(m),...e.envelopes.slice(t+2)]}}var _=Object.freeze([`keys`,`follow`,`rail`]),ee=Object.freeze({distance:3,height:1.6,response:.7,lead:.25,railStartMode:`head`,maxDollySpeed:4,pitchOffsetDeg:0,orbitOffsetDeg:0});function v(e){return Array.isArray(e)?e.map(e=>({x:e.x,z:e.z})):null}function te(e){if(!e||typeof e!=`object`)return null;let t=Array.isArray(e.points)?e.points:Number.isFinite(e.start)&&Number.isFinite(e.end)?[{t:0,height:e.start},{t:1,height:e.end}]:null;if(!t)return null;let n=t.filter(e=>e&&Number.isFinite(e.t)&&Number.isFinite(e.height)).map(e=>({t:Math.max(0,Math.min(1,e.t)),height:Math.max(.1,e.height)})).sort((e,t)=>e.t-t.t).filter((e,t,n)=>t===n.length-1||n[t+1].t-e.t>1e-6).slice(0,8);return n.length<2?null:(n[0]={...n[0],t:0},n[n.length-1]={...n[n.length-1],t:1},{points:n})}function ne(e){return!e||typeof e!=`object`?null:e.mode===`off`?{mode:`off`}:e.mode===`range`?{mode:`range`,startFrame:e.startFrame,endFrame:e.endFrame}:null}function re(e){let t=Array.isArray(e?.ids)?e.ids.filter(e=>typeof e==`string`&&e).slice(0,4):[];if(t.length)return Number.isFinite(e.height)?{ids:t,height:e.height}:{ids:t};let n=e?.point;return n&&[n.x,n.y,n.z].every(Number.isFinite)?{point:{x:n.x,y:n.y,z:n.z}}:null}function y(e,t){let n=t?re(e.aim):null,r=t&&Number.isFinite(e.focalMm)&&e.focalMm>0?e.focalMm:null;return{...n?{aim:n}:{},...r?{focalMm:r}:{}}}function b(e={}){let t=e&&typeof e==`object`?e:{},n=_.includes(t.mode)?t.mode:`keys`,r={...ee,...t.followCam??{}},i=v(t.cameraRail),a=te(t.craneHeight)??(n===`rail`&&i?{points:[{t:0,height:r.height},{t:1,height:r.height}]}:null),o=u(t.dollyTiming);return{mode:n,followCam:r,cameraRail:i,railFollow:ne(t.railFollow),craneHeight:a,dollyTiming:l(o)?null:o,...y(t,i)}}function ie(e){return b(e)}function x(e,t={}){let n=b(e),r=t&&typeof t==`object`?t:{};return b({...n,...r,followCam:r.followCam?{...n.followCam,...r.followCam}:n.followCam,cameraRail:Object.hasOwn(r,`cameraRail`)?r.cameraRail:n.cameraRail,railFollow:Object.hasOwn(r,`railFollow`)?r.railFollow:n.railFollow,craneHeight:Object.hasOwn(r,`craneHeight`)?r.craneHeight:n.craneHeight,dollyTiming:Object.hasOwn(r,`dollyTiming`)?r.dollyTiming:n.dollyTiming})}function ae(e){let t=b(e);return x(t,{mode:t.mode===`rail`?`follow`:t.mode,cameraRail:null,railFollow:null,craneHeight:null})}var S=e=>e&&typeof e==`object`?Object.freeze({...e}):e,C=Object.freeze([{path:`character.position`,type:`vec3`,persisted:!0,undoDomain:`cast`,normalizer:`createCharacterEntry`,min:{x:-240,y:0,z:-240},max:{x:240,y:240,z:240},gizmo:{min:{x:-4,y:0,z:-4},max:{x:4,y:240,z:4}},note:`y is the feet`},{path:`character.rot`,type:`number`,persisted:!0,undoDomain:`cast`,normalizer:`createCharacterEntry`,min:-180,max:180,angle:!0,note:`yaw degrees, wrapped at the upper bound`},{path:`character.scale`,type:`number`,persisted:!0,undoDomain:`cast`,normalizer:`createCharacterEntry`,min:.2,max:3},{path:`character.subject`,type:`string`,persisted:!0,undoDomain:`cast`,normalizer:`createCharacterEntry`},{path:`character.hidden`,type:`boolean`,persisted:!0,undoDomain:`cast`,normalizer:`createCharacterEntry`},{path:`character.parent`,type:`id`,nullable:!0,persisted:!0,undoDomain:`cast`,normalizer:`createCharacterEntry`,note:`scene object id the character is grouped under and rides; null stands in the world`},{path:`character.model`,type:`enum`,persisted:!0,undoDomain:`cast`,normalizer:`createCharacterEntry`,enum:[`y-bot-tpose`,`x-bot-tpose`,`proxy-figure`]},{path:`character.posture`,type:`enum`,persisted:!0,undoDomain:`cast`,normalizer:`createCharacterEntry`,enum:[`stand`,`sit`,`lie`]},{path:`character.tint`,type:`color`,persisted:!0,undoDomain:`cast`,normalizer:`createCharacterEntry`},{path:`character.identityImage`,type:`image`,persisted:!0,undoDomain:`cast`,normalizer:`createCharacterEntry`,note:`data:image only`},{path:`character.pose`,type:`id`,persisted:!0,undoDomain:`cast`,normalizer:`createCharacterEntry`},{path:`character.waypoints`,type:`array`,persisted:!0,undoDomain:`cast`,normalizer:`createCharacterEntry`,actions:[`character.addWaypoint`,`character.moveWaypoint`,`character.removeWaypoint`,`character.clearWaypoints`],note:`root path pins, addressed by frame`},{path:`character.sessionMotion`,type:`array`,persisted:!1,undoDomain:`cast`,normalizer:`createCharacterEntry`,note:`dropped by createCharacterEntry`},{path:`character.ikKeys`,type:`array`,persisted:!1,undoDomain:`cast`,normalizer:`createCharacterEntry`,actions:[`character.setIkKey`,`character.removeIkKey`,`character.clearIkKeys`],note:`dropped by createCharacterEntry; keys travel as JSON quaternions/positions`},{path:`object.renderer`,type:`enum`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`,enum:[`cube`,`sphere`,`capsule`,`cylinder`,`cone`,`plane`,`chair`,`car`,`small-plane`,`empty`,`light`,`effect`],note:`light is made from catalogue kind point-light or spot-light; effect (smoke, fire, rain, trail...) from kind effect`},{path:`object.position`,type:`vec3`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`,min:{x:-240,y:0,z:-240},max:{x:240,y:240,z:240},note:`y is the object's base: y=0 rests on the floor; height/supportY rise from it`},{path:`object.rotation`,type:`vec3`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`,min:{x:-180,y:-180,z:-180},max:{x:180,y:180,z:180},angle:!0,note:`rot/rotX/rotZ degrees, wrapped at the upper bound`},{path:`object.scale`,type:`vec3`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`,min:{x:.01,y:.01,z:.01},max:{x:100,y:100,z:100}},{path:`object.name`,type:`string`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`},{path:`object.color`,type:`color`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`},{path:`object.opacity`,type:`number`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`,min:.05,max:1,note:`1 is solid; lower is see-through, e.g. 0.3 for clear glass`},{path:`object.parent`,type:`id`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`},{path:`object.attach`,type:`id`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`,actions:[`object.attach`,`object.detach`],note:`carried by a character's root or bone; channels convert so the prop stays put`},{path:`object.path`,type:`array`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`},{path:`object.remove`,type:`boolean`,persisted:!0,undoDomain:`objects`,normalizer:null,note:`lifecycle operation, not a document field`},{path:`object.cutout`,type:`image`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`,actions:[`asset.import`],note:`assetId-backed cutout record; imported pictures and models are placed by asset.import`},{path:`object.light`,type:`object`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`,note:`renderer light only. { type point|spot, color, intensity 0..1000 candela (lighter 0.45, candle 0.3, desk lamp 5, street lamp 40), range m (0 none), angle 1..89 deg spot half-angle, softness 0..1, shadow (first 2 lights only; inside a solid record it is blocked: receipt LIGHT_BLOCKED), flicker 0..1 (lighter 0.6), aim {x,y,z} world point or null = local -Y }, e.g. { intensity: 40, aim: { x: 0, y: 0, z: 1 } }; a take level track scales it`},{path:`object.glow`,type:`object`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`,note:`any record: self-lit colour plus additive halo, same under any stage light; casts no shadow, so a light inside a glowing bulb shines out. { color, intensity 0..20, halo 0..4 x the record's radius }, e.g. ember { color: "#ff5a1f", intensity: 6, halo: 2 }; null removes; a take level track scales it`},{path:`object.effect`,type:`object`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`,note:`renderer effect only (object.add kind "effect"). { preset: smoke|exhale|steam|fire|sparks|dust|rain|snow|trail, rate particles/s, life s, size m start diameter, grow end/start size, speed m/s along the record's local +Y (rotX 90 aims +Z), spread 0..1 cone, gravity m/s2 (+ falls, - rises), wind {x,y,z} m/s, color, opacity 0..1, additive (emissive: fire, sparks), seed int, area {x,y,z} m birth box (rain/snow/dust fall through it from its top), width m trail ribbon across local Y }. A new preset loads its defaults and fields in the same set override them, e.g. { preset: "fire", rate: 40 }; the record stores the merged numbers. Particles are born where the record is at each frame (route, parent, take carry), only while it and its parents are shown, at rate x the take level. To emit from the body (a breath at the mouth), a motion spec entry objects.<id> = { follow: "landmark:mouth", aim: "face" } moves it there every frame. Measure with inspect_studio { scope: "entities", ids }: effect { frame (the playhead), alive, emitter [x,y,z], bounds { min, max } m }`},{path:`stage.keyLight.x`,type:`number`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,min:-30,max:30},{path:`stage.keyLight.y`,type:`number`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,min:.5,max:30},{path:`stage.keyLight.z`,type:`number`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,min:-30,max:30},{path:`stage.keyLight.intensity`,type:`number`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,min:0,max:4},{path:`stage.keyLight.warmth`,type:`number`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,min:0,max:1},{path:`stage.environmentImage`,type:`image`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,note:`data:image only`},{path:`stage.environment`,type:`string`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,note:`location description every shot prompt is built from`},{path:`stage.style`,type:`string`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,note:`look / style line for shot prompts`},{path:`stage.hasEnvSheet`,type:`boolean`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,note:`author supplies an environment sheet instead of a description`},{path:`stage.camera`,documentPath:`shotAspect`,type:`enum`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,enum:[`16:9`,`2.39:1`,`9:16`,`1:1`,`4:3`,`12:7`,`fal 480P`],note:`output aspect ratio`},{path:`stage.cameraPresetId`,type:`id`,nullable:!0,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`},{path:`stage.sensorId`,type:`enum`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,enum:[`super16`,`super35`,`fullFrame`,`65mm`]},{path:`stage.keyLight.color`,type:`color`,nullable:!0,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,note:`key light colour #rrggbb, overrides warmth, e.g. "#9db6e6" cool moonlight or "#ffad5c" low sun; null = white tinted by warmth`},{path:`stage.lighting.preset`,type:`enum`,persisted:!0,readOnly:!0,undoDomain:`stage`,normalizer:`createSceneStage`,enum:[`studio`,`day`,`overcast`,`golden`,`dusk`,`night`,`interior`,`stage`],note:`label of the last recipe stage.applyLighting applied; studio is the neutral grey default`},{path:`stage.lighting.sky`,type:`color`,nullable:!0,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,note:`background and fog colour at the horizon, e.g. "#0b1426" night; null = the UI theme's studio grey`},{path:`stage.lighting.skyTop`,type:`color`,nullable:!0,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,note:`sky colour overhead: shot camera and exports grade from sky at the horizon to this, e.g. "#020408"; null = flat sky`},{path:`stage.lighting.ambient`,type:`number`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,min:0,max:3,note:`multiplier on the hemisphere and ambient light; 1 = studio, 0.6 = night, 0 = black stage`},{path:`stage.lighting.hemiSky`,type:`color`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,note:`hemisphere light from above, e.g. "#34507f" cool night sky; studio "#ffffff"`},{path:`stage.lighting.hemiGround`,type:`color`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,note:`hemisphere bounce from below, e.g. "#6e5136" warm ground; studio "#5a5d64"`},{path:`stage.lighting.fill`,type:`number`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,min:0,max:3,note:`multiplier on the fixed fill and rim lights; 1 = studio, 0 = key only`},{path:`stage.lighting.fog`,type:`number`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,min:0,max:1,note:`haze 0..1 fading the set into the sky colour: 0 = far horizon only, 0.45 = from ~18 m to ~38 m, 1 = from 2 m to 14 m`},{path:`stage.lighting.exposure`,type:`number`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,min:.2,max:3,note:`camera exposure multiplier on lit surfaces; 1 = studio, e.g. 1.4 to lift a dark frame`},{path:`stage.lighting.shadowSoftness`,type:`number`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,min:0,max:1,note:`key shadow penumbra; 0 = crisp (studio), 0.75 = soft moonlight, 1 = overcast`},{path:`stage.lighting.envLight`,type:`number`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,min:0,max:2,note:`sky environment light on every surface: a map from sky, skyTop, hemiGround and a glow toward the key (sun or moon) tints and fills clay from all sides; it takes over the flat hemisphere as it rises. 0 = hemisphere only (studio), 1 = the map alone at the same brightness (every other recipe), e.g. 1.4 for a brighter fill`},{path:`stage.lighting.ao`,type:`number`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,min:0,max:1,note:`ambient occlusion strength: contact darkening within ~0.5 m where a body meets the floor or a prop and in creases (armpits, the back of a squat's knees), in the viewport and every export. 0 = off (studio), 0.8 = most recipes, 1 = overcast`},{path:`stage.lighting.hdr`,type:`id`,nullable:!0,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,note:`HDR environment map that replaces the sky environment light: a built-in ("builtin:night-street", "builtin:overcast-field", "builtin:studio-softbox") or a file the user loaded ("hdr-<32 hex>"); inspect_studio { scope: "catalogue" } environments lists them with each map's brightest direction. It lights the set only while envLight > 0 (its light = map x hdrIntensity x envLight; studio has envLight 0, so set envLight 1). stage.applyLighting clears it unless keep has "lighting.hdr". null = the look's own sky`},{path:`stage.lighting.hdrRotation`,type:`number`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,min:-180,max:180,angle:!0,note:`degrees the HDR map turns about the vertical axis, light and backdrop together: +90 carries a light at +x (screen right from the default camera) to -z (behind the subject), so a brightest [x, y, z] lands at [x cos r + z sin r, y, z cos r - x sin r]; wrapped at the upper bound`},{path:`stage.lighting.hdrIntensity`,type:`number`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,min:0,max:4,note:`multiplier on the HDR map's radiance in its light and its backdrop; 1 = the file as authored, e.g. 0.5 to calm a bright daylight map`},{path:`stage.lighting.hdrBackground`,type:`boolean`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,note:`true = the HDR map is the backdrop behind the set (the floor fades into its horizon), in the viewport, shot and every export; false = keep the look's sky as the backdrop and use the map only as light`},{path:`shot.crud`,type:`array`,persisted:!0,undoDomain:`shot`,normalizer:null,actions:[`shot.create`,`shot.split`,`shot.duplicate`,`shot.remove`,`shot.setRange`,`shot.reorder`],note:`create/split/duplicate/reorder/remove/range through the shared action registry`},{path:`shot.cameraKeys`,type:`array`,persisted:!0,undoDomain:`shot`,normalizer:null,frameMin:0},{path:`shot.cameraRail`,type:`array`,persisted:!0,undoDomain:`shot`,normalizer:`repairCamera`,actions:[`shot.setCameraRail`,`shot.clearCameraRail`],note:`rail points; crane/dolly timing follow the shot's camera block`},{path:`shot.targetModel`,type:`id`,persisted:!0,undoDomain:`shot`,normalizer:`repairCamera`},{path:`shot.kind`,type:`enum`,persisted:!0,undoDomain:`shot`,normalizer:null,readOnly:!0,enum:[`clip`,`still`],note:`clip or still; a still holds one picture for endFrame - startFrame + 1 frames`},{path:`shot.caption`,type:`string`,persisted:!0,undoDomain:`shot`,normalizer:null,readOnly:!0,note:`trimmed, at most 500 characters`},{path:`shot.cast`,type:`array`,persisted:!0,undoDomain:`shot`,normalizer:null,readOnly:!0,note:`per-shot placement overrides keyed by character id: { x, z, rot, posture?, pose? }`},{path:`shot.stylizedAssetId`,type:`id`,nullable:!0,persisted:!0,undoDomain:`shot`,normalizer:null,readOnly:!0,note:`image asset id only`},{path:`shot.freeCamera`,type:`vec3`,persisted:!1,undoDomain:`shot`,normalizer:null,note:`transient until keyed`},{path:`scenes`,type:`array`,persisted:!0,undoDomain:null,normalizer:null,actions:[`scene.create`,`scene.duplicate`,`scene.rename`,`scene.delete`,`scene.switch`],note:`the project's scene list and the open scene; outside the undo history`},{path:`project`,type:`string`,persisted:!0,undoDomain:null,normalizer:null,actions:[`project.save`],note:`save to the current project file; opening one needs the user's file picker`},{path:`selection`,type:`id`,persisted:!1,undoDomain:null,normalizer:null},{path:`timeline`,type:`number`,persisted:!1,undoDomain:null,normalizer:null},{path:`view.mode`,type:`enum`,persisted:!1,undoDomain:null,normalizer:null,enum:[`scene`,`pose`,`camera`,`motion`]},{path:`view.partColoursGuideModeInset`,type:`array`,persisted:!1,undoDomain:null,normalizer:null,actions:[`view.setPartColours`,`view.setGuideMode`,`view.setInset`,`view.setGhosts`],note:`partColours/guideMode/inset/ghosts; viewer settings, not document fields`},{path:`read.sceneDescription`,type:`string`,persisted:!1,undoDomain:null,normalizer:null},{path:`read.captureFrame`,type:`image`,persisted:!1,undoDomain:null,normalizer:null},{path:`undo`,type:`boolean`,persisted:!1,undoDomain:null,normalizer:null}].map(e=>Object.freeze({...e,...e.enum?{enum:Object.freeze([...e.enum])}:{},...e.actions?{actions:Object.freeze([...e.actions])}:{},...e.min&&typeof e.min==`object`?{min:S(e.min)}:{},...e.max&&typeof e.max==`object`?{max:S(e.max)}:{},...e.gizmo?{gizmo:Object.freeze({min:S(e.gizmo.min),max:S(e.gizmo.max)})}:{}})));function oe(e){return C.find(t=>t.path===e)}var se=e=>e.persisted!==!1&&!e.actions&&!e.readOnly,ce=Object.freeze(`INVALID_ARGUMENT.INVALID_CONTEXT.INVALID_IDENTITY.INVALID_TURN_ID.INVALID_SESSION_ID.INVALID_RECEIPT.INVALID_RANGE.INVALID_REQUEST.UNKNOWN_TOOL.UNKNOWN_VARIANT.DUPLICATE_NAME.CONTEXT_LIMIT.CONTEXT_TOO_LARGE.AMBIGUOUS_TARGET.AMBIGUOUS_BASIS.TARGET_NOT_READY.TARGET_BUSY.STALE_TARGET.STALE_SCENE.STALE_ENVIRONMENT.STALE_CURSOR.CAPABILITY_MISSING.LIVE_HUB_UNAVAILABLE.AUTH_REQUIRED.GENERATION_LIMIT.RATE_LIMITED.BACKEND_UNAVAILABLE.VERIFICATION_FAILED.REPAIR_REGRESSED.CANCELLED.UNCERTAIN_APPLY.UNDO_CONFLICT.CONFIRMATION_REQUIRED.TIMEOUT.UNDO_EXPIRED.INTERNAL_ERROR`.split(`.`)),le=e=>e?.code??([`TypeError`,`ReferenceError`,`RangeError`,`SyntaxError`].includes(e?.name)?`INTERNAL_ERROR`:`INVALID_ARGUMENT`),ue=`#c2c6c8`,w=[`#e2e5e6`,ue,`#9aa1a5`,`#767d81`,`#d9b18c`,`#8fae9b`,`#d94a4a`,`#4a7bd9`,`#e2c04a`,`#4fa86a`],de=6,fe=`cozyclay.objectColors.recent`,pe=/^#?([0-9a-f]{3})$/i,me=/^#?([0-9a-f]{6})$/i;function T(e){if(typeof e!=`string`)return null;let t=e.trim(),n=pe.exec(t);if(n)return`#${n[1].toLowerCase().replace(/./g,e=>e+e)}`;let r=me.exec(t);return r?`#${r[1].toLowerCase()}`:null}function he(e,t){let n=Array.isArray(e)?e.map(T).filter((e,t,n)=>e&&n.indexOf(e)===t&&!w.includes(e)):[],r=T(t),i=(r&&!w.includes(r)?[r,...n.filter(e=>e!==r)]:n).slice(0,de);return Array.isArray(e)&&i.length===e.length&&i.every((t,n)=>t===e[n])?e:i}function ge(e){try{let t=JSON.parse(e?.getItem(fe)??`[]`);return he(Array.isArray(t)?t:[],null)}catch{return[]}}function _e(e,t){try{e?.setItem(fe,JSON.stringify(t))}catch{}}var ve=`effect`,ye={kind:ve,label:`Effect`,group:`Effects`,footprint:{width:0,depth:0},height:0,color:`#7fd4f0`},E=(e,t,n)=>({x:e,y:t,z:n}),be=E(0,0,0),xe=Object.freeze({smoke:{rate:60,life:2.8,size:.012,grow:6,speed:.05,spread:.1,gravity:-.3,wind:E(.02,0,0),color:`#7d8a99`,opacity:.42,additive:!1,area:be,width:0},exhale:{rate:120,life:2.4,size:.035,grow:8,speed:.9,spread:.35,gravity:-.35,wind:E(.02,0,0),color:`#a3abb4`,opacity:.3,additive:!1,area:E(.01,0,.01),width:0},steam:{rate:26,life:2,size:.03,grow:4,speed:.1,spread:.2,gravity:-.45,wind:E(.02,0,0),color:`#bcc5ce`,opacity:.2,additive:!1,area:E(.07,0,.07),width:0},fire:{rate:140,life:.75,size:.12,grow:.3,speed:.4,spread:.15,gravity:-2.2,wind:be,color:`#ff7a1f`,opacity:1,additive:!0,area:E(.22,0,.22),width:0},sparks:{rate:40,life:1,size:.012,grow:.6,speed:2.6,spread:.55,gravity:6,wind:be,color:`#ff9d33`,opacity:1,additive:!0,area:E(.05,0,.05),width:0},dust:{rate:30,life:7,size:.014,grow:1.2,speed:0,spread:1,gravity:.01,wind:E(.04,0,.01),color:`#a89a82`,opacity:.55,additive:!1,area:E(3,2.2,3),width:0},rain:{rate:1600,life:1.2,size:.01,grow:1,speed:0,spread:0,gravity:9.8,wind:be,color:`#9aabbd`,opacity:.4,additive:!1,area:E(8,5,8),width:0},snow:{rate:220,life:8,size:.025,grow:1,speed:0,spread:0,gravity:9.8,wind:E(.1,0,0),color:`#ffffff`,opacity:.85,additive:!1,area:E(8,4,8),width:0},trail:{rate:0,life:.3,size:0,grow:1,speed:0,spread:0,gravity:0,wind:be,color:`#a7b8ca`,opacity:.75,additive:!1,area:be,width:.5}}),Se=Object.freeze(Object.keys(xe)),Ce={rate:[0,2e3],life:[.05,12],size:[.001,5],grow:[.05,20],speed:[0,60],spread:[0,1],gravity:[-30,30],opacity:[0,1],width:[0,10]},we={wind:[-20,20],area:[0,100]},Te=2147483647,Ee=([e,t],n,r)=>{let i=Number(n);return Number.isFinite(i)?Math.min(t,Math.max(e,i)):r};function De(e){let t=e&&typeof e==`object`&&!Array.isArray(e)?e:{},n=Se.includes(t.preset)?t.preset:`smoke`,r=xe[n],i={preset:n};for(let[e,n]of Object.entries(Ce))i[e]=Ee(n,t[e],r[e]);for(let[e,n]of Object.entries(we)){let a=t[e]&&typeof t[e]==`object`?t[e]:{};i[e]=E(...[`x`,`y`,`z`].map(t=>Ee(n,a[t],r[e][t])))}i.color=T(t.color)??r.color,i.additive=typeof t.additive==`boolean`?t.additive:r.additive;let a=Number(t.seed);return i.seed=Number.isFinite(a)?Math.min(Te,Math.max(0,Math.round(a))):1,i}function Oe(e){return e?.renderer===`effect`?{effect:De(e.effect)}:{}}function ke(e,t){let n=e?.set?.effect?.preset;if(!Se.includes(n))return e;let r=t?.find?.(t=>t.id===e.id)?.effect;if(r?.preset===n)return e;let i=structuredClone(xe[n]);return{...e,set:{...e.set,effect:{...i,seed:r?.seed??1,...e.set.effect}}}}var Ae=(e,t)=>({type:`number`,minimum:e,maximum:t}),je=([e,t])=>({type:`object`,properties:{x:Ae(e,t),y:Ae(e,t),z:Ae(e,t)},required:[],additionalProperties:!1}),Me=Object.freeze({type:`object`,properties:{preset:{type:`string`,enum:[...Se]},...Object.fromEntries(Object.entries(Ce).map(([e,[t,n]])=>[e,Ae(t,n)])),...Object.fromEntries(Object.entries(we).map(([e,t])=>[e,je(t)])),color:{type:`string`,minLength:1,maxLength:32,pattern:`^#[0-9a-fA-F]{6}$`},additive:{type:`boolean`},seed:{type:`integer`,minimum:0,maximum:Te}},required:[],additionalProperties:!1}),Ne=24,Pe=40,Fe=e=>{let t=JSON.stringify(e)??String(e);return t.length>Pe?`${t.slice(0,37)}...`:t},Ie=e=>e===null?`null`:Array.isArray(e)?`an array`:typeof e==`object`?`an object`:typeof e==`number`&&!Number.isFinite(e)?String(e):`a ${typeof e}`,Le=e=>e.length>Ne?`${e.slice(0,Ne).join(`, `)}, ... (${e.length} in all)`:e.join(`, `),Re=e=>Object.hasOwn(e,`const`)?JSON.stringify(e.const):e.type===`integer`?`an integer`:e.type===`array`?`an array${e.items?.type?` of ${e.items.type}s`:``}`:e.type===`object`?`an object`:e.type===`null`?`null`:`a ${e.type}`,ze=(e,t,n)=>`${e}: expected ${Re(t)}, got ${Object.hasOwn(t,`const`)?Fe(n):Ie(n)}.`,Be=(e,t,n)=>{let r=Object.keys(t.properties);return`${e} has unknown field ${Fe(n)}; ${r.length?`allowed: ${Le(r)}`:`it takes no fields`}.`},Ve=(e,t)=>`${e}: missing required field "${t}".`;function He(e,t,n){if(!Array.isArray(n))return ze(e,t,n);let r=t.minItems??0,i=t.maxItems??1/0;return`${e}: expected ${r===i?`exactly ${r}`:i===1/0?`at least ${r}`:r===0?`at most ${i}`:`${r} to ${i}`} item${r===i&&r===1?``:`s`}, got ${n.length}.`}var Ue=(e,t)=>{let n=new Set,r=t.map(e=>JSON.stringify(e)).find(e=>n.has(e)?!0:(n.add(e),!1));return`${e}: items must be unique; ${r&&r.length<=Pe?r:`one item`} appears twice.`};function We(e,t,n){if(typeof n!=`string`)return ze(e,t,n);if(!n.trim())return`${e}: must not be empty.`;let r=[...n].length;return t.maxLength!==void 0&&r>t.maxLength?t.description?`${e}: over ${t.maxLength} characters. ${t.description}`:`${e}: at most ${t.maxLength} characters, got ${r}.`:`${e}: ${Fe(n)} does not match ${t.pattern}.`}var Ge=(e,t,n)=>`${e}: ${Fe(n)} is not one of: ${Le(t.enum)}.`;function Ke(e,t,n){return typeof n!=`number`||!Number.isFinite(n)?ze(e,t,n):t.type===`integer`&&!Number.isSafeInteger(n)?`${e}: expected an integer, got ${n}.`:`${e}: must be greater than ${t.exclusiveMinimum}, got ${n}.`}var qe=e=>e.oneOf??e.anyOf?(e.oneOf??e.anyOf).every(qe):e.type!==`object`&&e.type!==`array`,Je=e=>[e.minimum,e.maximum].some(e=>e!==void 0)?` within [${[e.minimum??`-inf`,e.maximum??`inf`].join(`, `)}]`:``,Ye=e=>e.oneOf??e.anyOf?(e.oneOf??e.anyOf).flatMap(Ye):Object.hasOwn(e,`const`)?[JSON.stringify(e.const)]:e.enum?e.enum.map(e=>JSON.stringify(e)):e.type===`boolean`?[`true`,`false`]:[`${Re(e)}${e.type===`number`||e.type===`integer`?Je(e):``}`];function Xe(e,t,n){if(!t.every(({error:t})=>t.details?.path===e)||typeof n==`object`&&n&&!t.every(({branch:e})=>qe(e)))return null;let r=[...new Set(t.flatMap(({branch:e})=>Ye(e)))],i=r.length>Ne?[...r.slice(0,Ne),`... (${r.length} in all)`]:r;return`${e} must be ${i.length>1?`${i.slice(0,-1).join(`, `)} or ${i.at(-1)}`:i[0]}, got ${typeof n==`object`&&n?Ie(n):Fe(n)}.`}var Ze=[`storyboard`,`animation`],Qe=[`stand`,`sit`,`lie`],$e=65536,et=Object.freeze({entities:24,entityIndex:400,shots:8,assets:48,recentReceipts:3,jobs:8}),tt=Object.freeze([`inspect_studio`,`run_action`,`verify_result`]);Object.freeze([`operate_studio`,`arrange_objects`,`arrange_characters`,`patch_elements`,`frame_shot`,`undo_edit`]);var nt=Object.freeze({inspect_studio:`Read the scene`,operate_studio:`Selection and view`,arrange_objects:`Arrange objects`,arrange_characters:`Arrange characters`,patch_elements:`Edit properties`,frame_shot:`Frame the shot`,verify_result:`Verify the result`,undo_edit:`Undo an edit`,run_action:`Run an editor action`}),rt=Object.freeze(Object.keys(nt)),it=Object.freeze([`character`,`object`,`shot`,`stage`]);Object.freeze({character:`cast`,object:`objects`,shot:`shot`,stage:`stage`});var D=k({selectionKinds:[`scene`,`object`,`character`,`rig`,`camera`],modes:[`scene`,`pose`,`camera`,`motion`],shotModes:[`keys`,`follow`,`rail`],framingSizes:[`extreme close-up`,`close-up`,`medium close-up`,`medium shot`,`medium-wide shot`,`wide shot`,`extreme wide shot`],framingViews:[`front`,`front three-quarter`,`profile`,`rear three-quarter`,`back`],framingLevels:[`ground`,`low`,`hip`,`eye`,`high`,`overhead`],framingSides:[`left`,`right`],positionSides:[`left`,`right`,`front`,`behind`],positionBases:[`world`,`subject`,`shot_camera`],collisionPolicies:[`report`,`avoid`],objectOps:[`create`,`update`,`remove`,`group`,`ungroup`],characterOps:[`create`,`update`,`remove`],inspectionScopes:[`selection`,`scene`,`entities`,`shot`,`motion`,`catalogue`,`actions`,`document`],receiptStatuses:[`applied`,`partial`,`noop`,`transient`,`installed`,`undone`],opStatuses:[`applied`,`partial`,`noop`],jobStates:[`queued`,`generating`,`preparing`,`verifying`,`repairing`,`committing`,`reconciling`,`installed`,`review_required`,`failed`,`cancelled`,`stale_target`,`stale_environment`]}),O=class extends Error{constructor(e,t,n={}){super(t),this.name=`StudioProtocolError`,this.code=e,this.details=n}toJSON(){return{code:this.code,message:this.message,...Object.keys(this.details).length?{details:this.details}:{}}}},at=e=>new TextEncoder().encode(e).byteLength;function k(e){if(e&&typeof e==`object`&&!Object.isFrozen(e)){for(let t of Object.values(e))k(t);Object.freeze(e)}return e}var A=(e,t,n=`$`,r={})=>{throw new O(e,t,{path:n,...r})},ot=e=>typeof e==`object`&&!!e&&!Array.isArray(e),j=(e=120)=>({type:`string`,minLength:1,maxLength:e}),M=(e,t)=>({type:`number`,...e===void 0?{}:{minimum:e},...t===void 0?{}:{maximum:t}}),N=(e=0,t=2**53-1)=>({...M(e,t),type:`integer`}),P={type:`boolean`},F=e=>({const:e}),I=e=>({type:`string`,enum:e}),L=e=>({oneOf:[e,{type:`null`}]}),R=(e,t,n=0,r=!1)=>({type:`array`,items:e,minItems:n,maxItems:t,...r?{uniqueItems:r}:{}}),z=(e,t={})=>({type:`object`,properties:{...e,...t},required:Object.keys(e),additionalProperties:!1}),B=(...e)=>({oneOf:e}),st={type:`object`,properties:{},required:[],additionalProperties:!0},V={...j(),pattern:`^[A-Za-z0-9][A-Za-z0-9._:-]*$`},ct={...j(36),pattern:`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$`},H=z({x:M(),y:M(),z:M()}),U={type:`number`,exclusiveMinimum:0},lt=z({x:U,y:U,z:U}),ut={...z({startFrame:N(),endFrameExclusive:N(1)}),"x-studio-range":!0},W=(e=100,t=1)=>R(V,e,t,!0),G=j(120),dt={...j(120),description:`Object id, or the name of a part created EARLIER in this ops list (create it first).`},ft={workspaceId:V,documentEpoch:V,sceneId:V,sceneEpoch:V},pt=z(ft),mt=z({surface:F(`studio`),...ft,workspaceHandle:L(V)}),ht=z({scene:N(),physics:N(),view:N()}),gt=L(z({kind:I(D.selectionKinds),id:V},{hierarchyId:V})),_t=z({mode:I(D.modes),frame:N(),playing:P,lookThrough:P,grid:P,autoColor:P}),vt=B(z({world:H}),z({relativeTo:dt,basis:I(D.positionBases),side:I(D.positionSides),gapM:M(0),support:B(F(`floor`),z({objectId:dt}))}),z({between:R(dt,2,2,!0),fraction:M(0,1),support:F(`floor`)}),z({onObject:dt},{offsetXZ:z({x:M(),z:M()})})),yt=B(z({yawDeg:M()}),z({towardId:dt}),z({sameAsId:dt}),z({awayFromId:dt})),bt=B(z({intent:z({size:I(D.framingSizes),view:I(D.framingViews),level:I(D.framingLevels),side:I(D.framingSides)},{focalMm:U})}),z({exact:z({position:H,lookAt:H,focalMm:U})})),xt={...I([`parent`]),description:`"parent" reads position.world, rotationDeg and facing.yawDeg in the parent's local frame (its pivot and rotation, not its scale); omit for world space.`},St=B(z({op:F(`create`),source:z({kind:V}),position:vt},{name:G,facing:yt,scale:lt,rotationDeg:{...H,description:`Euler XYZ degrees (x pitch, y yaw, z roll), as in update. Exclusive with facing. A pitched/rolled part rests its lowest corner on its support.`},parent:{...G,description:`Group this new object under a parent: an existing object id, or the name of an object created earlier in this same ops list. Moving the parent then moves it too.`},space:xt}),z({op:F(`update`),id:V},{position:vt,facing:yt,rotationDeg:H,scale:lt,color:j(32),name:G,hidden:P,space:xt}),z({op:F(`remove`),id:V}),z({op:F(`group`),parentId:V,childIds:W()}),z({op:F(`ungroup`),childIds:W()})),Ct=B(z({op:F(`create`),name:G,position:vt},{facing:yt,scale:U}),z({op:F(`update`),characterId:V},{position:vt,facing:yt,scale:U,name:G,hidden:P}),z({op:F(`remove`),characterId:V})),wt={...j(2097152),pattern:`^data:image/[A-Za-z0-9.+-]+[;,]`},Tt=z({frame:N(),framing:z({pos:H,yaw:M(),pitch:M(),fovDeg:M(1,179)})},{id:V}),Et=B(M(0,1),z({t:M(0,1)},{bank:M(-90,90),pitch:M(-90,90)})),Dt=L(z({points:R(H,64,2)},{speed:M(0,50),faceTravel:P,loop:P,extend:P,marks:R(Et,6)})),Ot=z({},{type:I([`point`,`spot`]),color:{...j(32),pattern:`^#[0-9a-fA-F]{6}$`},intensity:M(0,1e3),range:M(0,100),angle:M(1,89),softness:M(0,1),shadow:P,flicker:M(0,1),aim:L(H)}),kt=L(z({},{color:{...j(32),pattern:`^#[0-9a-fA-F]{6}$`},intensity:M(0,20),halo:M(0,4)})),At={"character.pose":L(V),"character.identityImage":L(wt),"object.light":Ot,"object.glow":kt,"object.effect":Me,"object.parent":L(V),"object.path":Dt,"stage.environmentImage":L(wt),"shot.cameraKeys":R(Tt,64),"shot.targetModel":L(V)};function jt(e){if(Object.hasOwn(At,e.path))return At[e.path];if(e.type===`number`)return M(e.min,e.max);if(e.type===`boolean`)return P;if(e.type===`enum`)return I([...e.enum]);if(e.type===`id`)return V;if(e.type===`color`)return{...j(32),pattern:`^#[0-9a-fA-F]{6}$`};if(e.type===`image`)return L(wt);if(e.type===`vec3`){let{min:t,max:n}=e;return t&&typeof t==`object`&&n&&typeof n==`object`?z({x:M(t.x,n.x),y:M(t.y,n.y),z:M(t.z,n.z)}):H}return e.type===`string`?j(240):null}function Mt(e){return e.filter(se).map(({path:e,type:t,min:n,max:r,enum:i,note:a})=>({path:e,type:t,...n===void 0?{}:{min:n&&typeof n==`object`?{...n}:n},...r===void 0?{}:{max:r&&typeof r==`object`?{...r}:r},...i?{enum:[...i]}:{},...a?{note:a}:{}}))}var Nt=k(Mt(C));function Pt(e){let t={};for(let n of it){let r={};for(let t of e){if(!se(t)||!t.path.startsWith(`${n}.`))continue;let e=jt(t);e&&(r[t.path.slice(n.length+1)]=e)}t[n]={type:`object`,properties:r,required:[],additionalProperties:!1}}return t}var Ft=k(Pt(C)),It=k(Object.fromEntries(it.map(e=>[e,Object.keys(Ft[e].properties).map(t=>`${e}.${t}`)]))),Lt=B(z({target:z({kind:F(`character`),id:V}),set:Ft.character}),z({target:z({kind:F(`object`),id:V}),set:Ft.object}),z({target:z({kind:F(`shot`)},{id:V}),set:Ft.shot}),z({target:z({kind:F(`stage`)}),set:Ft.stage})),Rt={inspect_studio:z({scope:I(D.inspectionScopes)},{ids:W(32),select:W(32),query:G,cursor:j(512),limit:{...N(1,32),default:12}}),operate_studio:z({},{selection:gt,shotId:V,frame:N(),playing:P,mode:I(D.modes),view:z({},{lookThrough:P,grid:P,autoColor:P})}),arrange_objects:z({ops:{...R(St,100,1),description:`Applied in order, as one undo step. Each op sees the parts created by earlier ops, so build an assembly in one call: create the main part, then place the rest with position.onObject / relativeTo(+side,gapM) / between naming earlier parts (e.g. relativeTo "Hood"). Reference parts created in this call by name, never by id.`}},{collisionPolicy:{...I(D.collisionPolicies),default:`report`}}),arrange_characters:z({ops:R(Ct,8,1)}),patch_elements:z({ops:R(Lt,32,1)}),frame_shot:z({subjectIds:W(1),framing:bt},{shotId:V,caption:{type:`string`,maxLength:500},keyAtFrame:N()}),verify_result:z({checks:{...R(I([`placement`,`framing`,`motion`,`lighting`]),4,1,!0),description:`lighting measures the shot frame rendered at the playhead: checks.lighting { meanLuma 0..1, clippedPct (a channel at full scale), crushedPct (pure black), subjects: [{ id, meanLuma, contrast (5th to 95th percentile luma spread, 0..1) }] inside each target character's projected box, look: { preset, envLight, ao } the stage look's environment light and occlusion strength }. motion also answers exportFraming (one per character with a take): what the camera the export renders shows of the take over sampledFrames: camera (shot where a shot covers the frame, studio = the Studio camera as it stands when none does; shotIds), character { screenFraction [min, max] of the frame height, inFrame [lowest share of its joints' screen box inside the frame, frame], behindCamera, cut { head, hand_l, hand_r, foot_l, foot_r } }, and every object the take names { id, name, inFrame, out, cut }; out, cut and behindCamera are spans [first, last] of sampled frames; { character: { id }, reason } when it cannot be measured`}},{receiptId:V,targets:W(),range:B(F(`whole_clip`),ut),visual:{...I([`none`,`frame`,`contact_sheet`,`plan`,`trace`]),default:`none`},frames:{...B(I([`even`,`beats`]),R(N(),8,1,!0)),default:`even`,description:`contact_sheet frames: even spacing, beats (grab/release, beat starts, the worst QA frames, then even fill, answered in visualRefs[0].picks), or up to 8 timeline frames of your choice`},views:{...R(I([`front`,`side`,`three-quarter`,`top`]),2,1,!0),description:`contact_sheet from cameras of its own around the character instead of the shot camera (which stays as it is): a row per view, each held still over the frames and framed on focus, so small actions fill the tile; side and three-quarter look from the focus's side; a sheet always holds two views at least 60 degrees apart: if the asked ones look along nearly one line, side, front or top is added and named in visualRefs[0].addedView`},focus:{...B(j(120),R(j(120),3,1,!0)),description:`with views: what to frame, as refs (object:<id>, joint:<Bone>, prop:<prop>.<point>, landmark:mouth); default the whole character`},trail:{...B(j(120),R(j(120),3,1,!0)),description:`with views: refs whose path over the range is drawn as one dot per frame (spacing shows speed; later frames faint, the tile's own frame ringed), colours in visualRefs[0].trails`},ghosts:{...P,description:`with views: each tile also shows the first target's poses around its frame as translucent ghosts (onion skin), earlier ones blue, later ones orange, carried props included, so spacing and arcs read in one tile; how many and how far apart is view.setGhosts (while it is off: 3 each side, every 4 frames), answered in visualRefs[0].ghosts`}}),undo_edit:z({receiptId:V}),run_action:z({action:V},{args:st,confirmationToken:V})},zt=k(Rt),Bt=k(rt.map(e=>({name:e,slice:1,parameters:Rt[e]}))),Vt=z({min:H,max:H}),Ht=z({id:V,kind:I([`object`,`character`,`rig`]),token:V},{name:G,detailsOmitted:P,position:H,yawDeg:M(),rotationDeg:H,scale:B(U,lt),bounds:L(Vt),libraryKind:V,renderer:V,color:L(j(32)),tint:L(j(32)),modelId:L(j(120)),assetId:V,parentId:L(V),attachment:L(z({characterId:V,bone:L(V)})),pathPointCount:N(0,64),pathMarks:R(B(M(0,1),z({t:M(0,1)},{bank:M(-90,90),pitch:M(-90,90)})),6),local:z({position:H,rotationDeg:H}),motion:z({takeId:L(V),frames:N(),ikKeyCount:N()},{poseId:L(V),keyIds:W(8,0)}),capabilities:z({rigReady:P,ik:P,measuredFeet:P}),characterKind:I([`rig`,`proxy`]),posture:I(Qe)}),Ut=z({id:V,kind:I([`object`,`character`,`rig`])},{name:G,position:H}),Wt=z({id:V},{label:G,generation:F(`motion`),timeoutMs:N(1,3e5)}),Gt=z({id:V,name:G,range:ut,keyCount:N()},{subjectIds:W(24,0),kind:I([`clip`,`still`]),caption:j(500)}),Kt=z({id:V,name:G,range:ut,mode:I(D.shotModes)},{subjectIds:W(24,0),kind:I([`clip`,`still`]),caption:j(500)}),qt=z({position:H,lookAt:H,focalMm:U,sensorId:V,slate:G}),Jt=I([`primitive`,`set-piece`,`image`,`mesh`]),Yt=B(z({kind:V,name:G,type:Jt}),z({id:V,name:G,type:Jt})),Xt=z({id:V,characterId:V,state:I(D.jobStates)},{targetIds:W(24,0),progress:L(M(0,1)),phase:G}),Zt=z({schema:F(`studio-context-v1`),host:mt,revision:ht,units:z({distance:F(`m`),angle:F(`deg`),up:F(`+Y`),yawZero:F(`+Z`),yawPositiveToward:F(`+X`),pivot:F(`base`),fps:F(24),rangeEnd:F(`exclusive`)}),scene:z({name:G,aspect:j(40),floorY:M(),frameCount:N(),objectCount:N(),characterCount:N()},{previsMode:I(Ze)}),selection:gt,activeCharacterId:L(V),view:_t,shot:L(Kt),camera:L(qt),entities:R(Ht,24),entityPage:z({returned:N(0,24),total:N(),truncated:P,nextCursor:L(j(512))}),shots:R(Gt,8),shotsTruncated:P,assets:R(Yt,et.assets),recentReceipts:R(z({id:V,summary:G,canUndoDirect:P}),3),jobs:R(Xt,8),capabilities:z({profile:F(`studio-slice-1`),tools:R(I(rt),rt.length,0,!0)},{rigReady:P,cameraReady:P,bridgeReady:P,storyboard:P})},{entityIndex:R(Ut,et.entityIndex),actionIndex:R(Wt,512)}),Qt=z({...ft,targetId:V,token:V}),$t=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`,`ultra`],en=z({dataUrl:{...j(6e6),pattern:`^data:image/(png|jpeg|webp);base64,`}},{name:j(120)}),tn=z({surface:F(`studio`),sessionId:ct,turnId:ct,text:j(16e3),context:Zt},{model:j(120),effort:I($t),attachFrame:P,attachments:R(en,4,1),supervisor:P}),nn=z({surface:F(`studio`),sessionId:ct,turnId:ct},{jobId:V}),rn=z({before:N(),after:N()}),an=z({historyEntryId:V,entries:F(1),canUndoDirect:P}),on=z({characterId:V,beforeTakeId:L(V),takeId:V,targetToken:V,frameCount:N(1),fps:F(24),durationSeconds:U,blocks:R(z({sourceBeat:N(0,7),startFrame:N(),endFrameExclusive:N(1)}),120,1),selectionChanged:F(!1)}),sn=z({id:V,status:I([`verified`,`unverified`]),profile:F(`studio-motion-v1`),range:ut,evaluatedFrames:N(),physicsRevision:N(),limitations:R(G,12)},{surfaceMeasured:P,maxFloorPenetrationM:M(0),maxContactSlipM:M(0),maxContactFloatM:M(0),unsupportedFrames:N(),supportedCollisionFrames:N(),continuityRegressed:P,semanticStatus:I([`pending_image_review`,`passed`,`failed`,`unavailable`])}),cn=z({path:j(120)},{number:M(),text:L(j(512)),flag:P,vec:H,count:N(),bytes:N()}),ln=z({},{position:H,yawDeg:M(),rotationDeg:H,scale:B(U,lt),name:G,color:j(32),hidden:P,modelId:V,renderer:V,parentId:L(V),childIds:W(100,0),childCount:N(0),bounds:L(Vt),removed:P,range:ut,camera:qt,keyId:V,frame:N(),subjectIds:W(24,0),selection:gt,activeCharacterId:L(V),shotId:L(V),view:_t,token:V,takeId:L(V),statureM:U,patched:R(cn,32,1)}),un=[`left`,`right`,`on-axis`],dn=z({coverage:G},{relationSatisfied:P,overlapIds:W(100,0),actualGapM:M(),requestedGapM:M(0),maximumFootprintOverlapM:M(0),basis:I(D.positionBases),clipped:P,occluded:P,behindCamera:P,screenFraction:M(0),derivedSize:I(D.framingSizes),support:G,baseY:M(),facesTargetId:V,cameraSide:I(un),axisConsistent:P,evaluatedFrames:N(1),sampledFrames:R(N(),64,1),sampledChecks:R(z({frame:N(),screenFraction:M(),clipped:P,behindCamera:P,occluded:P}),64,1),issueFrames:R(z({frame:N(),codes:R(G,4,1),screenFraction:M()}),64,0)}),fn=z({subjects:R(z({id:V,position:H,yawDeg:M()}),24),pairs:R(z({a:V,b:V,distanceM:M(0)}),24),shots:R(z({shotId:V,subjectIds:W(2,0),camera:L(z({position:H,lookAt:H})),cameraSide:L(I(un)),occluders:R(z({subjectId:V,byObjectId:V}),8)}),8),axisConsistent:L(P)}),pn=z({code:V},{id:V,message:G,suggestedOutwardDeltaM:M(),count:N()}),mn={ok:F(!0),commandId:V,receiptId:V,host:pt,status:I(D.receiptStatuses),authored:P,revision:rn,affectedIds:W(100,0),delta:R(z({id:V,after:ln}),8),checks:dn,undo:L(an),warnings:R(pn,12)},hn={counts:z({created:N(),updated:N(),deleted:N()}),detailCursor:L(j(512))},gn=R(z({index:N(),status:I(D.opStatuses)},{droppedPaths:R(j(120),32,1)}),32,1),_n={...mn,authored:F(!0),undo:an},vn={action:V,summary:j(240)},yn={completed:z({...mn,status:F(`completed`),kind:I([`job`,`document`,`transaction`,`mutation`])},{...vn,...hn,output:st,jobId:V,txId:V,nextHost:pt,ops:gn}),started:z({...mn,status:F(`started`),kind:F(`job`),jobId:V,authored:F(!1),undo:F(null)},{...vn}),applied:z({..._n,status:F(`applied`)},{mutated:F(!0),ops:gn,...hn,...vn}),partial:z({..._n,status:F(`partial`),ops:gn},{mutated:F(!0),...hn}),noop:z({...mn,status:F(`noop`),authored:F(!1),mutated:F(!1),undo:F(null)},{ops:gn,...vn}),transient:z({...mn,status:F(`transient`),authored:F(!1),view:rn,undo:F(null)},{mutated:P,...vn}),installed:z({..._n,status:F(`installed`),jobId:V,artifactId:V,installed:on,verification:sn},{mutated:F(!0),explicitUnverifiedAcceptance:P,acceptance:F(`advisory-policy`),repairs:z({autoPhysicsInvocations:N(0,1),fixCollisionsInvocations:N(0,1),remaining:N(0,2)}),...hn}),undone:z({..._n,status:F(`undone`),undoneReceiptId:V,restoredTargets:R(Qt,100,1)},{mutated:F(!0),...hn})},bn=B(...Object.values(yn)),xn=z({ok:F(!1),commandId:V,host:pt,code:I(ce),phase:I([`admission`,`execution`,`prepare`,`verify`,`repair`,`commit`,`reconcile`,`undo`]),affectedIds:W(100,0),expectedTargets:R(Qt,24),currentTargets:R(Qt,24),mutated:B(P,F(`unknown`)),preserved:z({authoredState:I([`unchanged`,`changed`,`unknown`])}),recovery:z({action:I([`none`,`inspect`,`retry`,`new_intent`,`reconcile`,`sign_in`])},{retryAllowed:P})},{message:j(500),jobId:V,txId:V,candidates:R(z({id:V,kind:I([`object`,`character`,`rig`]),position:L(H)}),5)}),Sn=k({catalogue:Bt,variants:D,Vec3:H,FrameRange:ut,PositionSpec:vt,FacingSpec:yt,ObjectOp:St,CharacterOp:Ct,Framing:bt,Identity:pt,Host:mt,TargetGuard:Qt,Entity:Ht,ShotSummary:Gt,StudioContextV1:Zt,StudioTurn:tn,StudioStop:nn,Receipt:bn,ReceiptVariants:yn,Failure:xn,GeometryFacts:fn});function K(e,t,n=`INVALID_ARGUMENT`,r=`$`){if(e.oneOf||e.anyOf){let i=[],a=[];for(let o of e.oneOf??e.anyOf)try{i.push(K(o,t,n,r))}catch(e){if(!(e instanceof O))throw e;a.push({branch:o,error:e})}if(i.length===0&&a.length){let e=ot(t)&&ot(t.target)?t.target.kind:void 0,i=e!==void 0&&a.find(({branch:t})=>t.properties?.target?.properties?.kind?.const===e),o=!i&&Xe(r,a,t);throw o&&A(n,o,r),(i||a.reduce((e,t)=>t.error.details.path.length>e.error.details.path.length?t:e)).error}return i.length!==1&&e.oneOf&&A(n,`${r}: matches ${i.length} variants; send the fields of exactly one.`,r),i[0]}if(Object.hasOwn(e,`const`))return t!==e.const&&A(n,ze(r,e,t),r),t;if(e.type===`null`)return t!==null&&A(n,ze(r,e,t),r),null;if(e.type===`object`){ot(t)||A(n,ze(r,e,t),r);let i=e.additionalProperties===!0;for(let a of Object.keys(t))!Object.hasOwn(e.properties,a)&&!i&&A(n,Be(r,e,a),r);let a={};if(i)for(let n of Object.keys(t))Object.hasOwn(e.properties,n)||(a[n]=structuredClone(t[n]));for(let[i,o]of Object.entries(e.properties))Object.hasOwn(t,i)?a[i]=K(o,t[i],n,`${r}.${i}`):e.required.includes(i)?A(n,Ve(r,i),`${r}.${i}`):Object.hasOwn(o,`default`)&&(a[i]=structuredClone(o.default));return e[`x-studio-range`]&&a.endFrameExclusive<=a.startFrame&&A(n,`Frame range must be nonempty and half-open.`,r),a}if(e.type===`array`){(!Array.isArray(t)||t.length<e.minItems||t.length>e.maxItems)&&A(n,He(r,e,t),r);let i=t.map((t,i)=>K(e.items,t,n,`${r}[${i}]`));return e.uniqueItems&&new Set(i.map(e=>JSON.stringify(e))).size!==i.length&&A(n,Ue(r,i),r),i}if(e.type===`string`)return(typeof t!=`string`||!t.trim()||e.maxLength!==void 0&&[...t].length>e.maxLength||e.pattern&&!new RegExp(e.pattern).test(t))&&A(n,We(r,e,t),r),e.enum&&!e.enum.includes(t)&&A(n,Ge(r,e,t),r),t;if(e.type===`boolean`)return typeof t!=`boolean`&&A(n,ze(r,e,t),r),t;if(e.type===`number`||e.type===`integer`)return(typeof t!=`number`||!Number.isFinite(t)||e.type===`integer`&&!Number.isSafeInteger(t)||e.exclusiveMinimum!==void 0&&t<=e.exclusiveMinimum)&&A(n,Ke(r,e,t),r),(e.minimum!==void 0&&t<e.minimum||e.maximum!==void 0&&t>e.maximum)&&A(n,`${r}: Expected a number within [${[e.minimum,e.maximum].filter(e=>e!==void 0).join(`, `)}], got ${t}.`,r),t;throw Error(`Unsupported internal Studio schema.`)}var Cn=e=>K(pt,e,`INVALID_IDENTITY`);function wn(e){return[...new Set([...[`object`,`character`,`rig`].includes(e.selection?.kind)?[e.selection.id]:[],...e.activeCharacterId?[e.activeCharacterId]:[],...e.shot?.subjectIds??[],...e.jobs.flatMap(e=>[e.characterId,...e.targetIds??[]])])]}function Tn(e){let t=at(JSON.stringify(e)??``);t>65536&&A(`CONTEXT_TOO_LARGE`,`Studio context exceeds ${$e/1024} KiB.`,`$`,{bytes:t,maxBytes:$e});let n=K(Zt,e,`INVALID_CONTEXT`),r=new Set(n.entities.map(e=>e.id));r.size!==n.entities.length&&A(`INVALID_CONTEXT`,`Duplicate entity ID.`);for(let e of wn(n))r.has(e)||A(`TARGET_NOT_READY`,`Mandatory target is absent from context.`);n.activeCharacterId&&!n.entities.some(e=>e.id===n.activeCharacterId&&e.kind===`character`)&&A(`INVALID_CONTEXT`,`Active target is not a character.`),[`object`,`character`,`rig`].includes(n.selection?.kind)&&!n.entities.some(e=>e.id===n.selection.id&&e.kind===n.selection.kind)&&A(`INVALID_CONTEXT`,`Selection kind disagrees with the selected entity.`),n.selection?.kind===`scene`&&n.selection.id!==n.host.sceneId&&A(`INVALID_CONTEXT`,`Selected scene is not the bound scene.`);for(let e of n.entities)e.bounds&&[`x`,`y`,`z`].some(t=>e.bounds.min[t]>e.bounds.max[t])&&A(`INVALID_CONTEXT`,`Inverted entity bounds.`),e.kind===`object`&&typeof e.scale==`number`&&A(`INVALID_CONTEXT`,`Objects use three-axis scale.`),e.kind!==`object`&&ot(e.scale)&&A(`INVALID_CONTEXT`,`Cast uses scalar scale.`);let i=n.entityPage;if((i.returned!==n.entities.length||i.total<i.returned||i.truncated!==i.total>i.returned||(i.truncated?i.nextCursor===null:i.nextCursor!==null))&&A(`INVALID_CONTEXT`,`Entity pagination is inconsistent.`),n.entityIndex){let e=new Set(n.entityIndex.map(e=>e.id));e.size!==n.entityIndex.length&&A(`INVALID_CONTEXT`,`Duplicate entity index ID.`),(n.entityIndex.length>i.total||n.entities.some(t=>!e.has(t.id)))&&A(`INVALID_CONTEXT`,`Entity index must cover every detailed entity and no more than the total.`)}n.view.frame>=Math.max(1,n.scene.frameCount)&&A(`INVALID_CONTEXT`,`Playhead is outside the scene.`),new Set(n.shots.map(e=>e.id)).size!==n.shots.length&&A(`INVALID_CONTEXT`,`Duplicate shot ID.`);for(let e of[...n.shots,...n.shot?[n.shot]:[]])e.range.endFrameExclusive>n.scene.frameCount&&A(`INVALID_CONTEXT`,`Shot is outside the scene.`);return n.shot&&!n.shots.some(e=>e.id===n.shot.id&&e.range.startFrame===n.shot.range.startFrame&&e.range.endFrameExclusive===n.shot.range.endFrameExclusive)&&A(`INVALID_CONTEXT`,`Current shot and range must survive projection.`),n}function En(e){let t=new Set;for(let n of Array.isArray(e?.ops)?e.ops:[]){let e=ot(n)?n.target?.kind:void 0;if(it.includes(e)){t.add(e);for(let t of ot(n.set)?Object.keys(n.set):[])Object.hasOwn(Ft[e].properties,t)||A(`INVALID_ARGUMENT`,`Unknown ${e} path "${e}.${t}". Valid ${e} paths: ${It[e].join(`, `)}.`)}}t.size>1&&A(`INVALID_ARGUMENT`,`One domain per patch: split character, object, shot and stage edits into separate commands.`)}function Dn(e){(!ot(e)||!rt.includes(e.name))&&A(`UNKNOWN_TOOL`,`Unsupported Studio tool.`),e.name===`patch_elements`&&En(e.args);let{args:t}=K(z({name:I(rt),args:Rt[e.name]}),e);if(e.name===`inspect_studio`&&t.ids&&t.query!==void 0&&A(`INVALID_ARGUMENT`,`IDs and query are exclusive.`),e.name===`operate_studio`&&(!Object.keys(t).length||t.view&&!Object.keys(t.view).length)&&A(`INVALID_ARGUMENT`,`Transient operation must specify an action.`),t.ops){let e=t.ops.filter(e=>e.op===`create`&&e.name!==void 0).map(e=>e.name.normalize(`NFC`).trim());new Set(e).size!==e.length&&A(`DUPLICATE_NAME`,`Create names must be unique; resolve existing targets by ID.`);for(let e of t.ops)e.op===`update`&&Object.keys(e).length===2&&A(`INVALID_ARGUMENT`,`Update has no fields.`),e.facing&&e.rotationDeg&&A(`INVALID_ARGUMENT`,`Facing and rotationDeg are exclusive: facing sets yaw only (toward/away/same-as/yawDeg); rotationDeg {x,y,z} sets the full rotation, with y as the yaw.`),e.op===`group`&&e.childIds.includes(e.parentId)&&A(`INVALID_ARGUMENT`,`Cannot group an object under itself.`),e.op===`create`&&e.parent!==void 0&&e.name!==void 0&&e.parent.normalize(`NFC`).trim()===e.name.normalize(`NFC`).trim()&&A(`INVALID_ARGUMENT`,`Cannot group an object under itself.`);t.collisionPolicy===`avoid`&&!t.ops.some(e=>[`create`,`update`].includes(e.op)&&e.position?.relativeTo)&&A(`INVALID_ARGUMENT`,`collisionPolicy avoid needs at least one op with position.relativeTo (it nudges outward from that reference); other ops are placed as given.`)}if(e.name===`frame_shot`&&t.framing.exact&&JSON.stringify(t.framing.exact.position)===JSON.stringify(t.framing.exact.lookAt)&&A(`INVALID_ARGUMENT`,`Camera position and aim cannot coincide.`),e.name===`patch_elements`)for(let e of t.ops)Object.keys(e.set).length||A(`INVALID_ARGUMENT`,`Patch has no fields.`);return e.name===`verify_result`&&(!!t.receiptId==!!t.targets&&A(`INVALID_ARGUMENT`,`Exactly one of receiptId or targets is required.`),t.checks.includes(`motion`)&&t.range===void 0&&(t.range=`whole_clip`,Object.defineProperty(t,"rangeWasDefaulted",{value:!0,enumerable:!1}))),{name:e.name,args:t}}function q(e){if(e?.ok===!1){let t=K(xn,e,`INVALID_RECEIPT`);return at(JSON.stringify(t))>8192&&A(`INVALID_RECEIPT`,`Failure receipt exceeds 8 KiB.`),(t.mutated===!1&&t.preserved.authoredState!==`unchanged`||t.mutated===!0&&t.preserved.authoredState!==`changed`||t.mutated===`unknown`&&(t.preserved.authoredState!==`unknown`||t.recovery.action!==`reconcile`||t.recovery.retryAllowed===!0))&&A(`INVALID_RECEIPT`,`Failure must preserve uncertainty and actual state evidence.`),k(t)}let t=K(bn,e,`INVALID_RECEIPT`);if(at(JSON.stringify(t))>8192&&A(`INVALID_RECEIPT`,`Receipt exceeds 8 KiB; use a detail cursor.`),t.delta.some(e=>!t.affectedIds.includes(e.id)||!Object.keys(e.after).length)&&A(`INVALID_RECEIPT`,`Readback must identify affected targets and actual state.`),t.ops){let e=t.ops.some(e=>e.status===`partial`);t.ops.some((e,t)=>e.index!==t)&&A(`INVALID_RECEIPT`,`Operation results must report every operation in order.`),t.ops.some(e=>e.status===`partial`!=!!e.droppedPaths?.length)&&A(`INVALID_RECEIPT`,`A partial operation must name the paths the domain dropped, and only a partial one may.`),t.status===`applied`&&e&&A(`INVALID_RECEIPT`,`Applied status cannot hide a dropped path.`),t.status===`partial`&&!e&&A(`INVALID_RECEIPT`,`Partial status requires at least one dropped path.`),t.status===`noop`&&t.ops.some(e=>e.status===`applied`)&&A(`INVALID_RECEIPT`,`A noop cannot report an applied operation.`)}if(t.status===`started`||t.status===`completed`?(t.revision.after<t.revision.before&&!t.nextHost&&A(`INVALID_RECEIPT`,`Completion revisions must not move backwards in one document.`),t.status===`started`&&(t.authored||t.undo||t.revision.before!==t.revision.after)&&A(`INVALID_RECEIPT`,`Started jobs cannot claim an authored commit.`),t.kind===`mutation`&&(!t.authored||!t.undo||t.revision.after<=t.revision.before||!t.delta.length)&&A(`INVALID_RECEIPT`,`A completed composite mutation needs retained undo and advancing revision evidence.`),t.undo&&(!t.authored||!t.affectedIds.length)&&A(`INVALID_RECEIPT`,`An undo entry requires an authored result and affected targets.`)):t.status===`noop`||t.status===`transient`?((t.authored||t.undo!==null||t.revision.before!==t.revision.after)&&A(`INVALID_RECEIPT`,`Non-authored operations cannot create history or advance authored revision.`),t.status===`noop`&&(t.mutated!==!1||t.delta.length)&&A(`INVALID_RECEIPT`,`Noop must prove no mutation.`),t.status===`transient`&&(!t.view||t.view.after<t.view.before||!t.delta.length)&&A(`INVALID_RECEIPT`,`Transient receipt requires view revisions and actual readback.`)):((!t.authored||!t.undo||t.revision.after!==t.revision.before+1||!t.affectedIds.length||!t.delta.length||t.mutated===!1)&&A(`INVALID_RECEIPT`,`Authored mutation requires one revision and one undo entry with actual readback.`),t.delta.length<t.affectedIds.length&&!t.detailCursor&&A(`INVALID_RECEIPT`,`Omitted batch readback requires a detail cursor.`)),t.status===`undone`&&(new Set(t.restoredTargets.map(e=>e.targetId)).size!==t.affectedIds.length||t.restoredTargets.some(e=>!t.affectedIds.includes(e.targetId)||Object.keys(ft).some(n=>e[n]!==t.host[n])))&&A(`INVALID_RECEIPT`,`Undo must identify every restored target and its new token in the bound host.`),t.status===`installed`){(!t.jobId||!t.artifactId||!t.installed||!t.verification||!t.affectedIds.includes(t.installed.characterId))&&A(`INVALID_RECEIPT`,`Installation requires correlated target, artifact and verification evidence.`);let{frameCount:e,blocks:n}=t.installed,r=0;for(let e of n)(e.startFrame!==r||e.endFrameExclusive<=r||e.endFrameExclusive-r>120)&&A(`INVALID_RECEIPT`,`Installed schedule is not contiguous or bounded.`),r=e.endFrameExclusive;(r!==e||t.installed.durationSeconds!==e/24||t.verification.range.startFrame!==0||t.verification.range.endFrameExclusive!==e||t.verification.evaluatedFrames>e)&&A(`INVALID_RECEIPT`,`Installed schedule and verification coverage disagree.`),t.verification.status===`verified`&&t.verification.evaluatedFrames!==e&&A(`INVALID_RECEIPT`,`Verified motion requires whole-clip coverage.`),t.verification.status===`unverified`&&t.explicitUnverifiedAcceptance!==!0&&t.acceptance!==`advisory-policy`&&A(`INVALID_RECEIPT`,`Unverified installation requires explicit user or advisory-policy acceptance.`)}else(t.installed||t.verification||t.jobId&&![`started`,`completed`].includes(t.status)||t.artifactId||t.repairs||t.explicitUnverifiedAcceptance!==void 0)&&A(`INVALID_RECEIPT`,`Installation evidence is exclusive to installed receipts.`);return k(t)}var On=[`begin`,`mark`,`rollback`,`finish`,`cancel`],kn=(e,t)=>Object.fromEntries(On.map(n=>[`agent.turn.${n}`,e({turnId:t})]));function An(e,t){if(e===`agent.turn.mark`)return t.mark={point:t.session?.savepoint()??null,affectedIds:new Set(t.affectedIds),since:new Set},{txId:t.txId,affectedIds:[],toasts:[]};let{mark:n}=t;if(!n)throw new O(`STALE_TARGET`,`The agent turn has no mark to roll back to.`);return t.mark=null,t.session?.rollback(n.point??void 0),t.affectedIds=n.affectedIds,{txId:t.txId,affectedIds:[...n.since],toasts:[]}}var J=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Y=(e,t)=>{throw new O(e,t)},jn=(e,t,n)=>e?.then?e.then(t,n):t(e),Mn=e=>e.slice(-12).map(e=>({code:`STUDIO_TOAST`,message:[...e.message].slice(0,120).join(``)})),Nn=0;function Pn({registry:e,ports:t}){let n=new Map,r=new Map,i=new Map,a=new Set,o=new Map,s=new Map,c=null;function l(n,r,i){if(i.origin===`ui`)return;if(n.exposure===`ui-only`&&Y(`CAPABILITY_MISSING`,n.uiOnlyHint??`This command is available only from the Studio UI.`),n.id===`load_scenes`){let t=e=>[...new Set(e.map(e=>e.id))].sort();if(J(t(r.document.scenes),t(e.state().scenes)))return}else if(n.exposure!==`confirm`||n.requiresConfirmation?.(e.state(),r)===!1)return;let a=o.get(i.confirmationToken);(!a||a.id!==n.id||!J(a.args,r)||!J(a.host,t.read().host)||a.expires<(t.now??Date.now)())&&Y(`CONFIRMATION_REQUIRED`,n.confirmationReason??`This command needs user confirmation.`),o.delete(i.confirmationToken)}let u=e=>{for(let t of a)t(e);t.emit?.(e)},d=Sn.TargetGuard.properties.targetId,f=e=>({type:`object`,properties:e,required:Object.keys(e),additionalProperties:!1}),p={type:`object`,properties:{},required:[],additionalProperties:!0},m={...kn(f,d),"run.begin":f({id:d,args:p}),"run.update":f({txId:d,args:p}),"run.commit":f({txId:d}),"run.cancel":f({txId:d}),"job.await":{...f({jobId:d}),properties:{jobId:d,timeoutMs:{type:`integer`,minimum:1,maximum:3e5,default:3e4}}},"job.cancel":f({jobId:d}),"edit.undo":{...f({receiptId:d}),required:[]},"edit.redo":{...f({receiptId:d}),required:[]}},h=e=>(t.clearTimeout??clearTimeout)(e);function g(e,n=!1,i=new O(`CANCELLED`,`Transaction was cancelled.`)){r.delete(e.txId),h(e.timer),e.workTimer!==void 0&&h(e.workTimer),e.controller.abort(i),e.session.cancel({restore:J(e.before.host,t.read().host)}),u({type:`transaction.cancelled`,txId:e.txId,expired:n})}function _(e){e.timer!==void 0&&h(e.timer),e.timer=(t.setTimeout??setTimeout)(()=>g(e,!0),t.transactionIdleMs??3e4)}function ee(n,a,o,u){if(n.startsWith(`agent.turn.`)){if((o.origin!==`agent`||o.turnId!==a.turnId)&&Y(`CAPABILITY_MISSING`,`Only the owning agent turn can control this transaction.`),n===`agent.turn.begin`)return(c||r.size)&&Y(`TARGET_BUSY`,`Finish the open transaction first.`),c={txId:a.turnId,before:u,affectedIds:new Set,toasts:[],session:null},v(n,c,o,u);c?.txId!==a.turnId&&Y(`STALE_TARGET`,`The agent turn is no longer open.`);let e=c;if(n===`agent.turn.mark`||n===`agent.turn.rollback`)return v(n,An(n,e),o,u);if(n===`agent.turn.cancel`)return c=null,e.session?.cancel(),v(n,e,o,u);try{e.historyEntryId=e.session?.commit().historyEntryId}catch(t){throw e.session?.cancel(),t}finally{c=null}return v(n,e,o,e.before)}let d=n===`edit.undo`||n===`edit.redo`;if(c&&!n.startsWith(`job.`)&&!(d&&!c.session)&&Y(`TARGET_BUSY`,`Finish the agent turn before traversing history or opening another transaction.`),d){let e=n===`edit.redo`,r=t.history?.(e),i=a.receiptId?t.receipt(a.receiptId):s.get(r)??(r?{receiptId:r,host:u.host,affectedIds:[u.host.sceneId],undo:{historyEntryId:r,entries:1,canUndoDirect:!0}}:null);if(!a.receiptId&&!i)return q({ok:!0,status:`noop`,action:n,commandId:o.commandId,receiptId:crypto.randomUUID(),host:u.host,authored:!1,mutated:!1,revision:{before:u.revision,after:u.revision},affectedIds:[],delta:[],checks:{coverage:`native-history-restoration`},undo:null,warnings:[]});(!i?.undo||!t.isRetained(i))&&Y(`UNDO_EXPIRED`,`The receipt no longer has a retained history entry.`),J(i.host,u.host)||Y(`STALE_SCENE`,`The receipt belongs to another document.`),(e?r!==i.undo.historyEntryId:!t.canUndo(i))&&Y(`UNDO_CONFLICT`,`Another edit owns the history boundary.`),(e?t.redo:t.undo)();let c=t.read(),l=i.affectedIds,d=l.map(e=>({...u.host,targetId:e,token:t.readTarget?.(e)??`removed-${crypto.randomUUID()}`}));return q({ok:!0,status:e?`applied`:`undone`,commandId:o.commandId,receiptId:crypto.randomUUID(),host:u.host,authored:!0,revision:{before:u.revision,after:c.revision},affectedIds:l,delta:l.slice(0,8).map(e=>({id:e,after:{token:d.find(t=>t.targetId===e).token}})),checks:{coverage:`native-history-restoration`},undo:{...i.undo,canUndoDirect:e},warnings:[],...e?{action:n,mutated:!0}:{undoneReceiptId:i.receiptId,restoredTargets:d},...l.length>8?{detailCursor:o.commandId}:{}})}if(n.startsWith(`job.`)){let e=i.get(a.jobId);(!e||!J(e.host,u.host))&&Y(`STALE_TARGET`,`Job is not in this document.`),n===`job.cancel`&&!e.outcome&&e.controller.abort(new O(`CANCELLED`,`Job was cancelled.`));let r;return(n===`job.await`&&!e.outcome?Promise.race([e.completion,new Promise((e,n)=>{r=(t.setTimeout??setTimeout)(()=>n(new O(`TIMEOUT`,`Job is still running.`)),a.timeoutMs)})]):e.completion).then(t=>q({...t,commandId:o.commandId,...t.ok?{receiptId:crypto.randomUUID()}:{},jobId:e.id})).finally(()=>{r!==void 0&&h(r)})}let f;if(n===`run.begin`){r.size&&Y(`TARGET_BUSY`,`Finish or cancel the open command transaction first.`);let n=e.prepare(a.id,a.args);l(n.entry,n.args,o),n.entry.kind!==`mutation`&&Y(`INVALID_ARGUMENT`,`Only mutations can open a transaction.`),f={txId:crypto.randomUUID(),entry:n.entry,before:u,origin:o.origin,targetId:n.args.characterId??null,controller:new AbortController,session:t.beginAction(n.entry.undoDomain,n.args.characterId??null),affectedIds:new Set,toasts:[]},r.set(f.txId,f),_(f)}else{if(f=r.get(a.txId),(!f||!J(f.before.host,u.host))&&Y(`STALE_TARGET`,`Transaction is no longer open in this document.`),o.origin!==f.origin&&Y(`TARGET_BUSY`,`This transaction belongs to another origin.`),f.updating&&n!==`run.cancel`&&Y(`TARGET_BUSY`,`A transaction update is still running.`),n===`run.update`){let i=e.prepare(f.entry.id,a.args);f.entry.undoDomain===`motion`&&i.args.characterId!==f.targetId&&Y(`INVALID_ARGUMENT`,`A motion transaction keeps its original target.`);let s=[],c=t.captureToasts?.(e=>s.push(typeof e==`string`?{message:e}:e)),l={origin:o.origin,signal:f.controller.signal,check(){f.controller.signal.throwIfAborted(),(!r.has(f.txId)||!J(f.before.host,t.read().host))&&Y(`STALE_TARGET`,`Transaction is no longer current.`)}},d=e=>{c?.(),h(f.workTimer),f.updating=!1,l.check(),s.length&&t.read().revision===u.revision&&Y(`TARGET_NOT_READY`,s.at(-1).message);for(let t of e.affectedIds)f.affectedIds.add(t);return f.toasts.push(...s),_(f),v(n,f,o,u)},p=e=>{throw c?.(),h(f.workTimer),f.updating=!1,!(e instanceof O)&&s.length&&t.read().revision===u.revision&&(e=new O(`TARGET_NOT_READY`,s.at(-1).message)),r.has(f.txId)&&g(f),e};try{f.updating=!0,h(f.timer),f.workTimer=(t.setTimeout??setTimeout)(()=>g(f,!0,new O(`TIMEOUT`,`${f.entry.id} exceeded its deadline.`)),f.entry.timeoutMs??3e4);let n=f.session.run(()=>e.invoke(f.entry,i.args,l));if(!n?.then)return d(n);let r=new Promise((e,t)=>f.controller.signal.addEventListener(`abort`,()=>t(f.controller.signal.reason),{once:!0}));return Promise.race([n,r]).then(d,p)}catch(e){return p(e)}}if(n===`run.cancel`&&g(f),n===`run.commit`){r.delete(f.txId),h(f.timer);try{f.historyEntryId=f.session.commit().historyEntryId}catch(e){throw f.session.cancel({restore:!1}),e}}}return v(n,f,o,n===`run.commit`?f.before:u)}function v(e,n,r,i){let a=t.read();return q({ok:!0,status:`completed`,kind:`transaction`,commandId:r.commandId,receiptId:crypto.randomUUID(),host:i.host,action:e,txId:n.txId,authored:!!n.historyEntryId,revision:{before:i.revision,after:a.revision},affectedIds:[...n.affectedIds],delta:[],checks:{coverage:`wire-transaction`},warnings:Mn(n.toasts),undo:n.historyEntryId?{historyEntryId:n.historyEntryId,entries:1,canUndoDirect:!0}:null})}function te(e,n,r,i){let a=i??t.read().revision!==n.revision;return q({ok:!1,commandId:e.commandId,host:n.host,code:le(r),phase:a?`commit`:`admission`,affectedIds:[],expectedTargets:[],currentTargets:[],mutated:a,preserved:{authoredState:a?`changed`:`unchanged`},recovery:{action:`inspect`,retryAllowed:!1},message:[...String(r.message||r)].slice(0,500).join(``)})}let ne=(e=[],t=[],n=0,r=12)=>{let i=[...n?[{code:`READBACK_TRUNCATED`,count:n,message:`Readback lists 8 of ${8+n} affected ids; inspect_studio scope entities with ids for the rest.`}]:[],...e,...Mn(t)];return i.length<=r?i:[...i.slice(0,r-1),{code:`WARNINGS_TRUNCATED`,count:i.length-r+1,message:`${i.length-r+1} more warnings omitted.`}]};function re(e,n,r,i,a,o=[],s=null){let c=t.read(),l=c.revision!==r.revision,u=a??(l?s?.txId:null)??null;e.kind===`mutation`&&l&&!a&&!s&&Y(`UNCERTAIN_APPLY`,`${e.id} changed the scene without one undoable entry.`);let d=e.kind===`job`||e.kind===`document`||e.kind===`mutation`&&l&&(s||c.revision>r.revision+1),f=d||l?i.affectedIds:e.kind===`transient`?[r.host.sceneId]:[];if(s&&l)for(let e of f)s.affectedIds.add(e),s.mark?.since.add(e);let p=a=>q({ok:!0,commandId:n.commandId,receiptId:crypto.randomUUID(),host:r.host,action:e.id,summary:i.summary,status:d?`completed`:e.kind===`transient`?`transient`:l?`applied`:`noop`,authored:l,...d?{kind:e.kind,...i.output===void 0?{}:{output:i.output},...J(r.host,c.host)?{}:{nextHost:c.host}}:e.kind===`transient`?{view:{before:r.viewRevision??0,after:c.viewRevision??0}}:{mutated:l},revision:{before:r.revision,after:c.revision},affectedIds:f,delta:f.slice(0,8).map(e=>({id:e,after:t.readback?.(e,c,a>0)??{removed:!0}})),checks:{coverage:`studio-action:${e.id}`,...i.checks},warnings:ne(i.warnings,o,Math.max(0,f.length-8),a>1?4:12),undo:u?{historyEntryId:u,entries:1,canUndoDirect:!s}:null,...f.length>8?{detailCursor:n.commandId}:{}});for(let e=0;;e++)try{return p(e)}catch(t){if(e>=2||t?.code!==`INVALID_RECEIPT`||!/8 KiB/.test(t.message))throw t}}function y(a,o={},d={}){let f={origin:`ui`,commandId:crypto.randomUUID(),...d};f.origin===`ui`&&(a===`edit.undo`||a===`edit.redo`)&&t.finishHistoryGesture?.();let p=t.read(),g=t.journal();c&&!J(c.before.host,p.host)&&(c.session?.cancel({restore:!1}),c=null);let _=f.origin===`agent`&&f.turnId===c?.txId?c:null,v=(e,n,r,i=!1)=>_?(_.session??=t.beginAction(e,r),{result:_.session.run(()=>t.beginAction(e,r).run(n)),historyEntryId:null}):t.recordAction(e,n,r,i),ne=!1,y,b,ie,x,ae=!1,S,C=new AbortController,oe=()=>{b!==void 0&&h(b),ie!==void 0&&h(ie)},se=[],ce=()=>se.length&&t.read().revision===p.revision?new O(`TARGET_NOT_READY`,se.at(-1).message):null,le=e=>{if(x?.background){let t=x.completionCommandId??=crypto.randomUUID();g.begin(t),e=q({...e,commandId:t,jobId:x.id})}let n=g.record(e);n.undo?.canUndoDirect&&!a.startsWith(`edit.`)&&s.set(n.undo.historyEntryId,n);for(let[e,n]of s)t.isRetained?.(n)===!1&&s.delete(e);return t.remember?.(n),n},ue=e=>{oe(),y?.(),y=null,e instanceof O||(e=ce()??e),f.origin===`ui`&&e.uiMessage&&t.showRefusal?.(e.uiMessage);let n=te(f,p,e,x?ae:void 0),r=ne?le(n):n;return x&&!x.completion&&(x.outcome=r,x.completion=Promise.resolve(r),u({type:`job.completed`,jobId:x.id,receipt:r})),r};try{f.origin!==`ui`&&!J(Cn(f.host),p.host)&&Y(`STALE_SCENE`,`The live document changed.`),f.turnId&&!_&&a!==`agent.turn.begin`&&Y(`STALE_TARGET`,`The agent turn is no longer open.`);let s=JSON.stringify({id:a,args:o,...f});if(!g.begin(f.commandId,s))return g.get(f.commandId)??n.get(f.commandId)??te(f,p,new O(`UNCERTAIN_APPLY`,`Command is still executing.`));ne=!0;let{entry:c,args:d}=m[a]?{args:K(m[a],o)}:e.prepare(a,o);if(f.origin!==`ui`&&(!c?.readOnly&&![`job.await`,`job.cancel`,`agent.turn.mark`,`agent.turn.rollback`,`agent.turn.finish`,`agent.turn.cancel`].includes(a)&&f.expectedRevision!==p.revision&&Y(`STALE_SCENE`,`Authored state changed; obtain fresh intent.`),!c?.readOnly&&p.busy&&!_&&!r.has(d.txId)&&!a.startsWith(`job.`)&&Y(`TARGET_BUSY`,`Finish the current editor gesture first.`)),m[a])return jn(ee(a,d,f,p),le,ue);r.size&&Y(`TARGET_BUSY`,`Finish or cancel the open command transaction first.`),_&&c.kind===`document`&&Y(`TARGET_BUSY`,`Finish the agent turn before changing documents.`),l(c,d,f),y=t.captureToasts?.(e=>se.push(typeof e==`string`?{message:e}:e));let h=c.domain??c.undoDomain,w=c.target?.(d,p)??d.characterId??d.shotId??d.objectId,de=w?t.readTarget?.(w):null,fe=h?p.domainRevisions?.[h]:null,pe=()=>{let e=t.read();de=w?t.readTarget?.(w):null,fe=h?e.domainRevisions?.[h]:null},me=new Set,T={origin:f.origin,signal:C.signal,check(){C.signal.throwIfAborted();let e=t.read();J(e.host,p.host)||Y(`STALE_TARGET`,`The open document or scene changed while the job was running.`),h&&e.domainRevisions?.[h]!==fe&&Y(`STALE_TARGET`,`The ${h} data changed while the job was running (revision ${fe} to ${e.domainRevisions?.[h]}); an edit landed between the request and its result.`),w&&t.readTarget?.(w)!==de&&Y(`STALE_TARGET`,`${w} changed while the job was running.`)},commit(e){T.check(),h||Y(`INVALID_ARGUMENT`,`A committing job must declare its domain.`);let t=v(h,e,w??null);return t?.then&&Y(`INVALID_ARGUMENT`,`Job publication must be synchronous; prepare before commit.`),S=t.historyEntryId,ae||=!!S,x&&pe(),t.result},run(t,n={}){x?T.check():C.signal.throwIfAborted();let r=e.prepare(t,n);l(r.entry,r.args,f);let i=()=>e.invoke(r.entry,r.args,T),a=r.entry.kind===`mutation`?v(r.entry.undoDomain,i,r.args.characterId??null,!0):{result:i()};return x&&pe(),jn(a,e=>jn(e.result,t=>{x&&(T.check(),pe(),ae||=!!e.historyEntryId);for(let e of t.affectedIds)me.add(e);return t}))}};c.kind===`job`&&(x={id:crypto.randomUUID(),host:p.host,controller:C,background:!1},i.set(x.id,x)),b=(t.setTimeout??setTimeout)(()=>{let e=new O(`TIMEOUT`,`${c.id} exceeded its deadline.`);C.abort(e)},x&&c.background===!0?3e5:c.timeoutMs??3e4);let he=()=>{let t=e.invoke(c,d,T);if(!t?.then)return t;let n=new Promise((e,t)=>C.signal.addEventListener(`abort`,()=>t(C.signal.reason),{once:!0}));return Promise.race([t,n])},ge=c.kind===`mutation`?v(c.undoDomain,he,d.characterId??null):{result:he(),historyEntryId:null},_e=({result:e,historyEntryId:t})=>jn(e,e=>{oe(),y?.(),y=null;let n=ce();if(n)throw n;return le(re(c,f,p,{...e,affectedIds:[...new Set([...e.affectedIds,...me])]},t??S,se,_))}),ve=ge?.then?ge.then(_e):_e(ge),ye=ve?.then?ve.catch(ue):ve;if(x){x.completion=Promise.resolve(ye).then(e=>(x.outcome=e,u({type:`job.completed`,jobId:x.id,receipt:e}),e));let e=()=>{x.background=!0;let e=t.read();return g.record(q({ok:!0,commandId:f.commandId,receiptId:crypto.randomUUID(),host:p.host,action:c.id,status:`started`,kind:`job`,jobId:x.id,authored:!1,revision:{before:e.revision,after:e.revision},affectedIds:[],delta:[],checks:{coverage:`studio-action:${c.id}`},warnings:[],undo:null}))};if(ye?.then&&f.wait===!1)return e();if(ye?.then&&c.background===!0){let r=Promise.race([x.completion,new Promise(n=>{ie=(t.setTimeout??setTimeout)(()=>n(e()),c.timeoutMs??3e4)})]).finally(()=>n.delete(f.commandId));return n.set(f.commandId,r),r}}if(ye?.then){let e=(x?.completion??ye).finally(()=>n.delete(f.commandId));return n.set(f.commandId,e),e}return ye}catch(e){return ue(e)}}function b(...e){Nn++;try{let t=y(...e);return t?.then?t.finally(()=>{Nn--}):(Nn--,t)}catch(e){throw Nn--,e}}return{run:b,confirm(n,r={}){let i=e.prepare(n,r),a=crypto.randomUUID();return o.set(a,{id:n,args:i.args,host:t.read().host,expires:(t.now??Date.now)()+3e5}),a},subscribe(e){return a.add(e),()=>a.delete(e)},dispose(){c?.session?.cancel(),c=null;for(let e of r.values())g(e);for(let e of i.values())e.outcome||e.controller.abort(new O(`CANCELLED`,`Studio closed.`));a.clear()}}}var Fn=Object.freeze([`pose_edit`,`object_insert`,`cutout_insert`,`object_transform`,`shot_add`,`shot_edit`,`camera_key_record`,`rail_edit`,`prompt_block_add`,`prompt_block_edit`]);function X(e,t){if(e===t)return!0;if(typeof e==`number`&&typeof t==`number`)return Math.abs(e-t)<1e-8;if(!e||!t||typeof e!=`object`||typeof t!=`object`)return!1;if(e instanceof Map||t instanceof Map)return e instanceof Map&&t instanceof Map&&e.size===t.size&&[...e].every(([e,n])=>t.has(e)&&X(n,t.get(e)));let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.hasOwn(t,n)&&X(e[n],t[n]))}var In=e=>({bones:e?.bones??{},rootY:e?.rootY??0}),Ln=(e=[])=>e.map(({frame:e,framing:t})=>({frame:e,framing:t})),Rn=e=>({...e,camera:b(e.camera),cameraKeys:Ln(e.cameraKeys)});function zn(e,t,n){if(t===n)return null;if(e===`pose`)return X(t,n)?null:`pose_edit`;if(e===`objects`){let e=n.find(e=>!t.some(t=>t.id===e.id));return e?e.renderer===`cutout`?`cutout_insert`:`object_insert`:X(t,n)?null:`object_transform`}if(e===`characters`){if(n.some(e=>!t.some(t=>t.id===e.id)))return`object_insert`;for(let e of n){let n=t.find(t=>t.id===e.id);if(n&&!X(In(n.pose),In(e.pose)))return`pose_edit`}let e=e=>e.map(({id:e,x:t,y:n=0,z:r,rot:i,scale:a=1,hidden:o=!1,model:s,tint:c,subject:l,identityImage:u})=>({id:e,x:t,y:n,z:r,rot:i,scale:a,hidden:o,model:s,tint:c,subject:l,identityImage:u}));return X(e(t),e(n))?null:`object_transform`}if(e===`shots`){if(n.some(e=>!t.some(t=>t.id===e.id)))return`shot_add`;for(let e of n){let n=t.find(t=>t.id===e.id);if(!n)continue;let r=b(e.camera),i=b(n.camera);if([`cameraRail`,`craneHeight`,`railFollow`,`dollyTiming`].some(e=>!X(r[e],i[e])))return`rail_edit`;let a=e.cameraKeys??[],o=n.cameraKeys??[];if(a.length>o.length||a.some(e=>{let t=o.find(t=>t.frame===e.frame);return t&&!X(t.framing,e.framing)}))return`camera_key_record`}return X(t.map(Rn),n.map(Rn))?null:`shot_edit`}return null}function Bn(e){let t=new Set;return(n,r,i,a)=>{if(![`craft`,`playground`].includes(n)||t.has(n))return!1;let o=zn(r,i,a);return o?(t.add(n),e(`${n}:first_edit`,{edit_kind:o,definition_version:1}),!0):!1}}var Vn=`modulepreload`,Hn=function(e){return`/`+e},Un={},Wn=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=Hn(t,n),t=s(t),t in Un)return;Un[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:Vn,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},Gn=Object.freeze([`read`,`camera`,`scene_write`,`prompt_authoring`,`frame_capture`,`motion_generate`,`motion_apply`,`project_io`,`other`]),Kn=Object.freeze([`workflow_read`,`workflow_write`,`workflow_run`,`frame_capture`,`image_generate`,`scene_write`,`other`]),qn=Object.freeze([`workflow:run_requested`,`workflow:run_succeeded`,`workflow:run_failed`,`workflow:run_cancelled`,`workflow:result_applied`,`agent:turn_requested`,`agent:tool_executed`,`agent:turn_succeeded`,`agent:turn_failed`,`agent:turn_cancelled`,`agent:result_applied`,`mcp:tool_requested`,`mcp:tool_executed`,`mcp:result_applied`]),Jn=Object.freeze({"workflow:run_requested":[`surface`,`run_id`,`node_count_bucket`],"workflow:run_succeeded":[`run_id`,`duration_bucket`],"workflow:run_failed":[`run_id`,`duration_bucket`,`failure_code`],"workflow:run_cancelled":[`run_id`,`duration_bucket`,`failure_code`],"workflow:result_applied":[`run_id`],"agent:turn_requested":[`surface`,`turn_id`],"agent:tool_executed":[`turn_id`,`tool_category`,`outcome`,`duration_bucket`],"agent:turn_succeeded":[`turn_id`,`duration_bucket`],"agent:turn_failed":[`turn_id`,`duration_bucket`,`failure_code`],"agent:turn_cancelled":[`turn_id`,`duration_bucket`,`failure_code`],"agent:result_applied":[`turn_id`],"mcp:tool_requested":[`tool_category`,`request_id`],"mcp:tool_executed":[`tool_category`,`outcome`,`duration_bucket`,`request_id`],"mcp:result_applied":[`request_id`]}),Yn=Object.freeze({surface:new Set([`studio`,`workflow`]),node_count_bucket:new Set([`0`,`1-3`,`4-10`,`gte11`]),duration_bucket:new Set([`lt1s`,`1-3s`,`3-10s`,`10-30s`,`gte30s`]),tool_category:new Set([...Gn,...Kn]),outcome:new Set([`succeeded`,`failed`,`uncertain`,`cancelled`])}),Xn=Object.freeze({source:new Set([`agent`,`manual`]),outcome:new Set([`ok`,`error`]),surface:new Set([`assets`,`agent`,`mcp`])}),Zn=`cozyclay.analyticsOptOut`,Qn=`cozyclay.internalQa`,$n=`cozyclay.analyticsActivation`,er=`cozyclay.useCaseAsked`,tr=Object.freeze({pose:Object.freeze([`pose_edit`]),camera:Object.freeze([`camera_key_record`,`rail_edit`]),object:Object.freeze([`object_insert`,`cutout_insert`,`object_transform`]),shot:Object.freeze([`shot_add`,`shot_edit`]),prompt:Object.freeze([`prompt_block_add`,`prompt_block_edit`])}),nr=Object.freeze(Object.keys(tr).map(e=>`${e}_edit_bucket`)),rr=Object.freeze([`animation`,`film`,`game`,`ad_mv`,`personal`,`other`,`skip`]),ir=Object.freeze([`team`,`solo`,`skip`]),ar=new Set([`storyboard`,`animation`]),or=Object.freeze([`latest`,`outdated`,`unknown`]),sr=Object.freeze([`https://cozyclay.org`,`https://www.cozyclay.org`]),cr=Object.freeze({"install:first_launch":[`heard_from`],"app:session_started":[],"app:session_ended":[`duration_bucket`,`action_count_bucket`,`scenes_touched`,...nr],"app:error":[`error_kind`,`error_type`,`error_source`,`error_file`,`error_line`,`error_col`],"device:profile":[`gpu_vendor`,`gpu_class`,`webgl`,`cpu_bucket`,`memory_bucket`,`frame_rate_bucket`],"survey:use_case":[`use_case`,`team`],"feature:used":[`name`],"hosted:composer_viewed":[],"hosted:login_started":[],"hosted:ticket_created":[],"hosted:result_opened":[],"hosted:opened_in_studio":[],"scene:created":[`scene_source`,`previs_mode`],"storyboard:panel_created":[`source`],"storyboard:panel_stylized":[`outcome`],"cast:proxy_added":[`surface`],"scene:loaded":[`scene_source`],"project:saved":[`object_count_bucket`,`shot_count_bucket`],"project:opened":[`age_bucket`],"craft:first_action":[`action_kind`],"craft:first_edit":[`edit_kind`,`definition_version`],"motion:backend_state":[`backend`,`host_configured`],"motion:generate_requested":[`surface`,`input_mode`,`request_id`],"motion:preflight_blocked":[`reason`,`surface`,`request_id`],"motion:preflight_passed":[`backend`,`surface`,`request_id`],"motion:job_started":[`backend`,`input_mode`,`request_id`],"motion:job_succeeded":[`backend`,`duration_bucket`,`input_mode`,`request_id`],"motion:job_failed":[`backend`,`duration_bucket`,`input_mode`,`error_code`,`request_id`],"motion:result_applied":[`request_id`,`backend`],"export:blocking_frame_succeeded":[`format`],"export:video_succeeded":[`format`],"export:keyframe_pack":[`entries`,`source`],"export:attempt_started":[`attempt_id`,`export_kind`,`format`,`surface`],"export:attempt_succeeded":[`attempt_id`,`export_kind`,`format`,`surface`,`duration_bucket`],"export:attempt_failed":[`attempt_id`,`export_kind`,`format`,`surface`,`duration_bucket`,`failure_code`],"export:attempt_cancelled":[`attempt_id`,`export_kind`,`format`,`surface`,`duration_bucket`,`failure_code`],"sample:played":[`from`],"playground:opened":[],"playground:first_action":[`action_kind`],"playground:first_edit":[`edit_kind`,`definition_version`],"activation:completed":[`activation_path`],"tutorial:started":[`surface`,`tutorial_version`,`start_source`],"tutorial:step_entered":[`surface`,`tutorial_version`,`step_kind`],"tutorial:step_completed":[`surface`,`tutorial_version`,`step_kind`,`elapsed_bucket`],"tutorial:completed":[`surface`,`tutorial_version`,`elapsed_bucket`],"tutorial:dismissed":[`surface`,`tutorial_version`,`step_kind`],sculpt_run:[`outcome`,`rounds`,`final_iou`,`duration_ms`,`had_target`],...Jn}),lr=new Set([`pose_edit`,`pose_save`,`camera_fly`,`orbit`,`dolly_rail`,`crane_graph`,`timeline_scrub`,`prompt_block_add`,`shot_add`,`shot_cut`,`export_pose`,`export_frame`,`export_video`,`export_depth_video`,`export_keyframe_pack`,`fal_motion_open`,`mcp_connected`,`auto_color`,`plan_view`,`camera_tutorial`]),ur=Object.freeze([`x`,`hn`,`reddit`,`github`,`friend`,`other`,`site`,`playground`]),dr=new Set(ur),fr=new Set([`prompt`,`text`,`url`,`path`,`file`]),pr=Object.freeze({backend:new Set([`none`,`local_kimodo`,`hosted`,`fal`]),host_configured:new Set([!0,!1]),surface:new Set([`timeline`,`line_edit`,`trail`,`mcp`,`fal_card`,`agent`]),input_mode:new Set([`prompt`,`pose`,`edit`,`a_to_b`,`still`]),reason:new Set([`unconfigured`,`unreachable`,`unsupported_route`,`locked`,`missing_input`]),error_code:new Set([`aborted`,`unsupported_route`,`generation_failed`,`quota`,`unknown`]),duration_bucket:new Set([`lt1s`,`1-3s`,`3-10s`,`10-30s`,`gte30s`])}),mr=new Set([`unsupported_codec`,`encode_failed`,`render_failed`,`aborted`,`unknown`]),hr=Object.freeze({export_kind:new Set([`video`,`depth_video`,`frame`,`keyframe_pack`,`workflow_send`,`animation_project`,`contact_sheet`,`panel_pack`,`animatic`]),format:new Set([`mp4`,`png`,`zip`,`cclayproject`]),surface:new Set([`studio`,`workflow`,`embed`]),duration_bucket:new Set([`lt1s`,`1-3s`,`3-10s`,`10-30s`,`gte30s`]),failure_code:mr}),gr=Object.freeze({surface:new Set([`studio`,`playground`]),tutorial_version:new Set([1]),start_source:new Set([`query`,`settings`,`landing`]),step_kind:new Set([`fly`,`walk`,`dolly`,`orbit`,`shot`,`rail`,`play`]),elapsed_bucket:new Set([`lt1s`,`1-3s`,`3-10s`,`10-30s`,`gte30s`])}),_r=Object.freeze([`done`,`cancelled`,`failed`]),vr=10,yr=864e5,br=Object.freeze({workflow:new Set([`aborted`,`capture_failed`,`generation_failed`,`unknown`]),agent:new Set([`aborted`,`auth`,`rate_limited`,`tool_failed`,`upstream`,`unknown`])}),xr=Object.freeze({error_kind:new Set([`error`,`unhandled_rejection`]),error_type:new Set([`Error`,`TypeError`,`RangeError`,`ReferenceError`,`SyntaxError`,`EvalError`,`URIError`,`AggregateError`,`AbortError`,`TimeoutError`,`NotAllowedError`,`NotSupportedError`,`NotFoundError`,`NotReadableError`,`InvalidStateError`,`QuotaExceededError`,`SecurityError`,`NetworkError`,`DataCloneError`,`OperationError`,`EncodingError`,`UnknownError`,`DOMException`,`non_error`,`other`]),error_source:new Set([`app`,`extension`,`external`,`unknown`])}),Sr=/^[A-Za-z0-9_.-]{1,80}\.(?:m?js|jsx|ts|tsx)$/,Cr=Object.freeze({gpu_vendor:new Set([`nvidia`,`amd`,`intel`,`apple`,`qualcomm`,`arm`,`software`,`other`,`unknown`]),gpu_class:new Set([`discrete`,`integrated`,`software`,`unknown`]),webgl:new Set([`webgl2`,`webgl1`,`none`]),cpu_bucket:new Set([`1-4`,`5-8`,`9-16`,`gte17`,`unknown`]),memory_bucket:new Set([`lt4`,`4-7`,`gte8`,`unknown`]),frame_rate_bucket:new Set([`lt20`,`20-40`,`40-55`,`gte55`,`unknown`])}),Z=null,wr=!1,Q=!1,Tr=!1,Er=null,Dr=!1,Or=!1,kr=0,Ar=0,jr=0,Mr=!1,Nr=!1,Pr=new Set,Fr=new Map(Object.entries(tr).flatMap(([e,t])=>t.map(t=>[t,e]))),Ir=1e3,Lr=Object.fromEntries(Object.keys(tr).map(e=>[e,0])),Rr=null,zr=-1/0,Br=10,Vr=new Set,Hr=!1,Ur=!1,Wr=new Set([`app:session_started`,`app:session_ended`,`install:first_launch`,`motion:backend_state`,`app:error`,`device:profile`]);function Gr(){try{return globalThis.localStorage??null}catch{return null}}function Kr(e){try{return Gr()?.getItem(e)??null}catch{return null}}function qr(e,t){try{Gr()?.setItem(e,t)}catch{}}function Jr(e){return typeof e==`string`?e.trim().toLowerCase().replace(/[/.]+$/g,``):``}function Yr(e){return e===void 0?[...sr]:e.split(`,`).map(Jr).filter(Boolean)}function Xr(e,t){let n=Jr(e);return Array.isArray(t)&&t.some(e=>n===Jr(e))}var Zr=e=>typeof e==`boolean`?!0:typeof e==`number`?Number.isFinite(e):typeof e==`string`&&e.length<=32&&!/\s/.test(e);function Qr(e,t){let n=cr[e]??[];if(!t||typeof t!=`object`||Array.isArray(t))return{};let r={};for(let i of n)if(!(fr.has(i)||!Object.hasOwn(t,i))&&!(e===`feature:used`&&(i!==`name`||!lr.has(t[i])))&&!(e===`install:first_launch`&&(i!==`heard_from`||!dr.has(t[i])))){if(e.startsWith(`export:attempt_`)){if(i===`attempt_id`){if(typeof t[i]!=`string`||!/^[a-f0-9]{32}$/.test(t[i]))continue}else if(!hr[i]?.has(t[i]))continue}if(!(e===`export:keyframe_pack`&&(i===`source`&&t[i]!==`workflow`||i===`entries`&&(!Number.isFinite(t[i])||t[i]<0)))&&!((e===`craft:first_edit`||e===`playground:first_edit`)&&(i===`edit_kind`&&!Fn.includes(t[i])||i===`definition_version`&&t[i]!==1))){if(e.startsWith(`motion:`)){if(i===`request_id`){if(typeof t[i]!=`string`||!/^[a-f0-9]{32}$/.test(t[i]))continue}else if(!pr[i]?.has(t[i]))continue}if(!(e.startsWith(`tutorial:`)&&!gr[i]?.has(t[i]))){if(e.startsWith(`workflow:`)||e.startsWith(`agent:`)||e.startsWith(`mcp:`)){if(i===`run_id`||i===`turn_id`||i===`request_id`){if(typeof t[i]!=`string`||!/^[a-f0-9]{32}$/.test(t[i]))continue}else if(i===`surface`){if(!Yn.surface.has(t[i])||e.startsWith(`workflow:`)&&t[i]!==`workflow`)continue}else if(i===`node_count_bucket`&&!Yn.node_count_bucket.has(t[i]))continue;else if(i===`duration_bucket`&&!Yn.duration_bucket.has(t[i]))continue;else if(i===`tool_category`){if(!(e.startsWith(`agent:`)?Kn:Gn).includes(t[i]))continue}else if(i===`outcome`){if(!(e===`mcp:tool_executed`?[`succeeded`,`failed`,`uncertain`,`cancelled`]:[`succeeded`,`failed`,`cancelled`]).includes(t[i]))continue}else if(i===`failure_code`&&!br[e.startsWith(`agent:`)?`agent`:`workflow`].has(t[i]))continue}if(e===`app:error`){if(i===`error_file`){typeof t[i]==`string`&&Sr.test(t[i])&&(r[i]=t[i]);continue}if(i===`error_line`||i===`error_col`){Number.isInteger(t[i])&&t[i]>=0&&t[i]<=1e7&&(r[i]=t[i]);continue}if(!xr[i]?.has(t[i]))continue}if(!(e===`device:profile`&&!Cr[i]?.has(t[i]))){if(e===`sculpt_run`){let e=t[i];i===`outcome`&&_r.includes(e)||i===`rounds`&&Number.isInteger(e)&&e>=0&&e<=vr?r[i]=e:i===`final_iou`&&typeof e==`number`&&e>=0&&e<=1?r[i]=Math.round(e*100)/100:i===`duration_ms`&&typeof e==`number`&&e>=0&&e<=yr?r[i]=Math.round(e):i===`had_target`&&typeof e==`boolean`&&(r[i]=e);continue}i===`previs_mode`&&!ar.has(t[i])||(e.startsWith(`storyboard:`)||e.startsWith(`cast:`))&&!Xn[i]?.has(t[i])||e===`survey:use_case`&&(i===`use_case`&&!rr.includes(t[i])||i===`team`&&!ir.includes(t[i]))||Zr(t[i])&&(r[i]=t[i])}}}}return r}Object.freeze([...lr]);function $r(e){let t=Number.isFinite(e)?Math.max(0,Math.floor(e)):0;return t===0?`0`:t<=3?`1-3`:t<=10?`4-10`:`gte11`}function ei(e){return!Number.isFinite(e)||e<6e4?`lt1m`:e<3e5?`1-5m`:e<9e5?`5-15m`:e<18e5?`15-30m`:`gte30m`}function ti(e){return!Number.isFinite(e)||e<0||e<36e5?`lt1h`:e<864e5?`1-24h`:e<6048e5?`1-7d`:e<2592e6?`7-30d`:`gte30d`}function ni(){let e=String(globalThis.navigator?.userAgentData?.platform||globalThis.navigator?.platform||``).toLowerCase();return e.includes(`mac`)?`macos`:e.includes(`win`)?`windows`:e.includes(`linux`)?`linux`:e.includes(`android`)?`android`:e.includes(`iphone`)||e.includes(`ipad`)||e.includes(`ios`)?`ios`:`unknown`}function ri(e){return!Number.isFinite(e)||e<1e3?`lt1s`:e<3e3?`1-3s`:e<1e4?`3-10s`:e<3e4?`10-30s`:`gte30s`}function ii(e){return!Number.isFinite(e)||e<=0?`unknown`:e<=4?`1-4`:e<=8?`5-8`:e<=16?`9-16`:`gte17`}function ai(e){return!Number.isFinite(e)||e<=0?`unknown`:e<4?`lt4`:e<8?`4-7`:`gte8`}function oi(e){return!Number.isFinite(e)||e<=0?`unknown`:e<20?`lt20`:e<40?`20-40`:e<55?`40-55`:`gte55`}function si(e){let t=String(e??``).toLowerCase();return t.trim()?/swiftshader|llvmpipe|softpipe|software|basic render driver/.test(t)?{gpu_vendor:`software`,gpu_class:`software`}:/nvidia|geforce|quadro|\brtx\b|\bgtx\b|tesla/.test(t)?{gpu_vendor:`nvidia`,gpu_class:`discrete`}:/\bamd\b|radeon|\bati\b/.test(t)?{gpu_vendor:`amd`,gpu_class:/radeon\(tm\) graphics|radeon graphics|vega \d+ graphics|\b(?:610|660|680|740|760|780|880|890)m\b/.test(t)?`integrated`:`discrete`}:/intel|iris|uhd graphics|hd graphics/.test(t)?{gpu_vendor:`intel`,gpu_class:/arc(?:\(tm\))? [ab]\d{3}/.test(t)?`discrete`:`integrated`}:/apple|\bm[1-9](?: pro| max| ultra)?\b/.test(t)?{gpu_vendor:`apple`,gpu_class:`integrated`}:/adreno|qualcomm/.test(t)?{gpu_vendor:`qualcomm`,gpu_class:`integrated`}:/\bmali\b|\barm\b|powervr/.test(t)?{gpu_vendor:`arm`,gpu_class:`integrated`}:{gpu_vendor:`other`,gpu_class:`unknown`}:{gpu_vendor:`unknown`,gpu_class:`unknown`}}var ci=/((?:https?|chrome-extension|moz-extension|safari-extension|safari-web-extension):\/\/[^\s()]+?):(\d+):(\d+)/g;function li(e,t){if(typeof e!=`string`||!e)return`unknown`;if(/^(?:chrome|moz|safari|safari-web)-extension:/.test(e))return`extension`;try{return t&&new URL(e).origin===t?`app`:`external`}catch{return`unknown`}}function ui(e){try{let t=new URL(e).pathname.split(`/`).pop()??``;return Sr.test(t)?t:null}catch{return null}}function di(e){try{if(e===null||typeof e!=`object`&&typeof e!=`function`)return`non_error`;let t=typeof e.name==`string`?e.name:``;return t&&t!==`non_error`&&t!==`other`&&xr.error_type.has(t)?t:typeof DOMException<`u`&&e instanceof DOMException?`DOMException`:e instanceof Error?`other`:`non_error`}catch{return`other`}}function fi({error:e,filename:t,lineno:n,colno:r,kind:i=`error`}={},a=globalThis.location?.origin??``){let o={error_kind:i===`unhandled_rejection`?`unhandled_rejection`:`error`,error_type:di(e),error_source:`unknown`},s=typeof t==`string`&&t?{url:t,line:n,col:r}:null;if(!s||li(s.url,a)!==`app`){let t=``;try{t=typeof e?.stack==`string`?e.stack.slice(0,4e3):``}catch{t=``}let n=[...t.matchAll(ci)].map(e=>({url:e[1],line:Number(e[2]),col:Number(e[3])}));s=n.find(e=>li(e.url,a)===`app`)??s??n[0]??null}if(!s||(o.error_source=li(s.url,a),o.error_source!==`app`))return o;let c=ui(s.url);return c&&(o.error_file=c),Number.isInteger(s.line)&&s.line>=0&&(o.error_line=s.line),Number.isInteger(s.col)&&s.col>=0&&(o.error_col=s.col),o}function pi(e,t=Date.now()){let n=Fr.get(e);if(!n)return!1;let r=n===Rr&&t-zr<Ir;return Rr=n,zr=t,r||(Lr[n]+=1),e===`pose_edit`&&Pi(`pose_edit`),!r}function mi(){return Object.fromEntries(Object.entries(Lr).map(([e,t])=>[`${e}_edit_bucket`,$r(t)]))}function hi(e,t=`unknown`){try{if(e?.name===`AbortError`)return`aborted`;if(mr.has(e?.exportFailureCode))return e.exportFailureCode}catch{}return mr.has(t)?t:`unknown`}function gi(e,t={}){let n=!1,r=null,i=NaN,a=()=>performance.now(),o=$,s=()=>{try{return a()}catch{return NaN}},c=(e,t)=>{try{Promise.resolve(o(e,Qr(e,t))).catch(()=>{})}catch{}};try{a=t.now??a,o=t.capture??o;let n=[...globalThis.crypto.getRandomValues(new Uint8Array(16))].map(e=>e.toString(16).padStart(2,`0`)).join(``);r={...Qr(`export:attempt_started`,e),attempt_id:n},i=s(),c(`export:attempt_started`,r)}catch{r=null}let l=(e,t,a)=>{if(!n&&(n=!0,r))try{let n={...r,duration_bucket:ri(s()-i)};e===`failed`&&(n.failure_code=hi(t,a),n.failure_code===`aborted`&&(e=`cancelled`)),c(`export:attempt_${e}`,n)}catch{}};return{succeed(){l(`succeeded`)},fail(e,t=`unknown`){l(`failed`,e,t)}}}var _i=[`$current_url`,`$initial_current_url`,`$referrer`,`$initial_referrer`],vi=[`utm_source`,`utm_medium`,`utm_campaign`,`utm_content`,`utm_term`,`gad_source`,`mc_cid`,`gclid`,`gclsrc`,`dclid`,`gbraid`,`wbraid`,`fbclid`,`msclkid`,`twclid`,`li_fat_id`,`igshid`,`ttclid`,`rdt_cid`,`epik`,`qclid`,`sccid`,`irclid`,`_kx`,`ph_keyword`];function yi(e){return typeof e==`string`?e.split(`#`)[0].split(`?`)[0]:e}function bi(e){if(!e||typeof e!=`object`||!e.properties)return e;let t=[e.properties,e.properties.$set,e.properties.$set_once,e.$set,e.$set_once].filter(e=>e&&typeof e==`object`&&!Array.isArray(e));for(let e of t){for(let t of _i)typeof e[t]==`string`&&(e[t]=yi(e[t]));for(let t of vi)delete e[t],delete e[`$initial_${t}`];for(let t of Object.keys(e))t.startsWith(`$session_entry_`)&&delete e[t]}return e}function xi(e){return e?.activationTracked!==!0}function Si(){return Tr?!0:Di()?.distribution===`npm`?Di()?.telemetryEnabled!==!0:Kr(Zn)===`1`}function Ci(){try{let e=Gr();if(!e)return;let t=[];for(let n=0;n<e.length;n+=1){let r=e.key(n);r&&r.startsWith(`ph_`)&&r.endsWith(`_posthog`)&&t.push(r)}for(let n of t)e.removeItem(n)}catch{}}async function wi(e){if(Di()?.distribution!==`npm`)return{ok:!0,enabled:e};try{let t=await fetch(`/__cozyclay/telemetry`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({enabled:e})});if(!t.ok)return{ok:!1,enabled:!e};let n=await t.json();return globalThis.__COZYCLAY_RUNTIME__=n,{ok:!0,enabled:n.telemetryEnabled===!0}}catch{return{ok:!1,enabled:!e}}}async function Ti(e){let t=e===!0,n=Di()?.distribution===`npm`;Tr=t;let r=await wi(!t);if(Tr=!1,!r.ok)return Si();let i=!r.enabled;if(qr(Zn,i?`1`:`0`),i&&Ci(),n&&!i)return globalThis.location?.reload(),!1;if(!Z&&!i&&await Mi(),!Z)return i;try{i?(Q=!1,Z.opt_out_capturing()):(Z.opt_in_capturing(),Q=wr)}catch{Q=!1}return i}function Ei(){return{BASE_URL:`/`,DEV:!1,MODE:`production`,PROD:!0,SSR:!1,VITE_COZYCLAY_LIVE_PORT:`5184`}}function Di(){let e=globalThis.__COZYCLAY_RUNTIME__;return!e||typeof e!=`object`||Array.isArray(e)?null:e}function Oi(e){try{let t=new URL(e);return t.protocol===`http:`&&[`127.0.0.1`,`localhost`].includes(t.hostname)}catch{return!1}}function ki({env:e=Ei(),origin:t=globalThis.location?.origin??``,runtime:n=Di()}={}){return e.PROD?n?.distribution===`npm`?n.telemetryEnabled===!0?Oi(t)?typeof n.apiKey!=`string`||n.apiKey.length===0?{kind:`disabled`,reason:`no key`}:typeof n.installationId!=`string`||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(n.installationId)?{kind:`disabled`,reason:`invalid anonymous identity`}:{kind:`enabled`,distribution:`npm`,apiKey:n.apiKey,apiHost:n.apiHost||`https://t.cozyclay.org`,appVersion:n.appVersion||null,installationId:n.installationId,firstLaunch:n.firstLaunch===!0,firstLaunchHeardFrom:dr.has(n.firstLaunchHeardFrom)?n.firstLaunchHeardFrom:null,installKind:[`npx`,`global`,`clone`].includes(n.installKind)?n.installKind:`npx`,originKind:`local`,internalQa:n.internalQa===!0,updateStatus:or.includes(n.updateStatus)?n.updateStatus:`unknown`}:{kind:`disabled`,reason:`unapproved origin`}:{kind:`disabled`,reason:`opted out`}:e.VITE_POSTHOG_KEY?Xr(t,Yr(e.VITE_POSTHOG_ALLOWED_ORIGINS))?{kind:`enabled`,distribution:`hosted`,apiKey:e.VITE_POSTHOG_KEY,apiHost:e.VITE_POSTHOG_HOST||`https://us.i.posthog.com`,appVersion:e.VITE_APP_VERSION||null,installationId:null,firstLaunch:!1,firstLaunchHeardFrom:null,installKind:null,originKind:`hosted`,internalQa:Kr(Qn)===`1`,updateStatus:null}:{kind:`disabled`,reason:`unapproved origin`}:{kind:`disabled`,reason:`no key`}:{kind:`disabled`,reason:`not production`}}function Ai(e){return{distribution:e.distribution,...e.appVersion?{app_version:e.appVersion}:{},origin_kind:e.originKind,os:ni(),...e.installKind?{install_kind:e.installKind}:{},...e.updateStatus?{update_status:e.updateStatus}:{},internal_qa:e.internalQa}}function ji(e){let t=ki({env:e});return t.kind===`disabled`?t.reason:Si()?`opted out`:null}async function Mi(){if(wr||Er)return Er;if(Di()?.distribution!==`npm`){let e=new URLSearchParams(globalThis.location?.search??``).getAll(`internal_qa`);e.length===1&&(e[0]===`1`||e[0]===`0`)&&qr(Qn,e[0])}let e=Ei(),t=ji(e);if(t){Or||=(console.info(`[analytics] disabled: `+t),!0);return}Er=(async()=>{try{let t=await Wn(()=>import(`./module-MzlRiBjI.js`),[]);if(Si())return;let n=ki({env:e});if(n.kind===`disabled`)return;Z=t.default??t,Z.init(n.apiKey,{api_host:n.apiHost,defaults:`2025-05-24`,autocapture:!1,capture_pageview:!1,capture_pageleave:!1,person_profiles:`never`,persistence:n.distribution===`npm`?`memory`:`localStorage`,respect_dnt:!0,disable_session_recording:!0,capture_dead_clicks:!1,capture_performance:!1,disable_capture_url_hashes:!0,save_campaign_params:!1,save_referrer:!1,mask_personal_data_properties:!0,request_batching:!1,advanced_disable_feature_flags:!0,disable_external_dependency_loading:!0,disable_surveys:!0,ui_host:`https://us.posthog.com`,bootstrap:n.installationId?{distinctID:n.installationId,isIdentifiedID:!1}:void 0,before_send:bi}),wr=!0,Q=!0;let r=Ai(n);if(Z.register(r),globalThis.__cozyclayAnalytics={instance:Z},Z.capture(`$pageview`),kr=Date.now(),Gi(n,r),Ri(),Wi(),n.distribution===`npm`&&($(`app:session_started`),n.firstLaunch)){let e=n.firstLaunchHeardFrom;$(`install:first_launch`,e?{heard_from:e}:{})}}catch{console.info(`[analytics] initialization failed`)}})(),await Er}function $(e,t={}){if(!(!wr||!Q||!Z))try{if(Si())return;let n=Qr(e,t);Wr.has(e)||(Ar+=1,(e===`scene:created`||e===`scene:loaded`)&&(jr+=1)),Z.capture(e,n)}catch{}}function Ni(e,{hadTarget:t=!1}={}){return _r.includes(e?.stage)?{outcome:e.stage,rounds:e.round,...Number.isFinite(e.iou)?{final_iou:Math.round(e.iou*100)/100}:{},duration_ms:Math.round(e.elapsedMs),had_target:!!t}:null}function Pi(e){return!wr||!Q||!Z||!lr.has(e)||Pr.has(e)?!1:(Pr.add(e),$(`feature:used`,{name:e}),!0)}function Fi(){try{return wr&&Q&&!!Z&&!Si()}catch{return!1}}function Ii(){return Fi()&&Kr(er)!==`1`}function Li(e,t){qr(er,`1`),$(`survey:use_case`,{use_case:rr.includes(e)?e:`skip`,team:ir.includes(t)?t:`skip`})}function Ri(){if(Hr||typeof window>`u`||typeof window.addEventListener!=`function`)return;Hr=!0;let e=e=>{try{let t=fi(e),n=[t.error_kind,t.error_type,t.error_source,t.error_file,t.error_line,t.error_col].join(`|`);if(Vr.has(n)||Vr.size>=Br)return;Vr.add(n),$(`app:error`,t)}catch{}};window.addEventListener(`error`,t=>{try{if(typeof t?.message==`string`&&t.message.startsWith(`ResizeObserver loop`)||!t?.error&&!t?.filename)return;e({error:t?.error,filename:t?.filename,lineno:t?.lineno,colno:t?.colno,kind:`error`})}catch{}}),window.addEventListener(`unhandledrejection`,t=>{e({error:t?.reason,kind:`unhandled_rejection`})})}function zi(){try{let e=globalThis.document?.createElement?.(`canvas`);if(!e?.getContext)return{webgl:`none`,renderer:``};let t=e.getContext(`webgl2`),n=t?`webgl2`:`none`;if(t||(t=e.getContext(`webgl`),t&&(n=`webgl1`)),!t)return{webgl:n,renderer:``};let r=``;try{let e=t.getExtension(`WEBGL_debug_renderer_info`);r=String(t.getParameter(e?e.UNMASKED_RENDERER_WEBGL:t.RENDERER)??``)}catch{r=``}try{t.getExtension(`WEBGL_lose_context`)?.loseContext()}catch{}return{webgl:n,renderer:r}}catch{return{webgl:`none`,renderer:``}}}var Bi=8e3,Vi=3e3,Hi=6e4;function Ui(){return new Promise(e=>{let t=globalThis.requestAnimationFrame;if(typeof t!=`function`){e(null);return}let n=()=>globalThis.document?.visibilityState===`hidden`,r=Date.now(),i=()=>{if(Date.now()-r>Hi){e(null);return}if(n()){setTimeout(i,2e3);return}let a=0,o=0,s=r=>{if(n()){setTimeout(i,2e3);return}if(o||=r,a+=1,r-o>=Vi){e((a-1)*1e3/(r-o));return}t(s)};t(s)};setTimeout(i,Bi)})}async function Wi(){if(!(Ur||globalThis.document===void 0||typeof globalThis.requestAnimationFrame!=`function`)){Ur=!0;try{let{webgl:e,renderer:t}=zi(),n=si(t),r=await Ui();$(`device:profile`,{...n,webgl:e,cpu_bucket:ii(globalThis.navigator?.hardwareConcurrency),memory_bucket:ai(globalThis.navigator?.deviceMemory),frame_rate_bucket:oi(r)})}catch{}}}function Gi(e,t){if(Nr||typeof window>`u`)return;Nr=!0;let n=()=>{if(!(Mr||!kr)){Mr=!0;try{if(!Q||!Z||Si()||Z.has_opted_out_capturing())return;let n={api_key:e.apiKey,event:`app:session_ended`,properties:{...t,distinct_id:Z.get_distinct_id(),duration_bucket:ei(Date.now()-kr),action_count_bucket:$r(Ar),scenes_touched:Math.min(20,jr),...mi()}},r=JSON.stringify(n),i=`${e.apiHost.replace(/\/$/,``)}/e/`;typeof globalThis.navigator?.sendBeacon==`function`?globalThis.navigator.sendBeacon(i,new Blob([r],{type:`application/json`})):fetch(i,{method:`POST`,body:r,keepalive:!0,headers:{"content-type":`application/json`}})}catch{}}};window.addEventListener(`pagehide`,n,{once:!0}),window.addEventListener(`beforeunload`,n,{once:!0})}function Ki(e){if(!(!wr||!Q||Dr)){if(!xi({activationTracked:Kr($n)===`1`})){Dr=!0;return}Dr=!0,qr($n,`1`),$(`activation:completed`,{activation_path:e})}}export{ge as $,tt as A,q as B,Bn as C,$e as D,et as E,Sn as F,ye as G,Tn as H,k as I,ke as J,ve as K,wn as L,zt as M,D as N,Nt as O,O as P,T as Q,jt as R,Wn as S,Pn as T,Cn as U,Dn as V,K as W,ue as X,De as Y,w as Z,Ii as _,l as _t,Fi as a,se as at,Ki as b,ti as c,y as ct,Mi as d,e as dt,he as et,pi as f,u as ft,Ti as g,g as gt,Ni as h,h as ht,Yn as i,oe as it,nt as j,it as k,hi as l,ae as lt,Qr as m,c as mt,qn as n,le as nt,$r as o,ie as ot,Li as p,d as pt,Oe as q,Jn as r,C as rt,ri as s,b as st,Kn as t,_e as tt,Si as u,x as ut,gi as v,p as vt,zn as w,Pi as x,$ as y,at as z};