dsh-open-artifact 0.8.1 → 0.8.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 (77) hide show
  1. package/lib/client.js +2 -2
  2. package/lib/index.js +41 -4
  3. package/package.json +1 -1
  4. package/skills/open-artifact/SKILL.md +1 -1
  5. package/vendor/artifact-types/data/scripts/cli.mjs +1 -1
  6. package/vendor/artifact-types/data/scripts/editors/data/assets/{index-CZiM2XTm.js → index-B041Zu27.js} +1 -1
  7. package/vendor/artifact-types/data/scripts/editors/data/index.html +1 -1
  8. package/vendor/artifact-types/{design/scripts/editors/design/assets/index-jhwXmpbV.js → data/scripts/editors/design/assets/index-D6-vjsn9.js} +1 -1
  9. package/vendor/artifact-types/data/scripts/editors/design/index.html +1 -1
  10. package/vendor/artifact-types/{design/scripts/editors/design-system/assets/index-7LPrsXBY.js → data/scripts/editors/design-system/assets/index-BoT2v4hc.js} +1 -1
  11. package/vendor/artifact-types/data/scripts/editors/design-system/index.html +1 -1
  12. package/vendor/artifact-types/{design/scripts/editors/slides/assets/index-y09Z-wXP.js → data/scripts/editors/slides/assets/index-b9M479Ro.js} +2 -2
  13. package/vendor/artifact-types/data/scripts/editors/slides/assets/{src-C48N4IXt.js → src-CxNLgI5_.js} +1 -1
  14. package/vendor/artifact-types/data/scripts/editors/slides/index.html +1 -1
  15. package/vendor/artifact-types/{design/scripts/editors/whiteboard/assets/index-DbekE4ru.js → data/scripts/editors/whiteboard/assets/index-TrzGo_VR.js} +1 -1
  16. package/vendor/artifact-types/data/scripts/editors/whiteboard/index.html +1 -1
  17. package/vendor/artifact-types/design/scripts/cli.mjs +1 -1
  18. package/vendor/artifact-types/{slides/scripts/editors/data/assets/index-CZiM2XTm.js → design/scripts/editors/data/assets/index-B041Zu27.js} +1 -1
  19. package/vendor/artifact-types/design/scripts/editors/data/index.html +1 -1
  20. package/vendor/artifact-types/{data/scripts/editors/design/assets/index-jhwXmpbV.js → design/scripts/editors/design/assets/index-D6-vjsn9.js} +1 -1
  21. package/vendor/artifact-types/design/scripts/editors/design/index.html +1 -1
  22. package/vendor/artifact-types/{design-system/scripts/editors/design-system/assets/index-7LPrsXBY.js → design/scripts/editors/design-system/assets/index-BoT2v4hc.js} +1 -1
  23. package/vendor/artifact-types/design/scripts/editors/design-system/index.html +1 -1
  24. package/vendor/artifact-types/{slides/scripts/editors/slides/assets/index-y09Z-wXP.js → design/scripts/editors/slides/assets/index-b9M479Ro.js} +2 -2
  25. package/vendor/artifact-types/{slides/scripts/editors/slides/assets/src-C48N4IXt.js → design/scripts/editors/slides/assets/src-CxNLgI5_.js} +1 -1
  26. package/vendor/artifact-types/design/scripts/editors/slides/index.html +1 -1
  27. package/vendor/artifact-types/{design-system/scripts/editors/whiteboard/assets/index-DbekE4ru.js → design/scripts/editors/whiteboard/assets/index-TrzGo_VR.js} +1 -1
  28. package/vendor/artifact-types/design/scripts/editors/whiteboard/index.html +1 -1
  29. package/vendor/artifact-types/design-system/scripts/cli.mjs +1 -1
  30. package/vendor/artifact-types/{design/scripts/editors/data/assets/index-CZiM2XTm.js → design-system/scripts/editors/data/assets/index-B041Zu27.js} +1 -1
  31. package/vendor/artifact-types/design-system/scripts/editors/data/index.html +1 -1
  32. package/vendor/artifact-types/{slides/scripts/editors/design/assets/index-jhwXmpbV.js → design-system/scripts/editors/design/assets/index-D6-vjsn9.js} +1 -1
  33. package/vendor/artifact-types/design-system/scripts/editors/design/index.html +1 -1
  34. package/vendor/artifact-types/{data/scripts/editors/design-system/assets/index-7LPrsXBY.js → design-system/scripts/editors/design-system/assets/index-BoT2v4hc.js} +1 -1
  35. package/vendor/artifact-types/design-system/scripts/editors/design-system/index.html +1 -1
  36. package/vendor/artifact-types/design-system/scripts/editors/slides/assets/{index-y09Z-wXP.js → index-b9M479Ro.js} +2 -2
  37. package/vendor/artifact-types/{design/scripts/editors/slides/assets/src-C48N4IXt.js → design-system/scripts/editors/slides/assets/src-CxNLgI5_.js} +1 -1
  38. package/vendor/artifact-types/design-system/scripts/editors/slides/index.html +1 -1
  39. package/vendor/artifact-types/{data/scripts/editors/whiteboard/assets/index-DbekE4ru.js → design-system/scripts/editors/whiteboard/assets/index-TrzGo_VR.js} +1 -1
  40. package/vendor/artifact-types/design-system/scripts/editors/whiteboard/index.html +1 -1
  41. package/vendor/artifact-types/slides/scripts/cli.mjs +1 -1
  42. package/vendor/artifact-types/{design-system/scripts/editors/data/assets/index-CZiM2XTm.js → slides/scripts/editors/data/assets/index-B041Zu27.js} +1 -1
  43. package/vendor/artifact-types/slides/scripts/editors/data/index.html +1 -1
  44. package/vendor/artifact-types/{design-system/scripts/editors/design/assets/index-jhwXmpbV.js → slides/scripts/editors/design/assets/index-D6-vjsn9.js} +1 -1
  45. package/vendor/artifact-types/slides/scripts/editors/design/index.html +1 -1
  46. package/vendor/artifact-types/slides/scripts/editors/design-system/assets/{index-7LPrsXBY.js → index-BoT2v4hc.js} +1 -1
  47. package/vendor/artifact-types/slides/scripts/editors/design-system/index.html +1 -1
  48. package/vendor/artifact-types/{data/scripts/editors/slides/assets/index-y09Z-wXP.js → slides/scripts/editors/slides/assets/index-b9M479Ro.js} +2 -2
  49. package/vendor/artifact-types/{design-system/scripts/editors/slides/assets/src-C48N4IXt.js → slides/scripts/editors/slides/assets/src-CxNLgI5_.js} +1 -1
  50. package/vendor/artifact-types/slides/scripts/editors/slides/index.html +1 -1
  51. package/vendor/artifact-types/slides/scripts/editors/whiteboard/assets/{index-DbekE4ru.js → index-TrzGo_VR.js} +1 -1
  52. package/vendor/artifact-types/slides/scripts/editors/whiteboard/index.html +1 -1
  53. package/vendor/artifact-types/whiteboard/scripts/cli.mjs +1 -1
  54. package/vendor/artifact-types/whiteboard/scripts/editors/data/assets/index-B041Zu27.js +126 -0
  55. package/vendor/artifact-types/whiteboard/scripts/editors/data/index.html +1 -1
  56. package/vendor/artifact-types/whiteboard/scripts/editors/design/assets/index-D6-vjsn9.js +215 -0
  57. package/vendor/artifact-types/whiteboard/scripts/editors/design/index.html +1 -1
  58. package/vendor/artifact-types/whiteboard/scripts/editors/design-system/assets/index-BoT2v4hc.js +139 -0
  59. package/vendor/artifact-types/whiteboard/scripts/editors/design-system/index.html +1 -1
  60. package/vendor/artifact-types/whiteboard/scripts/editors/slides/assets/index-b9M479Ro.js +569 -0
  61. package/vendor/artifact-types/whiteboard/scripts/editors/slides/assets/src-CxNLgI5_.js +1 -0
  62. package/vendor/artifact-types/whiteboard/scripts/editors/slides/index.html +1 -1
  63. package/vendor/artifact-types/whiteboard/scripts/editors/whiteboard/assets/index-TrzGo_VR.js +141 -0
  64. package/vendor/artifact-types/whiteboard/scripts/editors/whiteboard/index.html +1 -1
  65. package/vendor/frame-host/client/comments.js +1 -1
  66. package/vendor/frame-host/frame-host.mjs +1 -1
  67. package/vendor/home/assets/{index-CPvXdSVh.js → index-aY1m8xEm.js} +1 -1
  68. package/vendor/home/index.html +1 -1
  69. package/vendor/open-artifact.mjs +56 -38
  70. package/vendor/shell/assets/{index-DE0jNtst.js → index-ElpFysv2.js} +1 -1
  71. package/vendor/shell/index.html +1 -1
  72. package/vendor/artifact-types/whiteboard/scripts/editors/data/assets/index-CZiM2XTm.js +0 -126
  73. package/vendor/artifact-types/whiteboard/scripts/editors/design/assets/index-jhwXmpbV.js +0 -215
  74. package/vendor/artifact-types/whiteboard/scripts/editors/design-system/assets/index-7LPrsXBY.js +0 -139
  75. package/vendor/artifact-types/whiteboard/scripts/editors/slides/assets/index-y09Z-wXP.js +0 -569
  76. package/vendor/artifact-types/whiteboard/scripts/editors/slides/assets/src-C48N4IXt.js +0 -1
  77. package/vendor/artifact-types/whiteboard/scripts/editors/whiteboard/assets/index-DbekE4ru.js +0 -141
package/lib/client.js CHANGED
@@ -1,4 +1,4 @@
1
- // dsh-open-artifact 0.8.1: the DSH plugin (browser half). Built by scripts/build.mjs; do not edit.
1
+ // dsh-open-artifact 0.8.2: the DSH plugin (browser half). Built by scripts/build.mjs; do not edit.
2
2
  window.__ModuleLoader__.load({
3
3
  id: "dsh-open-artifact",
4
4
  factory: (require) => {
@@ -145,7 +145,7 @@ window.__ModuleLoader__.load({
145
145
  },
146
146
  intent: {
147
147
  type: "string",
148
- description: "quickstart: what is being made (design, slides, whiteboard, document, data, other), or a few words about it."
148
+ description: "quickstart: what is being made (design, design-system, slides, whiteboard, document, data, other), or a few words about it."
149
149
  },
150
150
  scope: {
151
151
  type: "string",
package/lib/index.js CHANGED
@@ -1,4 +1,4 @@
1
- // dsh-open-artifact 0.8.1: the DSH plugin (server half). Built by scripts/build.mjs; do not edit.
1
+ // dsh-open-artifact 0.8.2: the DSH plugin (server half). Built by scripts/build.mjs; do not edit.
2
2
 
3
3
  // packages/daemon/src/client.ts
4
4
  import { spawn } from "node:child_process";
@@ -82,7 +82,7 @@ var ARTIFACT_SCHEMA = {
82
82
  },
83
83
  intent: {
84
84
  type: "string",
85
- description: "quickstart: what is being made (design, slides, whiteboard, document, data, other), or a few words about it."
85
+ description: "quickstart: what is being made (design, design-system, slides, whiteboard, document, data, other), or a few words about it."
86
86
  },
87
87
  scope: {
88
88
  type: "string",
@@ -355,7 +355,34 @@ function readJson(file, fallback) {
355
355
  }
356
356
  }
357
357
 
358
+ // packages/daemon/package.json
359
+ var package_default = {
360
+ name: "@open-artifact/daemon",
361
+ version: "0.2.2",
362
+ private: true,
363
+ type: "module",
364
+ description: "The Open Artifact daemon (`open-artifact`): type registry, artifact library, type servers, agent tools, wake routing, the Harness API, MCP and the Shell.",
365
+ bin: {
366
+ "open-artifact": "./src/bin/open-artifact.ts"
367
+ },
368
+ exports: {
369
+ ".": "./src/index.ts",
370
+ "./client": "./src/client.ts"
371
+ },
372
+ dependencies: {
373
+ "@open-artifact/protocol": "0.2.2"
374
+ },
375
+ license: "Apache-2.0"
376
+ };
377
+
358
378
  // packages/daemon/src/client.ts
379
+ var VERSION = package_default.version ?? "0.0.0";
380
+ function isOlderVersion(a, b) {
381
+ const parts = (v) => v.split("-")[0].split(".").map((n) => Number.parseInt(n, 10) || 0);
382
+ const [x, y] = [parts(a), parts(b)];
383
+ for (let i = 0; i < 3; i++) if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) < (y[i] ?? 0);
384
+ return false;
385
+ }
359
386
  function defaultDaemonBin() {
360
387
  return process.env.OPEN_ARTIFACT_DAEMON_BIN || resolve2(dirname2(fileURLToPath(import.meta.url)), "bin", "open-artifact.ts");
361
388
  }
@@ -378,10 +405,20 @@ async function readDaemon() {
378
405
  return null;
379
406
  }
380
407
  }
408
+ async function replaceDaemon(state, timeoutMs) {
409
+ try {
410
+ process.kill(state.pid, "SIGTERM");
411
+ } catch {
412
+ return;
413
+ }
414
+ const deadline = Date.now() + timeoutMs;
415
+ while (alive(state.pid) && Date.now() < deadline) await new Promise((done) => setTimeout(done, 100));
416
+ }
381
417
  async function ensureDaemon(options = {}) {
382
- const running = await readDaemon();
383
- if (running) return running;
384
418
  const { timeoutMs = 15e3, env = process.env, bin = defaultDaemonBin() } = options;
419
+ const running = await readDaemon();
420
+ if (running && !isOlderVersion(running.version ?? "0.0.0", VERSION)) return running;
421
+ if (running) await replaceDaemon(running, 5e3);
385
422
  mkdirSync2(files.logs(), { recursive: true });
386
423
  const logFile = join2(files.logs(), "daemon.out");
387
424
  const fd = openSync(logFile, "a");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-open-artifact",
3
- "version": "0.8.1",
3
+ "version": "0.8.2",
4
4
  "description": "Open Artifact in DeepSeek Harness: the Artifact, ArtifactData and ArtifactComments tools, comments on artifact pages waking the session that owns them, the Open Artifact page in the sidebar listing the open-artifact library, artifacts the agent opens shown in the session's Browser, and /open-artifact <type> to make a new one.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -11,7 +11,7 @@ The person started this message with `/open-artifact`. The first word after it i
11
11
  1. Take the type id from the first word. If there is none, or it is not one of the installed types listed below, ask
12
12
  which type they want (list the installed ones) and stop until they answer. Words like "deck" or "presentation"
13
13
  mean `slides`; "canvas", "UI" or "mockup" mean `design`; "board" means `whiteboard`; "dashboard", "report",
14
- "metrics" or "chart" mean `data`.
14
+ "metrics" or "chart" mean `data`; "brand", "tokens" or "design system" mean `design-system`.
15
15
  2. If the request needs details only the person has (the topic, the content, the brand) and the message gives none,
16
16
  ask in one short question. Otherwise go ahead.
17
17
  3. Create it: `Artifact {action: "publish", type_url: "open-artifact://type/<type id>", title: "<a short title>", open: "after_first_write"}`.
@@ -82,7 +82,7 @@ var ARTIFACT_SCHEMA = {
82
82
  },
83
83
  intent: {
84
84
  type: "string",
85
- description: "quickstart: what is being made (design, slides, whiteboard, document, data, other), or a few words about it."
85
+ description: "quickstart: what is being made (design, design-system, slides, whiteboard, document, data, other), or a few words about it."
86
86
  },
87
87
  scope: {
88
88
  type: "string",
@@ -32,7 +32,7 @@ Error generating stack: `+E.message+`
32
32
  `:"";switch(i(c)?!e&&l>0&&!i(A.at(l-1))&&(r=[]):a(u+"r"),c.t){case"blank":r.push(`
33
33
  `);break;case"p":r.push(...QC(c.c,u),C);break;case"h":r.push(d.jsx("strong",{className:"font-semibold",children:QC(c.c,u)},u),C);break;case"code":{const B=c.info===""?null:d.jsxs("span",{className:"block text-caption text-muted",children:[c.info,`
34
34
  `]});r.push(e?d.jsxs(N.Fragment,{children:[B&&d.jsxs("span",{className:"text-muted",children:[c.info," "]}),d.jsx("code",{dir:"ltr",className:Pj,children:c.text})]},u):d.jsxs("pre",{dir:"ltr",className:_uA,children:[B,d.jsx("code",{className:"[&&]:[word-break:normal]",children:c.text})]},u),e?C:"");break}case"quote":r.push(e?d.jsx("span",{className:"italic",children:PI(c.c,e,u,n)},u):d.jsx("blockquote",{className:juA,children:d.jsx("span",{className:bm,children:PI(c.c,e,u,n)})},u),e?C:"");break;case"list":{if(e){c.items.forEach((Q,f)=>{r.push(" ".repeat(n)+(c.ordered?Q.n+". ":"• "),...PI(Q.c,e,u+"."+f,n+1)),Q.c.at(-1)?.t!=="blank"&&r.push(f<c.items.length-1?`
35
- `:C)});break}const B=c.items.map((Q,f)=>d.jsx("li",{value:c.ordered?Q.n:void 0,children:d.jsx("span",{className:bm,children:PI(Q.c,e,u+"."+f,n+1)})},f));r.push(c.ordered?d.jsx("ol",{className:quA,children:B},u):d.jsx("ul",{className:PuA,children:B},u));break}}}),a(t+".end"),o}function QC(A,e){return A.map((t,n)=>{if(typeof t=="string")return t;const o=e+":"+n;switch(t.t){case"raw":return d.jsx(N.Fragment,{children:t.raw},o);case"code":return d.jsx("code",{dir:"ltr",className:Pj,children:t.text},o);case"em":return d.jsx("em",{children:QC(t.c,o)},o);case"strong":return d.jsx("strong",{className:"font-semibold",children:QC(t.c,o)},o);case"del":return d.jsx("del",{children:QC(t.c,o)},o)}})}function BU(A,e=new Date){const t=new Date(A);if(Number.isNaN(t.getTime()))return"";if(e.getTime()-t.getTime()<6e4)return"now";const n=t.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"}),o=a=>new Date(a.getFullYear(),a.getMonth(),a.getDate()).getTime(),i=Math.round((o(e)-o(t))/864e5);return i===0?n:i===1?`Yesterday, ${n}`:`${t.toLocaleDateString("en-US",{month:"short",day:"numeric",...t.getFullYear()!==e.getFullYear()?{year:"numeric"}:{}})}, ${n}`}function uIA(A,e=new Date){const t=new Date(A);if(Number.isNaN(t.getTime()))return"";const n=Math.floor((e.getTime()-t.getTime())/6e4);if(n<1)return"now";if(n<60)return`${n}m`;const o=Math.floor(n/60);if(o<24)return`${o}h`;const i=Math.floor(o/24);return i<7?`${i}d`:t.toLocaleDateString("en-US",{month:"short",day:"numeric",...t.getFullYear()!==e.getFullYear()?{year:"numeric"}:{}})}const EU=A=>{let e;const t=new Set,n=(l,u)=>{const C=typeof l=="function"?l(e):l;if(!Object.is(C,e)){const B=e;e=u??(typeof C!="object"||C===null)?C:Object.assign({},e,C),t.forEach(Q=>Q(e,B))}},o=()=>e,a={setState:n,getState:o,getInitialState:()=>c,subscribe:l=>(t.add(l),()=>t.delete(l))},c=e=A(n,o,a);return a},IIA=(A=>A?EU(A):EU),CIA=A=>A;function BIA(A,e=CIA){const t=UI.useSyncExternalStore(A.subscribe,UI.useCallback(()=>e(A.getState()),[A,e]),UI.useCallback(()=>e(A.getInitialState()),[A,e]));return UI.useDebugValue(t),t}const QU=A=>{const e=IIA(A),t=n=>BIA(e,n);return Object.assign(t,e),t},ln=(A=>A?QU(A):QU),EIA=4e3;function QIA(A){return A.wakesIdle===!1?`${A.name} gets this on its next turn: send it a message to start one`:"Waiting for the agent"}function fIA(A,e){return e===!1?{title:`Sent to ${A}`,description:`${A} gets it on its next turn. If it is idle, send it a message there to start one.`}:{title:`Sent to ${A}`}}function Zj(A){return A.reduce((e,t)=>t.status==="open"?e+t.messages.length:e,0)}function dIA(A){return A==="detached"?"What this was on is gone; shown on what held it.":A==="orphaned"?"What this was on has been deleted.":null}function hIA(A){const e=A.maxThreads??500,t=A.noun??"document",n=h=>A.notify?.(h);let o=null,i,r=0;const a=ln()(h=>({available:!1,threads:[],on:!1,listOpen:!1,active:null,draft:null,showResolved:!1,sendNew:!1,draftText:"",replies:{},setOn(D){h({on:D,draft:null}),A.onModeChange?.(D)},setListOpen(D){h({listOpen:D})},setActive(D){h({active:D,draft:null})},setDraft(D){h(D===null?{draft:D,active:null,draftText:"",sendNew:!1}:{draft:D,active:null})},setShowResolved(D){h({showResolved:D})},setSendNew(D){h({sendNew:D})},setDraftText(D){h({draftText:D})},setReply(D,m){h(y=>({replies:{...y.replies,[D]:m}}))}})),c=new Map,l=h=>{let D=c.get(h.anchor);return D===void 0&&(D=A.parse(h.anchor),c.size>2e3&&c.clear(),c.set(h.anchor,D)),D},u=h=>{n({title:"The comment could not be saved",description:h instanceof Error?h.message:String(h)})},C=h=>{a.setState(D=>({threads:D.threads.map(m=>m.id===h.id?h:m)})),A.heard?.([h])},B=h=>A.checkText?A.checkText(h):h.trim().slice(0,EIA)||void 0,Q=()=>!!o&&A.canComment(),f=()=>!!o&&A.canSendToAgent(),p={store:a,adapter:A,async start(h,D){if(!h)return;o=h;const m=r;a.setState({available:!0});try{const R=await h.list();if(m!==r)return;a.setState({threads:R}),A.heard?.(R)}catch{}if(m!==r)return;i=h.onChange(R=>{const M=a.getState().active;a.setState({threads:R,active:M&&R.some(k=>k.id===M)?M:null}),A.heard?.(R)});const y=D?a.getState().threads.find(R=>R.id===D):void 0;y&&p.reveal(y)},stop(){r+=1,i?.(),i=void 0},capability:()=>o,canComment:Q,canSendToAgent:f,canRemove:()=>!!o&&(A.canRemove?A.canRemove():A.canComment()),anchorOf:l,labelOf:h=>A.label(h),stateOf:h=>A.state?.(h)??"ok",stateNote:h=>A.stateNote?A.stateNote(h??"ok"):dIA(h),async create(h,D,m){if(!o)return!1;const y=B(D);if(!y)return!1;if(a.getState().threads.length>=e)return n({title:`This ${t} already has ${e} comments`}),!1;try{const R=A.detail?.(h),M=await o.create({anchor:A.serialize(h),label:A.label(h),...R!==void 0?{detail:R}:{},location:A.location?.(h)??{},text:y});return a.setState(k=>({threads:k.threads.some(F=>F.id===M.id)?k.threads:[...k.threads,M],draft:null,draftText:"",sendNew:!1,active:M.id})),A.heard?.([M]),m?.send&&f()&&await p.sendToAgent(M.id),!0}catch(R){return u(R),!1}},async reply(h,D,m){if(!o)return!1;const y=B(D);if(!y)return!1;try{let R=await o.reply(h,y);return R.status==="resolved"&&(R=await o.setResolved(h,!1)),C(R),a.setState(M=>{const{[h]:k,...F}=M.replies;return{replies:F}}),m?.send&&f()&&await p.sendToAgent(h),!0}catch(R){return u(R),!1}},async resolve(h,D){if(o)try{C(await o.setResolved(h,D));const m=a.getState();D&&m.active===h&&!m.showResolved&&a.setState({active:null})}catch(m){u(m)}},async remove(h,D){if(!(!o||A.canRemove&&!A.canRemove()))try{await o.remove(h,D),D||a.setState(m=>({threads:m.threads.filter(y=>y.id!==h),active:m.active===h?null:m.active}))}catch(m){u(m)}},async move(h,D){if(o)try{C(await o.move(h,A.serialize(D),A.location?.(D)))}catch(m){u(m)}},async sendToAgent(h){if(!o||!f())return!1;const D=A.sendToAgent?a.getState().threads.find(m=>m.id===h):void 0;if(A.sendToAgent)return D?A.sendToAgent(D,l(D)):!1;try{return C(await o.sendToAgent(h)),n(fIA(A.agentName?.()||"the agent",A.agentWakesIdle?.())),!0}catch(m){return u(m),!1}},async sendAllToAgent(){const h=a.getState().threads.filter(D=>p.canSendThread(D));for(const D of h)await p.sendToAgent(D.id)},canSendThread(h){if(h.status!=="open")return!1;const D=h.messages.at(-1);return!D||D.author.kind!=="person"?!1:!h.agent||h.agent.status==="replied"},reveal(h){A.reveal?.(l(h)),a.getState().setActive(h.id)},show(h){const D=a.getState();D.on||D.setOn(!0),h.status==="resolved"&&!a.getState().showResolved&&a.getState().setShowResolved(!0),p.reveal(h)},viewerName:()=>A.viewerName?.()||"You"};return p}const $j=300,fC=12,wIA=$j+fC*2;function pIA({comments:A,agent:e,top:t=fC,hint:n}){return A.store(i=>i.listOpen&&i.available)?d.jsx(tE,{mark:"data-comments-panel-layer",children:d.jsx(DIA,{comments:A,agent:e,top:t,hint:n})}):null}const fU=A=>A.messages[0]?.at??"";function DIA({comments:A,agent:e,top:t,hint:n}){const{dark:o}=eE(),i=A.store(Q=>Q.threads),r=A.store(Q=>Q.showResolved),a=A.store(Q=>Q.on),c=A.store(Q=>Q.active),l=()=>A.store.getState().setListOpen(!1),u=i.filter(Q=>Q.messages.length>0),C=u.filter(Q=>r||Q.status==="open").sort((Q,f)=>fU(f).localeCompare(fU(Q))),B=u.filter(Q=>Q.status==="resolved").length;return d.jsxs("section",{"aria-label":"All comments","data-comments-panel":"",className:Mt(bk(),"fixed flex flex-col text-body text-primary"),style:{top:t,right:fC,width:$j,maxWidth:`calc(100vw - ${fC*2}px)`,maxHeight:`calc(100dvh - ${t+fC}px)`,zIndex:40,pointerEvents:"auto",...Rk(o)},onKeyDown:Q=>{const f=Q.target instanceof Element&&Q.target.closest("[data-cds=Menu]");Q.key==="Escape"&&!Q.defaultPrevented&&!f&&(Q.preventDefault(),l())},children:[d.jsxs("div",{className:"flex shrink-0 items-center gap-xs",style:{padding:"10px 10px 6px 16px"},children:[d.jsx("span",{className:"min-w-0 flex-1 truncate font-medium",children:"All comments"}),d.jsx(mIA,{showResolved:r,onShowResolved:Q=>A.store.getState().setShowResolved(Q)}),d.jsx(Hi,{variant:"ghost",iconOnly:!0,"aria-label":"Close",icon:d.jsx(pi,{name:"X",size:"sm"}),onClick:l})]}),d.jsx(SIA,{comments:A,agent:e,threads:u}),d.jsxs("div",{className:"flex min-h-0 flex-col gap-xs overflow-y-auto [--cds-comment-card-bg:var(--cds-surface-2)]",style:{padding:"0 12px 12px"},children:[u.length===0?d.jsxs("div",{"data-comments-empty":"",className:"flex flex-1 flex-col items-center justify-center gap-xs px-lg text-center",style:{paddingBlock:"var(--cds-pad-xl)"},children:[d.jsx("span",{className:"text-body font-medium text-secondary",children:"No comments yet"}),d.jsx("span",{className:"text-caption text-muted",children:A.canComment()?n??"Press the comment button, then click anywhere on the artifact to add one.":"Only people with comment access can add one."})]}):C.length===0?d.jsxs("span",{"data-comments-filtered-empty":"",className:"px-lg text-center text-caption text-muted",style:{paddingBlock:"var(--cds-pad-xl)"},children:["No open comments.",B>0?d.jsxs(d.Fragment,{children:[" ",d.jsx("button",{type:"button",className:"cds-text-link cds-text-link-underline inline text-inherit",onClick:()=>A.store.getState().setShowResolved(!0),children:`Show ${B} resolved`})]}):null]}):null,C.map(Q=>d.jsx(NIA,{comments:A,agent:e,thread:Q,current:a&&c===Q.id},Q.id))]})]})}function yIA(){return d.jsx("svg",{"data-cds":"Icon","aria-hidden":!0,width:"1em",height:"1em",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:1.2,strokeLinecap:"round",style:{fontSize:"calc(1rem * var(--cds-rem-scale,1))"},children:d.jsx("path",{d:"M2.5 4.5h11M4.5 8h7M6.5 11.5h3"})})}function mIA({showResolved:A,onShowResolved:e}){const[t,n]=Lk();return d.jsxs(JB,{open:t,onOpenChange:n,modal:!1,children:[d.jsx(Ug,{content:"Filter",disabled:t,children:d.jsx(HB,{render:d.jsx(Hi,{variant:"ghost",iconOnly:!0,tooltip:!1,"aria-label":"Filter",icon:d.jsx(yIA,{})})})}),d.jsx(Mk,{align:"end",children:d.jsxs(d8,{checked:A,onCheckedChange:e,closeOnClick:!1,className:Mt(kj,"group/cb text-primary data-[highlighted]:bg-fill-ghost-hover"),children:[d.jsx(Gj,{}),d.jsx("span",{className:"min-w-0 flex-1 truncate",children:"Show resolved"})]})})]})}function SIA({comments:A,agent:e,threads:t}){const[n,o]=N.useState(!1),[i,r]=N.useState(!1),a=t.filter(u=>u.status==="open"&&u.messages.some(C=>C.author.kind==="person"));if(!A.canSendToAgent()||!e.available||a.length===0)return null;const l=!a.some(u=>A.canSendThread(u))?i?`These comments were just sent to ${e.name}.`:`${e.name} has every comment.`:void 0;return d.jsx("div",{className:"flex shrink-0 flex-col items-end gap-sm",style:{padding:"0 12px 8px"},children:d.jsx(Ug,{content:l,side:"bottom",children:d.jsx(Hi,{"data-comments-send-all":"","data-size":"sm",variant:"secondary",busy:n,"aria-disabled":l!==void 0||n||void 0,className:"aria-disabled:opacity-disabled",onClick:()=>{l!==void 0||n||(o(!0),A.sendAllToAgent().then(()=>r(!0)).finally(()=>o(!1)))},children:`Send all to ${e.name}`})})})}function NIA({comments:A,agent:e,thread:t,current:n}){const[o,i]=N.useState(!1),[r,a]=N.useState(!1),[c,l]=N.useState(!1),u=N.useId(),C=t.messages[0],B=t.messages.length-1,Q=t.status==="resolved",f=A.canComment(),w=C.author.kind==="agent"?C.author.name||e.name:C.author.name||"Someone",p=[...Q&&f?[{label:"Reopen",icon:"Comment",onSelect:()=>{A.resolve(t.id,!1)}}]:[],...A.canRemove()?[{label:"Delete thread",icon:"Trash",variant:"danger",onSelect:()=>i(!0)}]:[]];return d.jsxs(Yj,{variant:"flat",expanded:!1,active:n,labelledBy:u,onExpand:()=>A.show(t),className:"rounded",children:[d.jsx(nd,{nameId:u,authorName:w,agent:C.author.kind==="agent",timestamp:d.jsxs(d.Fragment,{children:[uIA(C.at),Q&&" · Resolved",t.agent?d.jsx("span",{role:"img","aria-label":`Sent to ${e.name}`,className:"inline-flex",style:{width:18,height:18,marginInlineStart:4,verticalAlign:"middle",color:"var(--cds-fill-brand)"},children:d.jsx(vj,{})}):null]}),confirm:o?d.jsx(Tj,{busy:c,onCancel:()=>i(!1),onDelete:()=>{l(!0),A.remove(t.id).finally(()=>l(!1))}}):void 0,actions:d.jsxs(Fk,{placement:n?"pinned":void 0,children:[f?d.jsx(Kj,{resolved:Q,busy:r,onResolve:()=>{a(!0),A.resolve(t.id,!0).finally(()=>a(!1))}}):null,d.jsx(Uj,{items:p})]}),children:d.jsx("span",{className:"line-clamp-3",children:SN(C.text,{flat:!0})})}),B>0&&!o?d.jsx("button",{type:"button","data-cds-part":"replies-toggle",className:"self-start text-body font-normal text-accent hover:underline",children:B===1?"1 reply":`${B} replies`}):null]})}function dU(A,e){return{x:e.x*A.zoom+A.x,y:e.y*A.zoom+A.y}}function bIA(A,e){const t=A.zoom||1;return{x:(e.x-A.x)/t,y:(e.y-A.y)/t}}function RIA(A,e){return{left:e.x*A.zoom+A.x,top:e.y*A.zoom+A.y,width:e.w*A.zoom,height:e.h*A.zoom}}const MIA=5,hU="#ae7303",kIA="<svg xmlns='http://www.w3.org/2000/svg' width='28' height='28' viewBox='0 0 28 28'><path d='M 2 26 L 2 14 A 12 12 0 1 1 14 26 Z' fill='#000' stroke='#fff' stroke-width='2'/></svg>";`${kIA.replace(/[ '<>#]/g,A=>"%"+A.charCodeAt(0).toString(16).toUpperCase())}`;const fr=36,cf=4,xn=8,xIA=330,wU=6,kN=48;function lf(A,e){const t=e.height-(A.y+cf),n=A.y-cf,o=t<320&&n>t&&(n>=240||t<240&&n>=48);return{left:Math.min(Math.max(A.x,0),Math.max(0,e.width-(fr+xn))),top:o?A.y-(fr+cf):A.y+cf,flip:o}}const AP=A=>Math.max(320,Math.round(A*.6));function vIA(A,e){const t=xn,n=e.height-xn,o=(r,a,c)=>Math.min(Math.max(r,a),c),i=A.flip?o(A.top+fr+2,Math.min(n,t+kN),n)-t:n-o(A.top-2,t,Math.max(t,n-kN));return Math.min(AP(e.height),Math.max(0,i))}function xN({pin:A,corner:e,viewport:t,onEscape:n,children:o}){const i=N.useRef(null),[r,a]=N.useState(0);N.useLayoutEffect(()=>{const Q=i.current;if(!Q)return;a(Q.offsetHeight);const f=new ResizeObserver(()=>a(Q.offsetHeight));return f.observe(Q),()=>f.disconnect()},[]);const c=Math.max(0,Math.min(xIA,t.width-2*xn));let l,u,C;if(e||!A){const Q=e??{x:xn,y:xn};l=Math.max(xn,Math.min(Q.x,t.width-xn-c)),u=Math.max(xn,Math.min(Q.y,t.height-xn-r)),typeof o=="function"&&(C=Math.min(AP(t.height),Math.max(kN,t.height-xn-Math.max(xn,Q.y))))}else{if(l=A.left+fr+wU,l+c>t.width-xn){const Q=A.left-wU-c;l=Q>=xn?Q:Math.max(xn,t.width-xn-c)}u=A.flip?A.top+fr+2-r:A.top-2,u=Math.max(xn,Math.min(u,t.height-xn-r)),typeof o=="function"&&(C=vIA(A,t))}const B={position:"absolute",left:l,top:u,width:c,pointerEvents:"auto",...C===void 0?{}:{maxHeight:C,display:"flex",flexDirection:"column"},...r?{}:{opacity:0,pointerEvents:"none"}};return d.jsx("div",{ref:i,style:B,"data-comment-card":"",onKeyDown:Q=>{Q.key!=="Escape"||Q.defaultPrevented||(Q.preventDefault(),n())},children:typeof o=="function"?o(C):o})}const GIA="cds-reset absolute flex items-center justify-center rounded-full rounded-tl-none border-0 p-0 cursor-[var(--cds-cursor-interactive)] outline-none focus-visible:outline-hidden focus-visible:shadow-focus";function eP({pin:A,avatar:e,draft:t=!1,label:n,title:o,expanded:i,faded:r=!1,...a}){const{pinId:c,...l}=a,u={left:A.left,top:A.top,width:fr,height:fr,pointerEvents:t?"none":"auto",touchAction:"none",...A.flip?{borderRadius:"9999px 9999px 9999px 0"}:{},...r?{opacity:.7}:{}};return d.jsx("button",{type:"button","data-comment-pin":c,"aria-label":n,title:o,"aria-expanded":i,tabIndex:t?-1:void 0,className:Mt(GIA,t?"bg-fill-accent":"bg-surface-2 shadow-panel-sm"),style:u,...l,children:d.jsx("span",{className:"flex rounded-full bg-surface-1",children:e})})}function vN(A,e){return A.author.kind==="agent"?A.author.name||e.name:A.author.name||"Someone"}function FIA(A,e){const t=A.messages[0];return t?d.jsx(oh,{name:vN(t,e),variant:t.author.kind==="agent"?"agent":"default",size:"sm"}):d.jsx(oh,{name:"?",size:"sm"})}function LIA({comments:A,camera:e,viewport:t,place:n,highlight:o,anchorAt:i,movable:r,onMove:a,agent:c,revision:l,piles:u=!0,insets:C}){const B=(r??!0)&&!!(i||a),Q=A.store(v=>v.available),f=A.store(v=>v.threads),w=A.store(v=>v.active),p=A.store(v=>v.draft),h=A.store(v=>v.on),D=A.store(v=>v.showResolved),m=A.store(v=>v.listOpen),[y,R]=N.useState(null),M=N.useMemo(()=>{if(!Q)return[];const v=[];for(const T of f){if(T.messages.length===0||T.status!=="open"&&!D&&T.id!==w)continue;const _=A.anchorOf(T),j=n(_);j&&v.push({key:T.id,thread:T,anchor:_,state:j.state,screen:dU(e,j.world)})}if(p!==null){const T=n(p);T&&v.push({key:"draft",thread:null,anchor:p,state:T.state,screen:dU(e,T.world)})}return v},[Q,f,w,p,D,e,n,l,A]);if(!Q||!h&&!w&&p===null&&M.length===0)return null;const k=p!==null?"draft":w,F=M.find(v=>v.key===k),G=F&&o?o(F.anchor):null,U=M.filter(v=>v.thread),L=u?wuA({points:U.map(v=>({id:v.key,x:v.screen.x,y:v.screen.y})),openId:w,box:{left:0,top:0,width:t.width,height:t.height},top:0,floor:C?.top??0,foot:C?.bottom?C.bottom+8:0,reserveRight:m?wIA:0}):null,K=U.filter(v=>!L?.piled.has(v.key)).map(v=>({...v,box:lf(v.screen,t)})),H=RuA(K.map(v=>({id:v.key,x:v.box.left,y:v.box.top,w:fr})),t.width,fr),x=v=>A.store.getState().setActive(v),Y=F?.thread?F:void 0;return d.jsxs(d.Fragment,{children:[G?d.jsx("div",{"data-comment-target":"",className:Mt("pointer-events-none absolute",!G.area&&"rounded"),style:{...RIA(e,G),border:G.area?`1px dashed ${hU}`:`1.5px solid ${hU}`}}):null,d.jsxs(tE,{className:"pointer-events-none absolute inset-0 z-[3]",mark:"data-comment-layer",onEscape:()=>{const v=A.store.getState();return v.draft!==null||v.active?(v.setDraft(null),v.setActive(null),!0):!1},children:[K.map(v=>{const T=v.thread,_=y?.id===T.id?y:null,j={...v.box,left:v.box.left+(H.get(v.key)??0)+(_?.x??0),top:v.box.top+(_?.y??0)};return d.jsx(YIA,{comments:A,thread:T,box:j,avatar:FIA(T,c),expanded:w===T.id,detached:v.state==="detached",onDrag:P=>R(P?{id:T.id,...P}:null),movable:B,onDrop:P=>{const O={x:v.screen.x+P.x,y:v.screen.y+P.y};a?a(T.id,O):i&&A.move(T.id,i(bIA(e,O)))}},v.key)}),L?d.jsx("div",{style:{display:"contents",pointerEvents:"auto"},children:d.jsx(buA,{piles:L,onOpen:v=>{const T=f.find(_=>_.id===v);T&&A.show(T)}})}):null,Y?d.jsx(xN,{pin:lf(Y.screen,t),viewport:t,onEscape:()=>x(null),children:v=>d.jsx(tP,{comments:A,agent:c,thread:Y.thread,state:Y.state,maxHeight:v})},Y.key):null,F&&!F.thread&&p!==null?d.jsxs(d.Fragment,{children:[d.jsx(eP,{pin:lf(F.screen,t),draft:!0,label:"New comment",avatar:d.jsx(oh,{name:A.viewerName(),size:"sm"})}),d.jsx(xN,{pin:lf(F.screen,t),viewport:t,onEscape:()=>A.store.getState().setDraft(null),children:d.jsx(TIA,{comments:A,agent:c,anchor:p})})]}):null]})]})}function YIA({comments:A,thread:e,box:t,avatar:n,expanded:o,detached:i,movable:r,onDrag:a,onDrop:c}){const l=N.useRef(null),u=N.useRef(!1),C=e.status==="resolved";return d.jsx(eP,{pinId:e.id,pin:t,avatar:n,expanded:o,faded:i,label:`Comment: ${e.label}${C?" (resolved)":""}`,title:i?"What this comment was on is gone":e.label,onPointerDown:B=>{if(B.button===0){l.current={x:B.clientX,y:B.clientY,moved:!1},u.current=!1;try{B.currentTarget.setPointerCapture(B.pointerId)}catch{}}},onPointerMove:B=>{const Q=l.current;if(!Q||!r||!A.canComment())return;const f=B.clientX-Q.x,w=B.clientY-Q.y;!Q.moved&&Math.hypot(f,w)<MIA||(Q.moved=!0,a({x:f,y:w}))},onPointerUp:B=>{const Q=l.current;l.current=null,Q?.moved&&(u.current=!0,a(null),c({x:B.clientX-Q.x,y:B.clientY-Q.y}))},onClick:()=>{if(u.current){u.current=!1;return}const B=A.store.getState();B.setActive(B.active===e.id?null:e.id)}})}function UIA(A,e){const t=N.useRef(null);N.useLayoutEffect(()=>{const o=t.current,i=A.current;if(!o||!i)return;i.scrollTop=i.scrollHeight;const r=e.messages.at(-1);if(r&&r.id!==o.after&&r.author.kind==="agent"){const a=[...i.querySelectorAll('[data-cds-part="comment"]')].at(-1),c=a?i.getBoundingClientRect().top-a.getBoundingClientRect().top:0;if(c>0){i.scrollTop-=c,t.current=null;return}}o.at=i.scrollTop});const n=()=>{t.current=null};return{start:()=>{t.current={after:e.messages.at(-1)?.id,at:0}},regionProps:{onPointerDownCapture:n,onWheelCapture:o=>{o.deltaY<0&&n()},onScroll:o=>{const i=o.currentTarget,r=t.current;r&&Math.abs(i.scrollTop-r.at)>2&&i.scrollHeight-i.scrollTop-i.clientHeight>2&&n()}}}}function tP(A){return d.jsx(_j,{children:d.jsx(KIA,{...A})})}function KIA({comments:A,agent:e,thread:t,state:n,maxHeight:o,onClose:i}){const[r,a]=N.useState(!1),[c,l]=N.useState(!1),[u,C]=N.useState(!1),[B,Q]=N.useState(!1),f=N.useId(),w=N.useRef(null),p=UIA(w,t),h=A.store(H=>H.replies[t.id])??{text:"",send:!1},D=A.canSendToAgent()&&e.available,m=A.canComment(),[y,...R]=t.messages;if(!y)return null;const M=i??(()=>A.store.getState().setActive(null)),k=A.stateNote(n??A.stateOf(A.anchorOf(t))),F=`Send to ${e.name}`,G=A.canRemove()?[{label:"Delete thread",icon:"Trash",variant:"danger",onSelect:()=>a(!0)}]:[],U=t.status==="open"?t.agent?.status:void 0,L=U==="pending"?"queued":U==="delivered"?"working":void 0,K=H=>A.store.getState().setReply(t.id,H);return d.jsxs(Yj,{expanded:!0,active:!0,onClose:M,labelledBy:f,maxHeight:o,scrollRef:w,scrollProps:p.regionProps,className:"min-h-0 flex-1",reply:m&&d.jsx(suA,{children:d.jsx(Jj,{label:"Reply",placeholder:t.status==="resolved"?"Reply to reopen…":D&&h.send?"What do you want to edit?":void 0,value:h.text,onChange:H=>K({...h,text:H}),sendBox:D?{label:F,checked:h.send,onCheckedChange:H=>K({...h,send:H})}:void 0,busy:B,onSubmit:(H,{send:x})=>{p.start(),Q(!0),A.reply(t.id,H,{send:D&&x}).finally(()=>Q(!1))},onCancel:M})}),children:[d.jsx(nd,{nameId:f,authorName:vN(y,e),agent:y.author.kind==="agent",timestamp:BU(y.at),footnote:k??void 0,confirm:r?d.jsx(Tj,{busy:u,onCancel:()=>a(!1),onDelete:()=>{C(!0),A.remove(t.id).finally(()=>C(!1))}}):void 0,actions:m||G.length>0?d.jsxs(Fk,{children:[m?d.jsx(Kj,{resolved:t.status==="resolved",busy:c,onResolve:()=>{l(!0),A.resolve(t.id,!0).finally(()=>l(!1))}}):null,d.jsx(Uj,{items:G})]}):void 0,children:SN(y.text)}),R.length>0||L?d.jsxs(iuA,{children:[R.map(H=>d.jsx(nd,{authorName:vN(H,e),agent:H.author.kind==="agent",timestamp:BU(H.at),children:SN(H.text)},H.id)),L?d.jsx(nd,{authorName:e.name,agent:!0,working:L,footnote:L==="queued"?QIA(e):"Working…"}):null]}):null]})}function TIA(A){return d.jsx(_j,{children:d.jsx(JIA,{...A})})}function JIA({comments:A,agent:e,anchor:t,onCancel:n}){const o=A.store(C=>C.draftText),i=A.store(C=>C.sendNew),[r,a]=N.useState(!1),c=N.useRef(null),l=A.canSendToAgent()&&e.available;N.useEffect(()=>{c.current?.focus({preventScroll:!0})},[t]);const u=()=>n?n():A.store.getState().setDraft(null);return d.jsx(Jj,{textareaRef:c,context:A.labelOf(t),value:o,onChange:C=>A.store.getState().setDraftText(C),sendBox:l?{label:`Send to ${e.name}`,checked:i,onCheckedChange:C=>A.store.getState().setSendNew(C)}:void 0,busy:r,onSubmit:(C,B)=>{r||(a(!0),A.create(t,C,{send:l&&B.send}).finally(()=>a(!1)))},onCancel:u})}function HIA({comments:A,shortcut:e="C",side:t="bottom"}){return A.store(o=>o.available)?d.jsx(tE,{inline:!0,mark:"data-comments-button",children:d.jsx(OIA,{comments:A,shortcut:e,side:t})}):null}function OIA({comments:A,shortcut:e,side:t}){const[n,o]=Lk(),i=A.store(B=>Zj(B.threads)),r=A.store(B=>B.on),a=A.store(B=>B.listOpen),c=!r&&i>0,l=r?"Done commenting":i>0?`${i} open ${i===1?"comment":"comments"}`:"Comments",u=B=>{o(!1),A.store.getState().setListOpen(B)},C=a?{label:"Hide comments",onSelect:()=>u(!1)}:{label:"Show all comments",trailing:i,onSelect:()=>u(!0)};return d.jsxs("span",{className:"flex shrink-0 items-center",children:[A.canComment()?d.jsx(Ug,{content:l,shortcut:e,side:t,children:d.jsx(Hi,{variant:"ghost",iconOnly:!0,tooltip:!1,"aria-label":"Comments","aria-pressed":r,icon:d.jsxs("span",{className:"relative inline-flex",children:[d.jsx(pi,{name:r?"CommentFilled":"Comment",size:"sm"}),c?d.jsx("span",{"aria-hidden":!0,className:"absolute rounded-full bg-fill-accent",style:{top:-1,right:-2,width:6,height:6,boxShadow:"0 0 0 1.5px var(--cds-page-bg)"}}):null]}),onClick:()=>A.store.getState().setOn(!r)})}):null,d.jsxs(JB,{open:n,onOpenChange:o,modal:!1,children:[d.jsx(Ug,{content:"Comment options",disabled:n,side:t,children:d.jsx(HB,{render:d.jsx(Hi,{variant:"ghost","aria-label":"Comment options",style:{paddingInline:2},children:d.jsx(pi,{name:"CaretDown",size:"xs"})})})}),d.jsx(Mk,{align:"end",children:d.jsx(xj,{items:[C]})})]})]})}const pU=200,GN=ln()(()=>({message:"",serial:0}));function _IA(A){const e=A.replace(/\s+/g," ").trim();return e.length>pU?`${e.slice(0,pU-1)}…`:e}function wt(A){const e=_IA(A);e&&GN.setState(t=>({message:e,serial:t.serial+1}))}function jIA(){const A=GN(t=>t.message),e=GN(t=>t.serial);return d.jsx("div",{role:"status","aria-live":"polite","aria-atomic":"true",className:"sr-only",style:{position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap"},children:d.jsx("span",{children:A},e)})}const nE=N.forwardRef(function({className:e,...t},n){return d.jsx("div",{ref:n,className:ye("pointer-events-auto flex items-center gap-1 rounded-[12px] bg-chrome text-chrome-fg shadow-chrome",e),...t})});function Uk({className:A,vertical:e=!0}){return d.jsx("div",{"aria-hidden":"true",className:ye(e?"mx-0.5 h-[18px] w-px":"my-1 h-px w-full","shrink-0 bg-chrome-line",A)})}const PIA=A=>A?{[A]:""}:{};function lr({label:A,shortcut:e,side:t="bottom",children:n,disabled:o}){return d.jsxs(NM,{disabled:o,children:[d.jsx(bM,{render:n}),d.jsx(RM,{children:d.jsx(vM,{side:t,sideOffset:8,className:"z-[1000]",children:d.jsxs(GM,{className:"flex max-w-80 items-center gap-1.5 rounded-[6px] bg-tip px-2 py-[5px] text-[13px] leading-[18px] text-tip-fg shadow-[0_1px_2px_rgb(11_11_11/0.06),0_2px_8px_rgb(11_11_11/0.08)] transition-opacity data-[ending-style]:opacity-0 data-[starting-style]:opacity-0",children:[d.jsx("span",{children:A}),e?d.jsx("kbd",{className:"rounded-[4px] bg-white/15 px-1 font-sans text-[12px] leading-4 text-tip-fg/80",children:e}):null]})})})]})}const qIA={md:"h-7",lg:"h-8",xl:"h-9"},WIA={md:"w-7",lg:"w-8",xl:"w-9"},Ki=N.forwardRef(function({pressed:e,square:t,size:n="md",className:o,type:i="button",...r},a){return d.jsx("button",{ref:a,type:i,"aria-pressed":e,className:ye("inline-flex shrink-0 select-none items-center justify-center gap-1 whitespace-nowrap rounded-[8px] text-[14px] font-control leading-5 text-chrome-fg outline-none transition-colors duration-100 ease-out","hover:bg-chrome-hover focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-chrome-focus","disabled:pointer-events-none disabled:opacity-40",qIA[n],t?WIA[n]:"px-[9px]",e&&"bg-chrome-pressed text-chrome-pressed-fg hover:bg-chrome-pressed",o),...r})}),dC=N.forwardRef(function({tip:e,shortcut:t,side:n,disabled:o,...i},r){const a=d.jsx(Ki,{ref:r,disabled:o,...i});return d.jsx(lr,{label:e,shortcut:t,side:n,children:o?d.jsx("span",{className:"inline-flex",children:a}):a})}),id=N.forwardRef(function({label:e,tip:t,icon:n,shortcut:o,tipSide:i="top",size:r="xl",className:a,...c},l){return d.jsx(lr,{label:t??e,shortcut:o,side:i,children:d.jsx(Ki,{ref:l,square:!0,size:r,"aria-label":e,className:ye("[&_svg]:size-[18px] [&_svg]:shrink-0",a),...c,children:n})})}),VIA="min-w-[128px] max-w-[320px] rounded-[14px] bg-chrome p-1.5 text-[14px] leading-5 font-control text-chrome-fg shadow-chrome-popup outline-none origin-[var(--transform-origin)] transition-[opacity,transform] duration-100 data-[starting-style]:scale-95 data-[starting-style]:opacity-0 data-[ending-style]:opacity-0",XIA="flex h-7 cursor-default select-none items-center gap-2 rounded-[8px] px-2.5 outline-none data-[highlighted]:bg-chrome-hover data-[popup-open]:bg-chrome-hover data-[disabled]:opacity-40";function zIA({trigger:A,children:e,side:t="bottom",align:n="start",className:o,tip:i,open:r,onOpenChange:a,sideOffset:c=6,mark:l,popupBase:u=VIA}){const C=d.jsx(HB,{render:A});return d.jsxs(JB,{open:r,onOpenChange:a?B=>a(B):void 0,children:[i?d.jsx(lr,{label:i.label,shortcut:i.shortcut,side:i.side??(t==="top"?"top":"bottom"),children:C}):C,d.jsx(TM,{children:d.jsx(HM,{side:t,align:n,sideOffset:c,className:"z-[1000]",children:d.jsx(KM,{...PIA(l),className:ye(u,o),children:e})})})]})}function ZIA({children:A,onSelect:e,shortcut:t,checked:n,disabled:o,danger:i,icon:r,title:a,description:c,closeOnClick:l}){return d.jsxs(h8,{className:ye(XIA,c!==void 0&&"h-auto min-h-7 items-start py-1.5",i&&"text-danger data-[highlighted]:bg-danger data-[highlighted]:text-white"),disabled:o,onClick:e,closeOnClick:l,title:a,children:[n!==void 0?d.jsx("span",{className:"flex size-4 shrink-0 items-center justify-center",children:n?d.jsx(lu,{className:"size-4 text-chrome-accent",strokeWidth:2.25}):null}):null,r?d.jsx("span",{"data-chrome-icon":"",className:"flex size-4 shrink-0 items-center justify-center text-chrome-muted",children:r}):null,c!==void 0?d.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[d.jsx("span",{className:"truncate",children:A}),d.jsx("span",{className:"truncate text-[12px] leading-4 text-chrome-muted",children:c})]}):d.jsx("span",{className:"min-w-0 flex-1 truncate",children:A}),t?d.jsx("span",{className:"ml-6 max-w-40 shrink-0 truncate text-[13px] text-chrome-muted",children:t}):null]})}function Dg(){return typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/.test(navigator.platform||navigator.userAgent)}const pl=Dg()?"⌘":"Ctrl+",$IA=pl==="⌘"?"⇧":"Shift+";function ACA(A){let e=!1;A.setCanRestore(A.roleMayRestore),A.report({history:!0});const t=()=>{A.history.list().then(o=>{e||A.setCanRestore(o.canRestore&&A.roleMayRestore)},()=>{})};t();const n=[A.history.onChange(t),A.onCommand(o=>{o.cmd==="history"&&A.toggle()})];return()=>{e=!0;for(const o of n)o();A.report({history:void 0})}}async function eCA(A,e,t,n=12){const o=t(Object.keys(await A.files(e))),i=[];let r=0;const a=async()=>{for(;r<o.length;){const c=o[r++],l=await A.read(e,c).catch(()=>null);l!==null&&i.push([c,l])}};return await Promise.all(Array.from({length:Math.min(n,o.length)},a)),i}const tCA="1.3.0";class ZC extends Error{code;paths;retryable;constructor(e,t,n,o){super(t),this.name="ArtifactError",this.code=e,n&&(this.paths=n),o&&(this.retryable=!0)}}function nCA(A){return A==="owner"||A==="editor"}const DI={maxDocumentBytes:262144,maxDepth:32},DU={defaultMs:12e4,maxMs:6e5};function oCA(A,e={}){const t=e.timeoutMs??1e4,n=new Map;return Object.freeze({version:tCA,use:i=>{const r=n.get(i);if(r)return r;const a=new Promise(c=>{const l=setTimeout(()=>c(null),t);Promise.resolve().then(()=>A.get(i)).then(u=>{clearTimeout(l),c(u?Object.freeze(u):null)},()=>{clearTimeout(l),c(null)})});return n.set(i,a),a}})}function iCA(A,e){const t=globalThis.window?.openartifact;if(t)return t;const n=oCA(A,e);return Object.defineProperty(window,"openartifact",{value:n,configurable:!1,enumerable:!0,writable:!1}),n}const it={session:"_api/session",files:"_api/files",file:"_api/file",publish:"_api/publish",assets:"_api/assets",events:"_api/events",agentSend:"_api/agent/send",presence:"_api/presence",peers:"_api/peers",downloads:"_api/downloads",roomEmit:"_api/room/emit",dbGet:"_api/db/get",dbList:"_api/db/list",dbWrite:"_api/db/write",comments:"_api/comments",commentsCreate:"_api/comments/create",commentsReply:"_api/comments/reply",commentsResolve:"_api/comments/resolve",commentsMove:"_api/comments/move",commentsRemove:"_api/comments/remove",commentsSend:"_api/comments/send",history:"_api/history",historyFiles:"_api/history/files",historyFile:"_api/history/file",historyDiff:"_api/history/diff",historyRestore:"_api/history/restore",historyDismiss:"_api/history/dismiss",mcpTools:"_api/mcp/tools",mcpCall:"_api/mcp/call"};function sCA(A,e,t){return e===401||e===403?"removed":e<200||e>=300||!t||t.id===A.id&&t.role===A.role?null:"changed"}async function yU(A){let e={};try{e=await A.json()}catch{}const t=A.status===409?"conflict":A.status===403?"not_writer":A.status===404?"not_found":"unavailable";return new ZC(e.code??t,e.message??`HTTP ${A.status}`,e.paths,e.retryable===!0)}function rCA(){const A=new Uint8Array(8);return crypto.getRandomValues(A),Array.from(A,e=>e.toString(16).padStart(2,"0")).join("")}function nP(A={}){const e=new URL(A.base??"./",location.href),t=rCA(),n=(G,U)=>{const L=new URL(G,e);for(const[K,H]of Object.entries(U??{}))L.searchParams.set(K,H);return L.toString()},o=async(G,U,L)=>{let K;try{K=await fetch(n(G,L),U)}catch(H){throw new ZC("unavailable",H instanceof Error?H.message:String(H))}if(!K.ok)throw await yU(K);return await K.json()},i=(G,U)=>o(G,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(U)}),r=new Map,a=(G,U)=>{for(const L of r.get(G)??[])L(U)},c=(G,U)=>{let L=r.get(G);return L||(L=new Set,r.set(G,L),C?.addEventListener(G,Q)),L.add(U),m(),()=>L.delete(U)};let l=null,u=!1,C=null,B=null;const Q=G=>{a(G.type,JSON.parse(G.data))},f=()=>{const G=new EventSource(n(it.events,{client:t}));C=G;for(const U of r.keys())G.addEventListener(U,Q);G.onerror=()=>{D().then(U=>{U||G.readyState!==EventSource.CLOSED||C!==G||(C=null,B=setTimeout(()=>{B=null,m()},2e3))})}};let w=!1,p=!1;const h=G=>{w||(w=!0,B&&clearTimeout(B),B=null,C?.close(),C=null,l?.close(),l=null,A.onAccessChange?A.onAccessChange(G):location.reload())},D=async()=>{if(w)return!0;if(!y||p)return!1;p=!0;try{const G=(await y.catch(()=>null))?.viewer;if(!G)return!1;let U;try{U=await fetch(n(it.session),{cache:"no-store"})}catch{return!1}const L=U.ok?(await U.json().catch(()=>null))?.viewer:null,K=sCA(G,U.status,L);return K&&h(K),K!==null}finally{p=!1}};function m(){if(l||C||B||w)return;if(typeof WebSocket>"u")return f();const G=new URL(n(it.events,{client:t}));G.protocol=G.protocol==="https:"?"wss:":"ws:";const U=new WebSocket(G);l=U,U.onopen=()=>{u=!0},U.onmessage=L=>{let K;try{K=JSON.parse(String(L.data))}catch{return}K.event&&a(K.event,K.data)},U.onclose=()=>{if(l===U&&(l=null),!w){if(!u)return f();D().then(L=>{L||l||C||B||(B=setTimeout(()=>{B=null,m()},2e3))})}}}let y=null;const R=()=>y??=o(it.session),M={async artifact(){const{artifact:G}=await R();return{id:G.id,title:async()=>(await o(it.session)).artifact.title,list:async()=>(await o(it.files)).files,readText:async L=>new TextDecoder().decode(await k(L)),readBytes:L=>k(L),publish:async L=>{const K={files:L,client:t};return o(it.publish,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(K)})},onChange:L=>c("files",L)}},async assets(){const{viewer:G}=await R();return nCA(G.role)?{upload:async(L,K)=>o(it.assets,{method:"POST",headers:{"content-type":L.type||"application/octet-stream"},body:L},K?.name?{name:K.name}:void 0)}:null},async user(){const{viewer:G}=await R();return{me:async()=>G}},async agent(){return{send:async(U,L)=>{const K={request:U,deliver:L?.deliver??"send"};return o(it.agentSend,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(K)})},status:async()=>(await o(it.session)).agent,onStatus:U=>c("agent",U)}},async room(){return{self:async()=>t,presence:async U=>{const L={client:t,patch:U};await o(it.presence,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(L)})},peers:async()=>(await o(it.peers)).peers,onPeers:U=>c("peers",U),emit:async(U,L)=>{const K={client:t,topic:U,data:L};await i(it.roomEmit,K)},onMessage:U=>c("room",U)}},async db(){const{stores:G}=await R();return G?.db?{get:async L=>(await o(it.dbGet,{cache:"no-store"},{path:L})).data,list:async L=>(await o(it.dbList,{cache:"no-store"},{collection:L})).documents,write:async L=>{const K={writes:L,client:t};await i(it.dbWrite,K)},onChange:L=>c("db",L)}:null},async comments(){const{stores:G}=await R();if(!G?.comments)return null;const U=async(K,H)=>(await i(K,H)).thread;return{list:async()=>(await o(it.comments,{cache:"no-store"})).threads,create:K=>U(it.commentsCreate,{input:K}),reply:(K,H)=>U(it.commentsReply,{threadId:K,text:H}),setResolved:(K,H)=>U(it.commentsResolve,{threadId:K,resolved:H}),move:(K,H,x)=>U(it.commentsMove,{threadId:K,anchor:H,...x?{location:x}:{}}),remove:async(K,H)=>{await i(it.commentsRemove,{threadId:K,...H?{messageId:H}:{}})},sendToAgent:K=>U(it.commentsSend,{threadId:K}),onChange:K=>c("comments",K)}},async history(){const{stores:G}=await R();if(!G?.history)return null;const U=(K,H)=>({n:String(K),...H===void 0?{}:{path:H}});return{list:()=>o(it.history,{cache:"no-store"}),files:async K=>(await o(it.historyFiles,{cache:"no-store"},U(K))).files,read:async(K,H)=>new TextDecoder().decode(await F(it.historyFile,U(K,H))),readBytes:(K,H)=>F(it.historyFile,U(K,H)),diff:(K,H)=>o(it.historyDiff,{cache:"no-store"},U(K,H)),restore:(K,H)=>i(it.historyRestore,{n:K,...H?{paths:H}:{},client:t}),dismissNotice:async K=>{await i(it.historyDismiss,{id:K})},onChange:K=>c("history",K)}},async mcp(){const{viewer:G}=await R();return G.role!=="owner"?null:{callTool:async(L,K,H,x)=>{const Y=x?.signal;Y?.throwIfAborted();const v={server:L,tool:K,args:H,...x?.timeoutMs===void 0?{}:{timeoutMs:x.timeoutMs}};try{return await o(it.mcpCall,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(v),...Y?{signal:Y}:{}})}catch(T){throw Y?.aborted?Y.reason:T}},listTools:L=>o(it.mcpTools,{cache:"no-store"},L===void 0?void 0:{server:L})}},async downloads(){return{save:async({name:U,data:L})=>o(it.downloads,{method:"POST",headers:{"content-type":L.type||"application/octet-stream"},body:L},{name:U})}}};function k(G){return F(it.file,{path:G})}async function F(G,U){let L;try{L=await fetch(n(G,U),{cache:"no-store"})}catch(K){throw new ZC("unavailable",K instanceof Error?K.message:String(K))}if(!L.ok)throw await yU(L);return new Uint8Array(await L.arrayBuffer())}return{get(G){const U=M[G];return U?U():null}}}const aCA="[Artifact comment sent to agent]",gCA="[Artifact edit request sent to agent]",cCA="[Artifact task finished]",lCA=1,uCA=1,ICA=/^[a-z][a-z0-9]{0,23}$/,CCA="may not have run: the artifact was updated before this call was answered",BCA=["quickstart","list","publish","read","open","call","adopt","delete","share"],ECA=["get","list","query","set","update","delete","str_replace","batch"],QCA=["read","reply","resolve","reopen","wait"],fCA=["share","export"],dCA={type:"object",properties:{action:{type:"string",enum:BCA,description:"What to do. Omitted: publish."},intent:{type:"string",description:"quickstart: what is being made (design, slides, whiteboard, document, data, other), or a few words about it."},scope:{type:"string",enum:["types","mine","all"],description:"list: the installed types, this session's and this workspace's artifacts (default), or every artifact."},type:{type:"string",description:"list: only artifacts of this type (an id, or open-artifact://type/<id>)."},query:{type:"string",description:"list: only artifacts whose title contains this text."},limit:{type:"integer",description:"list: how many to return (default 50, at most 200)."},cursor:{type:"string",description:"list: the next_cursor of the previous page."},type_url:{type:"string",description:"publish without url: the type to create from (open-artifact://type/<id>, from quickstart). read without url: the type to describe."},title:{type:"string",description:"publish without url: the new artifact's name."},folder:{type:"string",description:"publish without url, or adopt: where the artifact's folder goes (absolute, or relative to the workspace). Default <workspace>/artifacts/<slug>."},url:{type:"string",description:"An artifact: open-artifact://artifact/<id>, as publish returned it."},files:{type:"object",additionalProperties:!0,description:'publish with url: files to write under the artifact root, as {"rel/path": "text"} or {"rel/path": {"content": "...", "encoding": "base64"}}; null deletes.'},if_match:{type:"object",additionalProperties:!0,description:'publish with url: {"rel/path": sha256 | null | "*"}. Write only while the file still has the sha256 you read, does not exist (null), or anyway ("*"). One mismatch writes nothing and returns the current versions.'},check:{type:"boolean",description:"publish with url: run the type's check action after writing; its result comes back as check."},open:{type:"string",enum:["after_first_write","now"],description:"publish without url: after_first_write opens the page in your app once your first write lands; now opens it at once. Where your app cannot show pages by itself the result says so: open view_url in your app's built-in browser, if you have one."},related:{type:"boolean",description:"quickstart: list existing artifacts the recommended type can build on, such as design systems (default true)."},path:{type:"string",description:"read: one file or folder under the root (omitted: the record and the file list)."},paths:{type:"array",items:{type:"string"},description:"read: several files under the root at once."},name:{type:"string",description:"call: the action's name (check, upload, ...; read with url lists them)."},args:{type:"object",additionalProperties:!0,description:"call: the action's arguments. upload: {file: absolute path, name?, group?}."},panel:{type:"string",enum:fCA,description:"open: also open the page's Share panel (share), for the person to share it on the network, or its Export tab (export), for them to download a file."}}},hCA={type:"object",properties:{action:{type:"string",enum:ECA},url:{type:"string",description:"The artifact (open-artifact://artifact/<id>)."},collection:{type:"string"},doc_id:{type:"string"},path:{type:"string",description:"collection/doc_id, instead of the two."},data:{type:"object",additionalProperties:!0,description:"set / update: the document's fields."},file_path:{type:"string",description:"set / update: a JSON file holding the fields, instead of data."},if_match:{description:'set / update / delete / str_replace: the sha256 get returned (write only if unchanged), null (only if it does not exist) or "*" (replace whatever is there).'},field:{type:"string",description:"str_replace: the text field, as a dot path (body, notes.text)."},old:{type:"string",description:"str_replace: the passage to replace; it must occur exactly once."},new:{type:"string",description:"str_replace: the passage that replaces it."},where:{type:"array",items:{type:"object",additionalProperties:!0},description:"query: [{field, op, value}], all must hold. op: ==, !=, <, <=, >, >=, in, not-in (up to 30 values), array-contains."},order_by:{type:"object",additionalProperties:!0,description:'query: {field, dir: "asc" | "desc"}.'},limit:{type:"integer",description:"list / query: how many documents (default 100, at most 1000)."},cursor:{type:"string",description:"list / query: the next_cursor of the previous page."},out_file:{type:"string",description:"get / list / query: write the result to this JSON file (absolute, or relative to the workspace) and return only its path and counts."},writes:{type:"array",items:{type:"object",additionalProperties:!0},description:"batch: [{op: set|update|delete|str_replace, path | collection+doc_id, data | file_path, if_match?, field?, old?, new?}], at most 500."}},required:["action","url"]},wCA={type:"object",properties:{action:{type:"string",enum:QCA},url:{type:"string",description:"The artifact (open-artifact://artifact/<id>). wait: optional."},thread_id:{type:"string",description:'reply / resolve / reopen: the thread (after ";thread=" in the message).'},text:{type:"string",description:"reply: the answer."},resolve:{type:"boolean",description:"reply: resolve the thread too."},all:{type:"boolean",description:"read: resolved threads too."},since:{type:"string",description:"read: only threads with a message at or after this time (ISO 8601)."},acknowledge_duplicate:{type:"boolean",description:"reply: send the same text as your last reply in this thread again, on purpose."},timeout_ms:{type:"number",description:"wait: how long (default 600000)."}},required:["action"]},mU={Artifact:dCA,ArtifactData:hCA,ArtifactComments:wCA},pCA={Artifact:["Make and change artifacts: typed folders of files that open as live pages the person can view, edit, comment on and export. Actions:","- quickstart {intent}: call first for a new artifact; recommends a type and returns the call that creates it.",'- list {scope: "mine" | "all" | "types", type?, query?}: find existing artifacts, or the installed types.',"- publish {type_url, title, folder?, open?}: create an artifact; the result carries its root folder and the type's instructions. publish {url, files, if_match?, check?}: write files when you have no file tools of your own.","- read {url, path? | paths?}: the artifact's record, files and actions, or some of its files with their sha256. read {type_url}: a type's instructions, before creating.",`- open {url, panel?}: show it to the person in the computer's browser (or the app, when it shows pages), once its content is written. When your app has a built-in browser, open view_url there instead. panel "share" or "export" opens its Share panel or Export tab for them.`,"- call {url, name, args?}: run one of the type's actions (check, upload, ...). A long one answers {task, pending: true}; its result comes later as a message.","- adopt {url | folder}: take over an artifact, or add an existing folder. Only when the person asks.","- share {url}: whether it is shared on the local network, and its links. Only the person changes that, in the page's Share panel.","- delete {url}: forget an artifact; its folder stays. Only when the person asks."].join(`
35
+ `:C)});break}const B=c.items.map((Q,f)=>d.jsx("li",{value:c.ordered?Q.n:void 0,children:d.jsx("span",{className:bm,children:PI(Q.c,e,u+"."+f,n+1)})},f));r.push(c.ordered?d.jsx("ol",{className:quA,children:B},u):d.jsx("ul",{className:PuA,children:B},u));break}}}),a(t+".end"),o}function QC(A,e){return A.map((t,n)=>{if(typeof t=="string")return t;const o=e+":"+n;switch(t.t){case"raw":return d.jsx(N.Fragment,{children:t.raw},o);case"code":return d.jsx("code",{dir:"ltr",className:Pj,children:t.text},o);case"em":return d.jsx("em",{children:QC(t.c,o)},o);case"strong":return d.jsx("strong",{className:"font-semibold",children:QC(t.c,o)},o);case"del":return d.jsx("del",{children:QC(t.c,o)},o)}})}function BU(A,e=new Date){const t=new Date(A);if(Number.isNaN(t.getTime()))return"";if(e.getTime()-t.getTime()<6e4)return"now";const n=t.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"}),o=a=>new Date(a.getFullYear(),a.getMonth(),a.getDate()).getTime(),i=Math.round((o(e)-o(t))/864e5);return i===0?n:i===1?`Yesterday, ${n}`:`${t.toLocaleDateString("en-US",{month:"short",day:"numeric",...t.getFullYear()!==e.getFullYear()?{year:"numeric"}:{}})}, ${n}`}function uIA(A,e=new Date){const t=new Date(A);if(Number.isNaN(t.getTime()))return"";const n=Math.floor((e.getTime()-t.getTime())/6e4);if(n<1)return"now";if(n<60)return`${n}m`;const o=Math.floor(n/60);if(o<24)return`${o}h`;const i=Math.floor(o/24);return i<7?`${i}d`:t.toLocaleDateString("en-US",{month:"short",day:"numeric",...t.getFullYear()!==e.getFullYear()?{year:"numeric"}:{}})}const EU=A=>{let e;const t=new Set,n=(l,u)=>{const C=typeof l=="function"?l(e):l;if(!Object.is(C,e)){const B=e;e=u??(typeof C!="object"||C===null)?C:Object.assign({},e,C),t.forEach(Q=>Q(e,B))}},o=()=>e,a={setState:n,getState:o,getInitialState:()=>c,subscribe:l=>(t.add(l),()=>t.delete(l))},c=e=A(n,o,a);return a},IIA=(A=>A?EU(A):EU),CIA=A=>A;function BIA(A,e=CIA){const t=UI.useSyncExternalStore(A.subscribe,UI.useCallback(()=>e(A.getState()),[A,e]),UI.useCallback(()=>e(A.getInitialState()),[A,e]));return UI.useDebugValue(t),t}const QU=A=>{const e=IIA(A),t=n=>BIA(e,n);return Object.assign(t,e),t},ln=(A=>A?QU(A):QU),EIA=4e3;function QIA(A){return A.wakesIdle===!1?`${A.name} gets this on its next turn: send it a message to start one`:"Waiting for the agent"}function fIA(A,e){return e===!1?{title:`Sent to ${A}`,description:`${A} gets it on its next turn. If it is idle, send it a message there to start one.`}:{title:`Sent to ${A}`}}function Zj(A){return A.reduce((e,t)=>t.status==="open"?e+t.messages.length:e,0)}function dIA(A){return A==="detached"?"What this was on is gone; shown on what held it.":A==="orphaned"?"What this was on has been deleted.":null}function hIA(A){const e=A.maxThreads??500,t=A.noun??"document",n=h=>A.notify?.(h);let o=null,i,r=0;const a=ln()(h=>({available:!1,threads:[],on:!1,listOpen:!1,active:null,draft:null,showResolved:!1,sendNew:!1,draftText:"",replies:{},setOn(D){h({on:D,draft:null}),A.onModeChange?.(D)},setListOpen(D){h({listOpen:D})},setActive(D){h({active:D,draft:null})},setDraft(D){h(D===null?{draft:D,active:null,draftText:"",sendNew:!1}:{draft:D,active:null})},setShowResolved(D){h({showResolved:D})},setSendNew(D){h({sendNew:D})},setDraftText(D){h({draftText:D})},setReply(D,m){h(y=>({replies:{...y.replies,[D]:m}}))}})),c=new Map,l=h=>{let D=c.get(h.anchor);return D===void 0&&(D=A.parse(h.anchor),c.size>2e3&&c.clear(),c.set(h.anchor,D)),D},u=h=>{n({title:"The comment could not be saved",description:h instanceof Error?h.message:String(h)})},C=h=>{a.setState(D=>({threads:D.threads.map(m=>m.id===h.id?h:m)})),A.heard?.([h])},B=h=>A.checkText?A.checkText(h):h.trim().slice(0,EIA)||void 0,Q=()=>!!o&&A.canComment(),f=()=>!!o&&A.canSendToAgent(),p={store:a,adapter:A,async start(h,D){if(!h)return;o=h;const m=r;a.setState({available:!0});try{const R=await h.list();if(m!==r)return;a.setState({threads:R}),A.heard?.(R)}catch{}if(m!==r)return;i=h.onChange(R=>{const M=a.getState().active;a.setState({threads:R,active:M&&R.some(k=>k.id===M)?M:null}),A.heard?.(R)});const y=D?a.getState().threads.find(R=>R.id===D):void 0;y&&p.reveal(y)},stop(){r+=1,i?.(),i=void 0},capability:()=>o,canComment:Q,canSendToAgent:f,canRemove:()=>!!o&&(A.canRemove?A.canRemove():A.canComment()),anchorOf:l,labelOf:h=>A.label(h),stateOf:h=>A.state?.(h)??"ok",stateNote:h=>A.stateNote?A.stateNote(h??"ok"):dIA(h),async create(h,D,m){if(!o)return!1;const y=B(D);if(!y)return!1;if(a.getState().threads.length>=e)return n({title:`This ${t} already has ${e} comments`}),!1;try{const R=A.detail?.(h),M=await o.create({anchor:A.serialize(h),label:A.label(h),...R!==void 0?{detail:R}:{},location:A.location?.(h)??{},text:y});return a.setState(k=>({threads:k.threads.some(F=>F.id===M.id)?k.threads:[...k.threads,M],draft:null,draftText:"",sendNew:!1,active:M.id})),A.heard?.([M]),m?.send&&f()&&await p.sendToAgent(M.id),!0}catch(R){return u(R),!1}},async reply(h,D,m){if(!o)return!1;const y=B(D);if(!y)return!1;try{let R=await o.reply(h,y);return R.status==="resolved"&&(R=await o.setResolved(h,!1)),C(R),a.setState(M=>{const{[h]:k,...F}=M.replies;return{replies:F}}),m?.send&&f()&&await p.sendToAgent(h),!0}catch(R){return u(R),!1}},async resolve(h,D){if(o)try{C(await o.setResolved(h,D));const m=a.getState();D&&m.active===h&&!m.showResolved&&a.setState({active:null})}catch(m){u(m)}},async remove(h,D){if(!(!o||A.canRemove&&!A.canRemove()))try{await o.remove(h,D),D||a.setState(m=>({threads:m.threads.filter(y=>y.id!==h),active:m.active===h?null:m.active}))}catch(m){u(m)}},async move(h,D){if(o)try{C(await o.move(h,A.serialize(D),A.location?.(D)))}catch(m){u(m)}},async sendToAgent(h){if(!o||!f())return!1;const D=A.sendToAgent?a.getState().threads.find(m=>m.id===h):void 0;if(A.sendToAgent)return D?A.sendToAgent(D,l(D)):!1;try{return C(await o.sendToAgent(h)),n(fIA(A.agentName?.()||"the agent",A.agentWakesIdle?.())),!0}catch(m){return u(m),!1}},async sendAllToAgent(){const h=a.getState().threads.filter(D=>p.canSendThread(D));for(const D of h)await p.sendToAgent(D.id)},canSendThread(h){if(h.status!=="open")return!1;const D=h.messages.at(-1);return!D||D.author.kind!=="person"?!1:!h.agent||h.agent.status==="replied"},reveal(h){A.reveal?.(l(h)),a.getState().setActive(h.id)},show(h){const D=a.getState();D.on||D.setOn(!0),h.status==="resolved"&&!a.getState().showResolved&&a.getState().setShowResolved(!0),p.reveal(h)},viewerName:()=>A.viewerName?.()||"You"};return p}const $j=300,fC=12,wIA=$j+fC*2;function pIA({comments:A,agent:e,top:t=fC,hint:n}){return A.store(i=>i.listOpen&&i.available)?d.jsx(tE,{mark:"data-comments-panel-layer",children:d.jsx(DIA,{comments:A,agent:e,top:t,hint:n})}):null}const fU=A=>A.messages[0]?.at??"";function DIA({comments:A,agent:e,top:t,hint:n}){const{dark:o}=eE(),i=A.store(Q=>Q.threads),r=A.store(Q=>Q.showResolved),a=A.store(Q=>Q.on),c=A.store(Q=>Q.active),l=()=>A.store.getState().setListOpen(!1),u=i.filter(Q=>Q.messages.length>0),C=u.filter(Q=>r||Q.status==="open").sort((Q,f)=>fU(f).localeCompare(fU(Q))),B=u.filter(Q=>Q.status==="resolved").length;return d.jsxs("section",{"aria-label":"All comments","data-comments-panel":"",className:Mt(bk(),"fixed flex flex-col text-body text-primary"),style:{top:t,right:fC,width:$j,maxWidth:`calc(100vw - ${fC*2}px)`,maxHeight:`calc(100dvh - ${t+fC}px)`,zIndex:40,pointerEvents:"auto",...Rk(o)},onKeyDown:Q=>{const f=Q.target instanceof Element&&Q.target.closest("[data-cds=Menu]");Q.key==="Escape"&&!Q.defaultPrevented&&!f&&(Q.preventDefault(),l())},children:[d.jsxs("div",{className:"flex shrink-0 items-center gap-xs",style:{padding:"10px 10px 6px 16px"},children:[d.jsx("span",{className:"min-w-0 flex-1 truncate font-medium",children:"All comments"}),d.jsx(mIA,{showResolved:r,onShowResolved:Q=>A.store.getState().setShowResolved(Q)}),d.jsx(Hi,{variant:"ghost",iconOnly:!0,"aria-label":"Close",icon:d.jsx(pi,{name:"X",size:"sm"}),onClick:l})]}),d.jsx(SIA,{comments:A,agent:e,threads:u}),d.jsxs("div",{className:"flex min-h-0 flex-col gap-xs overflow-y-auto [--cds-comment-card-bg:var(--cds-surface-2)]",style:{padding:"0 12px 12px"},children:[u.length===0?d.jsxs("div",{"data-comments-empty":"",className:"flex flex-1 flex-col items-center justify-center gap-xs px-lg text-center",style:{paddingBlock:"var(--cds-pad-xl)"},children:[d.jsx("span",{className:"text-body font-medium text-secondary",children:"No comments yet"}),d.jsx("span",{className:"text-caption text-muted",children:A.canComment()?n??"Press the comment button, then click anywhere on the artifact to add one.":"Only people with comment access can add one."})]}):C.length===0?d.jsxs("span",{"data-comments-filtered-empty":"",className:"px-lg text-center text-caption text-muted",style:{paddingBlock:"var(--cds-pad-xl)"},children:["No open comments.",B>0?d.jsxs(d.Fragment,{children:[" ",d.jsx("button",{type:"button",className:"cds-text-link cds-text-link-underline inline text-inherit",onClick:()=>A.store.getState().setShowResolved(!0),children:`Show ${B} resolved`})]}):null]}):null,C.map(Q=>d.jsx(NIA,{comments:A,agent:e,thread:Q,current:a&&c===Q.id},Q.id))]})]})}function yIA(){return d.jsx("svg",{"data-cds":"Icon","aria-hidden":!0,width:"1em",height:"1em",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:1.2,strokeLinecap:"round",style:{fontSize:"calc(1rem * var(--cds-rem-scale,1))"},children:d.jsx("path",{d:"M2.5 4.5h11M4.5 8h7M6.5 11.5h3"})})}function mIA({showResolved:A,onShowResolved:e}){const[t,n]=Lk();return d.jsxs(JB,{open:t,onOpenChange:n,modal:!1,children:[d.jsx(Ug,{content:"Filter",disabled:t,children:d.jsx(HB,{render:d.jsx(Hi,{variant:"ghost",iconOnly:!0,tooltip:!1,"aria-label":"Filter",icon:d.jsx(yIA,{})})})}),d.jsx(Mk,{align:"end",children:d.jsxs(d8,{checked:A,onCheckedChange:e,closeOnClick:!1,className:Mt(kj,"group/cb text-primary data-[highlighted]:bg-fill-ghost-hover"),children:[d.jsx(Gj,{}),d.jsx("span",{className:"min-w-0 flex-1 truncate",children:"Show resolved"})]})})]})}function SIA({comments:A,agent:e,threads:t}){const[n,o]=N.useState(!1),[i,r]=N.useState(!1),a=t.filter(u=>u.status==="open"&&u.messages.some(C=>C.author.kind==="person"));if(!A.canSendToAgent()||!e.available||a.length===0)return null;const l=!a.some(u=>A.canSendThread(u))?i?`These comments were just sent to ${e.name}.`:`${e.name} has every comment.`:void 0;return d.jsx("div",{className:"flex shrink-0 flex-col items-end gap-sm",style:{padding:"0 12px 8px"},children:d.jsx(Ug,{content:l,side:"bottom",children:d.jsx(Hi,{"data-comments-send-all":"","data-size":"sm",variant:"secondary",busy:n,"aria-disabled":l!==void 0||n||void 0,className:"aria-disabled:opacity-disabled",onClick:()=>{l!==void 0||n||(o(!0),A.sendAllToAgent().then(()=>r(!0)).finally(()=>o(!1)))},children:`Send all to ${e.name}`})})})}function NIA({comments:A,agent:e,thread:t,current:n}){const[o,i]=N.useState(!1),[r,a]=N.useState(!1),[c,l]=N.useState(!1),u=N.useId(),C=t.messages[0],B=t.messages.length-1,Q=t.status==="resolved",f=A.canComment(),w=C.author.kind==="agent"?C.author.name||e.name:C.author.name||"Someone",p=[...Q&&f?[{label:"Reopen",icon:"Comment",onSelect:()=>{A.resolve(t.id,!1)}}]:[],...A.canRemove()?[{label:"Delete thread",icon:"Trash",variant:"danger",onSelect:()=>i(!0)}]:[]];return d.jsxs(Yj,{variant:"flat",expanded:!1,active:n,labelledBy:u,onExpand:()=>A.show(t),className:"rounded",children:[d.jsx(nd,{nameId:u,authorName:w,agent:C.author.kind==="agent",timestamp:d.jsxs(d.Fragment,{children:[uIA(C.at),Q&&" · Resolved",t.agent?d.jsx("span",{role:"img","aria-label":`Sent to ${e.name}`,className:"inline-flex",style:{width:18,height:18,marginInlineStart:4,verticalAlign:"middle",color:"var(--cds-fill-brand)"},children:d.jsx(vj,{})}):null]}),confirm:o?d.jsx(Tj,{busy:c,onCancel:()=>i(!1),onDelete:()=>{l(!0),A.remove(t.id).finally(()=>l(!1))}}):void 0,actions:d.jsxs(Fk,{placement:n?"pinned":void 0,children:[f?d.jsx(Kj,{resolved:Q,busy:r,onResolve:()=>{a(!0),A.resolve(t.id,!0).finally(()=>a(!1))}}):null,d.jsx(Uj,{items:p})]}),children:d.jsx("span",{className:"line-clamp-3",children:SN(C.text,{flat:!0})})}),B>0&&!o?d.jsx("button",{type:"button","data-cds-part":"replies-toggle",className:"self-start text-body font-normal text-accent hover:underline",children:B===1?"1 reply":`${B} replies`}):null]})}function dU(A,e){return{x:e.x*A.zoom+A.x,y:e.y*A.zoom+A.y}}function bIA(A,e){const t=A.zoom||1;return{x:(e.x-A.x)/t,y:(e.y-A.y)/t}}function RIA(A,e){return{left:e.x*A.zoom+A.x,top:e.y*A.zoom+A.y,width:e.w*A.zoom,height:e.h*A.zoom}}const MIA=5,hU="#ae7303",kIA="<svg xmlns='http://www.w3.org/2000/svg' width='28' height='28' viewBox='0 0 28 28'><path d='M 2 26 L 2 14 A 12 12 0 1 1 14 26 Z' fill='#000' stroke='#fff' stroke-width='2'/></svg>";`${kIA.replace(/[ '<>#]/g,A=>"%"+A.charCodeAt(0).toString(16).toUpperCase())}`;const fr=36,cf=4,xn=8,xIA=330,wU=6,kN=48;function lf(A,e){const t=e.height-(A.y+cf),n=A.y-cf,o=t<320&&n>t&&(n>=240||t<240&&n>=48);return{left:Math.min(Math.max(A.x,0),Math.max(0,e.width-(fr+xn))),top:o?A.y-(fr+cf):A.y+cf,flip:o}}const AP=A=>Math.max(320,Math.round(A*.6));function vIA(A,e){const t=xn,n=e.height-xn,o=(r,a,c)=>Math.min(Math.max(r,a),c),i=A.flip?o(A.top+fr+2,Math.min(n,t+kN),n)-t:n-o(A.top-2,t,Math.max(t,n-kN));return Math.min(AP(e.height),Math.max(0,i))}function xN({pin:A,corner:e,viewport:t,onEscape:n,children:o}){const i=N.useRef(null),[r,a]=N.useState(0);N.useLayoutEffect(()=>{const Q=i.current;if(!Q)return;a(Q.offsetHeight);const f=new ResizeObserver(()=>a(Q.offsetHeight));return f.observe(Q),()=>f.disconnect()},[]);const c=Math.max(0,Math.min(xIA,t.width-2*xn));let l,u,C;if(e||!A){const Q=e??{x:xn,y:xn};l=Math.max(xn,Math.min(Q.x,t.width-xn-c)),u=Math.max(xn,Math.min(Q.y,t.height-xn-r)),typeof o=="function"&&(C=Math.min(AP(t.height),Math.max(kN,t.height-xn-Math.max(xn,Q.y))))}else{if(l=A.left+fr+wU,l+c>t.width-xn){const Q=A.left-wU-c;l=Q>=xn?Q:Math.max(xn,t.width-xn-c)}u=A.flip?A.top+fr+2-r:A.top-2,u=Math.max(xn,Math.min(u,t.height-xn-r)),typeof o=="function"&&(C=vIA(A,t))}const B={position:"absolute",left:l,top:u,width:c,pointerEvents:"auto",...C===void 0?{}:{maxHeight:C,display:"flex",flexDirection:"column"},...r?{}:{opacity:0,pointerEvents:"none"}};return d.jsx("div",{ref:i,style:B,"data-comment-card":"",onKeyDown:Q=>{Q.key!=="Escape"||Q.defaultPrevented||(Q.preventDefault(),n())},children:typeof o=="function"?o(C):o})}const GIA="cds-reset absolute flex items-center justify-center rounded-full rounded-tl-none border-0 p-0 cursor-[var(--cds-cursor-interactive)] outline-none focus-visible:outline-hidden focus-visible:shadow-focus";function eP({pin:A,avatar:e,draft:t=!1,label:n,title:o,expanded:i,faded:r=!1,...a}){const{pinId:c,...l}=a,u={left:A.left,top:A.top,width:fr,height:fr,pointerEvents:t?"none":"auto",touchAction:"none",...A.flip?{borderRadius:"9999px 9999px 9999px 0"}:{},...r?{opacity:.7}:{}};return d.jsx("button",{type:"button","data-comment-pin":c,"aria-label":n,title:o,"aria-expanded":i,tabIndex:t?-1:void 0,className:Mt(GIA,t?"bg-fill-accent":"bg-surface-2 shadow-panel-sm"),style:u,...l,children:d.jsx("span",{className:"flex rounded-full bg-surface-1",children:e})})}function vN(A,e){return A.author.kind==="agent"?A.author.name||e.name:A.author.name||"Someone"}function FIA(A,e){const t=A.messages[0];return t?d.jsx(oh,{name:vN(t,e),variant:t.author.kind==="agent"?"agent":"default",size:"sm"}):d.jsx(oh,{name:"?",size:"sm"})}function LIA({comments:A,camera:e,viewport:t,place:n,highlight:o,anchorAt:i,movable:r,onMove:a,agent:c,revision:l,piles:u=!0,insets:C}){const B=(r??!0)&&!!(i||a),Q=A.store(v=>v.available),f=A.store(v=>v.threads),w=A.store(v=>v.active),p=A.store(v=>v.draft),h=A.store(v=>v.on),D=A.store(v=>v.showResolved),m=A.store(v=>v.listOpen),[y,R]=N.useState(null),M=N.useMemo(()=>{if(!Q)return[];const v=[];for(const T of f){if(T.messages.length===0||T.status!=="open"&&!D&&T.id!==w)continue;const _=A.anchorOf(T),j=n(_);j&&v.push({key:T.id,thread:T,anchor:_,state:j.state,screen:dU(e,j.world)})}if(p!==null){const T=n(p);T&&v.push({key:"draft",thread:null,anchor:p,state:T.state,screen:dU(e,T.world)})}return v},[Q,f,w,p,D,e,n,l,A]);if(!Q||!h&&!w&&p===null&&M.length===0)return null;const k=p!==null?"draft":w,F=M.find(v=>v.key===k),G=F&&o?o(F.anchor):null,U=M.filter(v=>v.thread),L=u?wuA({points:U.map(v=>({id:v.key,x:v.screen.x,y:v.screen.y})),openId:w,box:{left:0,top:0,width:t.width,height:t.height},top:0,floor:C?.top??0,foot:C?.bottom?C.bottom+8:0,reserveRight:m?wIA:0}):null,K=U.filter(v=>!L?.piled.has(v.key)).map(v=>({...v,box:lf(v.screen,t)})),H=RuA(K.map(v=>({id:v.key,x:v.box.left,y:v.box.top,w:fr})),t.width,fr),x=v=>A.store.getState().setActive(v),Y=F?.thread?F:void 0;return d.jsxs(d.Fragment,{children:[G?d.jsx("div",{"data-comment-target":"",className:Mt("pointer-events-none absolute",!G.area&&"rounded"),style:{...RIA(e,G),border:G.area?`1px dashed ${hU}`:`1.5px solid ${hU}`}}):null,d.jsxs(tE,{className:"pointer-events-none absolute inset-0 z-[3]",mark:"data-comment-layer",onEscape:()=>{const v=A.store.getState();return v.draft!==null||v.active?(v.setDraft(null),v.setActive(null),!0):!1},children:[K.map(v=>{const T=v.thread,_=y?.id===T.id?y:null,j={...v.box,left:v.box.left+(H.get(v.key)??0)+(_?.x??0),top:v.box.top+(_?.y??0)};return d.jsx(YIA,{comments:A,thread:T,box:j,avatar:FIA(T,c),expanded:w===T.id,detached:v.state==="detached",onDrag:P=>R(P?{id:T.id,...P}:null),movable:B,onDrop:P=>{const O={x:v.screen.x+P.x,y:v.screen.y+P.y};a?a(T.id,O):i&&A.move(T.id,i(bIA(e,O)))}},v.key)}),L?d.jsx("div",{style:{display:"contents",pointerEvents:"auto"},children:d.jsx(buA,{piles:L,onOpen:v=>{const T=f.find(_=>_.id===v);T&&A.show(T)}})}):null,Y?d.jsx(xN,{pin:lf(Y.screen,t),viewport:t,onEscape:()=>x(null),children:v=>d.jsx(tP,{comments:A,agent:c,thread:Y.thread,state:Y.state,maxHeight:v})},Y.key):null,F&&!F.thread&&p!==null?d.jsxs(d.Fragment,{children:[d.jsx(eP,{pin:lf(F.screen,t),draft:!0,label:"New comment",avatar:d.jsx(oh,{name:A.viewerName(),size:"sm"})}),d.jsx(xN,{pin:lf(F.screen,t),viewport:t,onEscape:()=>A.store.getState().setDraft(null),children:d.jsx(TIA,{comments:A,agent:c,anchor:p})})]}):null]})]})}function YIA({comments:A,thread:e,box:t,avatar:n,expanded:o,detached:i,movable:r,onDrag:a,onDrop:c}){const l=N.useRef(null),u=N.useRef(!1),C=e.status==="resolved";return d.jsx(eP,{pinId:e.id,pin:t,avatar:n,expanded:o,faded:i,label:`Comment: ${e.label}${C?" (resolved)":""}`,title:i?"What this comment was on is gone":e.label,onPointerDown:B=>{if(B.button===0){l.current={x:B.clientX,y:B.clientY,moved:!1},u.current=!1;try{B.currentTarget.setPointerCapture(B.pointerId)}catch{}}},onPointerMove:B=>{const Q=l.current;if(!Q||!r||!A.canComment())return;const f=B.clientX-Q.x,w=B.clientY-Q.y;!Q.moved&&Math.hypot(f,w)<MIA||(Q.moved=!0,a({x:f,y:w}))},onPointerUp:B=>{const Q=l.current;l.current=null,Q?.moved&&(u.current=!0,a(null),c({x:B.clientX-Q.x,y:B.clientY-Q.y}))},onClick:()=>{if(u.current){u.current=!1;return}const B=A.store.getState();B.setActive(B.active===e.id?null:e.id)}})}function UIA(A,e){const t=N.useRef(null);N.useLayoutEffect(()=>{const o=t.current,i=A.current;if(!o||!i)return;i.scrollTop=i.scrollHeight;const r=e.messages.at(-1);if(r&&r.id!==o.after&&r.author.kind==="agent"){const a=[...i.querySelectorAll('[data-cds-part="comment"]')].at(-1),c=a?i.getBoundingClientRect().top-a.getBoundingClientRect().top:0;if(c>0){i.scrollTop-=c,t.current=null;return}}o.at=i.scrollTop});const n=()=>{t.current=null};return{start:()=>{t.current={after:e.messages.at(-1)?.id,at:0}},regionProps:{onPointerDownCapture:n,onWheelCapture:o=>{o.deltaY<0&&n()},onScroll:o=>{const i=o.currentTarget,r=t.current;r&&Math.abs(i.scrollTop-r.at)>2&&i.scrollHeight-i.scrollTop-i.clientHeight>2&&n()}}}}function tP(A){return d.jsx(_j,{children:d.jsx(KIA,{...A})})}function KIA({comments:A,agent:e,thread:t,state:n,maxHeight:o,onClose:i}){const[r,a]=N.useState(!1),[c,l]=N.useState(!1),[u,C]=N.useState(!1),[B,Q]=N.useState(!1),f=N.useId(),w=N.useRef(null),p=UIA(w,t),h=A.store(H=>H.replies[t.id])??{text:"",send:!1},D=A.canSendToAgent()&&e.available,m=A.canComment(),[y,...R]=t.messages;if(!y)return null;const M=i??(()=>A.store.getState().setActive(null)),k=A.stateNote(n??A.stateOf(A.anchorOf(t))),F=`Send to ${e.name}`,G=A.canRemove()?[{label:"Delete thread",icon:"Trash",variant:"danger",onSelect:()=>a(!0)}]:[],U=t.status==="open"?t.agent?.status:void 0,L=U==="pending"?"queued":U==="delivered"?"working":void 0,K=H=>A.store.getState().setReply(t.id,H);return d.jsxs(Yj,{expanded:!0,active:!0,onClose:M,labelledBy:f,maxHeight:o,scrollRef:w,scrollProps:p.regionProps,className:"min-h-0 flex-1",reply:m&&d.jsx(suA,{children:d.jsx(Jj,{label:"Reply",placeholder:t.status==="resolved"?"Reply to reopen…":D&&h.send?"What do you want to edit?":void 0,value:h.text,onChange:H=>K({...h,text:H}),sendBox:D?{label:F,checked:h.send,onCheckedChange:H=>K({...h,send:H})}:void 0,busy:B,onSubmit:(H,{send:x})=>{p.start(),Q(!0),A.reply(t.id,H,{send:D&&x}).finally(()=>Q(!1))},onCancel:M})}),children:[d.jsx(nd,{nameId:f,authorName:vN(y,e),agent:y.author.kind==="agent",timestamp:BU(y.at),footnote:k??void 0,confirm:r?d.jsx(Tj,{busy:u,onCancel:()=>a(!1),onDelete:()=>{C(!0),A.remove(t.id).finally(()=>C(!1))}}):void 0,actions:m||G.length>0?d.jsxs(Fk,{children:[m?d.jsx(Kj,{resolved:t.status==="resolved",busy:c,onResolve:()=>{l(!0),A.resolve(t.id,!0).finally(()=>l(!1))}}):null,d.jsx(Uj,{items:G})]}):void 0,children:SN(y.text)}),R.length>0||L?d.jsxs(iuA,{children:[R.map(H=>d.jsx(nd,{authorName:vN(H,e),agent:H.author.kind==="agent",timestamp:BU(H.at),children:SN(H.text)},H.id)),L?d.jsx(nd,{authorName:e.name,agent:!0,working:L,footnote:L==="queued"?QIA(e):"Working…"}):null]}):null]})}function TIA(A){return d.jsx(_j,{children:d.jsx(JIA,{...A})})}function JIA({comments:A,agent:e,anchor:t,onCancel:n}){const o=A.store(C=>C.draftText),i=A.store(C=>C.sendNew),[r,a]=N.useState(!1),c=N.useRef(null),l=A.canSendToAgent()&&e.available;N.useEffect(()=>{c.current?.focus({preventScroll:!0})},[t]);const u=()=>n?n():A.store.getState().setDraft(null);return d.jsx(Jj,{textareaRef:c,context:A.labelOf(t),value:o,onChange:C=>A.store.getState().setDraftText(C),sendBox:l?{label:`Send to ${e.name}`,checked:i,onCheckedChange:C=>A.store.getState().setSendNew(C)}:void 0,busy:r,onSubmit:(C,B)=>{r||(a(!0),A.create(t,C,{send:l&&B.send}).finally(()=>a(!1)))},onCancel:u})}function HIA({comments:A,shortcut:e="C",side:t="bottom"}){return A.store(o=>o.available)?d.jsx(tE,{inline:!0,mark:"data-comments-button",children:d.jsx(OIA,{comments:A,shortcut:e,side:t})}):null}function OIA({comments:A,shortcut:e,side:t}){const[n,o]=Lk(),i=A.store(B=>Zj(B.threads)),r=A.store(B=>B.on),a=A.store(B=>B.listOpen),c=!r&&i>0,l=r?"Done commenting":i>0?`${i} open ${i===1?"comment":"comments"}`:"Comments",u=B=>{o(!1),A.store.getState().setListOpen(B)},C=a?{label:"Hide comments",onSelect:()=>u(!1)}:{label:"Show all comments",trailing:i,onSelect:()=>u(!0)};return d.jsxs("span",{className:"flex shrink-0 items-center",children:[A.canComment()?d.jsx(Ug,{content:l,shortcut:e,side:t,children:d.jsx(Hi,{variant:"ghost",iconOnly:!0,tooltip:!1,"aria-label":"Comments","aria-pressed":r,icon:d.jsxs("span",{className:"relative inline-flex",children:[d.jsx(pi,{name:r?"CommentFilled":"Comment",size:"sm"}),c?d.jsx("span",{"aria-hidden":!0,className:"absolute rounded-full bg-fill-accent",style:{top:-1,right:-2,width:6,height:6,boxShadow:"0 0 0 1.5px var(--cds-page-bg)"}}):null]}),onClick:()=>A.store.getState().setOn(!r)})}):null,d.jsxs(JB,{open:n,onOpenChange:o,modal:!1,children:[d.jsx(Ug,{content:"Comment options",disabled:n,side:t,children:d.jsx(HB,{render:d.jsx(Hi,{variant:"ghost","aria-label":"Comment options",style:{paddingInline:2},children:d.jsx(pi,{name:"CaretDown",size:"xs"})})})}),d.jsx(Mk,{align:"end",children:d.jsx(xj,{items:[C]})})]})]})}const pU=200,GN=ln()(()=>({message:"",serial:0}));function _IA(A){const e=A.replace(/\s+/g," ").trim();return e.length>pU?`${e.slice(0,pU-1)}…`:e}function wt(A){const e=_IA(A);e&&GN.setState(t=>({message:e,serial:t.serial+1}))}function jIA(){const A=GN(t=>t.message),e=GN(t=>t.serial);return d.jsx("div",{role:"status","aria-live":"polite","aria-atomic":"true",className:"sr-only",style:{position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap"},children:d.jsx("span",{children:A},e)})}const nE=N.forwardRef(function({className:e,...t},n){return d.jsx("div",{ref:n,className:ye("pointer-events-auto flex items-center gap-1 rounded-[12px] bg-chrome text-chrome-fg shadow-chrome",e),...t})});function Uk({className:A,vertical:e=!0}){return d.jsx("div",{"aria-hidden":"true",className:ye(e?"mx-0.5 h-[18px] w-px":"my-1 h-px w-full","shrink-0 bg-chrome-line",A)})}const PIA=A=>A?{[A]:""}:{};function lr({label:A,shortcut:e,side:t="bottom",children:n,disabled:o}){return d.jsxs(NM,{disabled:o,children:[d.jsx(bM,{render:n}),d.jsx(RM,{children:d.jsx(vM,{side:t,sideOffset:8,className:"z-[1000]",children:d.jsxs(GM,{className:"flex max-w-80 items-center gap-1.5 rounded-[6px] bg-tip px-2 py-[5px] text-[13px] leading-[18px] text-tip-fg shadow-[0_1px_2px_rgb(11_11_11/0.06),0_2px_8px_rgb(11_11_11/0.08)] transition-opacity data-[ending-style]:opacity-0 data-[starting-style]:opacity-0",children:[d.jsx("span",{children:A}),e?d.jsx("kbd",{className:"rounded-[4px] bg-white/15 px-1 font-sans text-[12px] leading-4 text-tip-fg/80",children:e}):null]})})})]})}const qIA={md:"h-7",lg:"h-8",xl:"h-9"},WIA={md:"w-7",lg:"w-8",xl:"w-9"},Ki=N.forwardRef(function({pressed:e,square:t,size:n="md",className:o,type:i="button",...r},a){return d.jsx("button",{ref:a,type:i,"aria-pressed":e,className:ye("inline-flex shrink-0 select-none items-center justify-center gap-1 whitespace-nowrap rounded-[8px] text-[14px] font-control leading-5 text-chrome-fg outline-none transition-colors duration-100 ease-out","hover:bg-chrome-hover focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-chrome-focus","disabled:pointer-events-none disabled:opacity-40",qIA[n],t?WIA[n]:"px-[9px]",e&&"bg-chrome-pressed text-chrome-pressed-fg hover:bg-chrome-pressed",o),...r})}),dC=N.forwardRef(function({tip:e,shortcut:t,side:n,disabled:o,...i},r){const a=d.jsx(Ki,{ref:r,disabled:o,...i});return d.jsx(lr,{label:e,shortcut:t,side:n,children:o?d.jsx("span",{className:"inline-flex",children:a}):a})}),id=N.forwardRef(function({label:e,tip:t,icon:n,shortcut:o,tipSide:i="top",size:r="xl",className:a,...c},l){return d.jsx(lr,{label:t??e,shortcut:o,side:i,children:d.jsx(Ki,{ref:l,square:!0,size:r,"aria-label":e,className:ye("[&_svg]:size-[18px] [&_svg]:shrink-0",a),...c,children:n})})}),VIA="min-w-[128px] max-w-[320px] rounded-[14px] bg-chrome p-1.5 text-[14px] leading-5 font-control text-chrome-fg shadow-chrome-popup outline-none origin-[var(--transform-origin)] transition-[opacity,transform] duration-100 data-[starting-style]:scale-95 data-[starting-style]:opacity-0 data-[ending-style]:opacity-0",XIA="flex h-7 cursor-default select-none items-center gap-2 rounded-[8px] px-2.5 outline-none data-[highlighted]:bg-chrome-hover data-[popup-open]:bg-chrome-hover data-[disabled]:opacity-40";function zIA({trigger:A,children:e,side:t="bottom",align:n="start",className:o,tip:i,open:r,onOpenChange:a,sideOffset:c=6,mark:l,popupBase:u=VIA}){const C=d.jsx(HB,{render:A});return d.jsxs(JB,{open:r,onOpenChange:a?B=>a(B):void 0,children:[i?d.jsx(lr,{label:i.label,shortcut:i.shortcut,side:i.side??(t==="top"?"top":"bottom"),children:C}):C,d.jsx(TM,{children:d.jsx(HM,{side:t,align:n,sideOffset:c,className:"z-[1000]",children:d.jsx(KM,{...PIA(l),className:ye(u,o),children:e})})})]})}function ZIA({children:A,onSelect:e,shortcut:t,checked:n,disabled:o,danger:i,icon:r,title:a,description:c,closeOnClick:l}){return d.jsxs(h8,{className:ye(XIA,c!==void 0&&"h-auto min-h-7 items-start py-1.5",i&&"text-danger data-[highlighted]:bg-danger data-[highlighted]:text-white"),disabled:o,onClick:e,closeOnClick:l,title:a,children:[n!==void 0?d.jsx("span",{className:"flex size-4 shrink-0 items-center justify-center",children:n?d.jsx(lu,{className:"size-4 text-chrome-accent",strokeWidth:2.25}):null}):null,r?d.jsx("span",{"data-chrome-icon":"",className:"flex size-4 shrink-0 items-center justify-center text-chrome-muted",children:r}):null,c!==void 0?d.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[d.jsx("span",{className:"truncate",children:A}),d.jsx("span",{className:"truncate text-[12px] leading-4 text-chrome-muted",children:c})]}):d.jsx("span",{className:"min-w-0 flex-1 truncate",children:A}),t?d.jsx("span",{className:"ml-6 max-w-40 shrink-0 truncate text-[13px] text-chrome-muted",children:t}):null]})}function Dg(){return typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/.test(navigator.platform||navigator.userAgent)}const pl=Dg()?"⌘":"Ctrl+",$IA=pl==="⌘"?"⇧":"Shift+";function ACA(A){let e=!1;A.setCanRestore(A.roleMayRestore),A.report({history:!0});const t=()=>{A.history.list().then(o=>{e||A.setCanRestore(o.canRestore&&A.roleMayRestore)},()=>{})};t();const n=[A.history.onChange(t),A.onCommand(o=>{o.cmd==="history"&&A.toggle()})];return()=>{e=!0;for(const o of n)o();A.report({history:void 0})}}async function eCA(A,e,t,n=12){const o=t(Object.keys(await A.files(e))),i=[];let r=0;const a=async()=>{for(;r<o.length;){const c=o[r++],l=await A.read(e,c).catch(()=>null);l!==null&&i.push([c,l])}};return await Promise.all(Array.from({length:Math.min(n,o.length)},a)),i}const tCA="1.3.0";class ZC extends Error{code;paths;retryable;constructor(e,t,n,o){super(t),this.name="ArtifactError",this.code=e,n&&(this.paths=n),o&&(this.retryable=!0)}}function nCA(A){return A==="owner"||A==="editor"}const DI={maxDocumentBytes:262144,maxDepth:32},DU={defaultMs:12e4,maxMs:6e5};function oCA(A,e={}){const t=e.timeoutMs??1e4,n=new Map;return Object.freeze({version:tCA,use:i=>{const r=n.get(i);if(r)return r;const a=new Promise(c=>{const l=setTimeout(()=>c(null),t);Promise.resolve().then(()=>A.get(i)).then(u=>{clearTimeout(l),c(u?Object.freeze(u):null)},()=>{clearTimeout(l),c(null)})});return n.set(i,a),a}})}function iCA(A,e){const t=globalThis.window?.openartifact;if(t)return t;const n=oCA(A,e);return Object.defineProperty(window,"openartifact",{value:n,configurable:!1,enumerable:!0,writable:!1}),n}const it={session:"_api/session",files:"_api/files",file:"_api/file",publish:"_api/publish",assets:"_api/assets",events:"_api/events",agentSend:"_api/agent/send",presence:"_api/presence",peers:"_api/peers",downloads:"_api/downloads",roomEmit:"_api/room/emit",dbGet:"_api/db/get",dbList:"_api/db/list",dbWrite:"_api/db/write",comments:"_api/comments",commentsCreate:"_api/comments/create",commentsReply:"_api/comments/reply",commentsResolve:"_api/comments/resolve",commentsMove:"_api/comments/move",commentsRemove:"_api/comments/remove",commentsSend:"_api/comments/send",history:"_api/history",historyFiles:"_api/history/files",historyFile:"_api/history/file",historyDiff:"_api/history/diff",historyRestore:"_api/history/restore",historyDismiss:"_api/history/dismiss",mcpTools:"_api/mcp/tools",mcpCall:"_api/mcp/call"};function sCA(A,e,t){return e===401||e===403?"removed":e<200||e>=300||!t||t.id===A.id&&t.role===A.role?null:"changed"}async function yU(A){let e={};try{e=await A.json()}catch{}const t=A.status===409?"conflict":A.status===403?"not_writer":A.status===404?"not_found":"unavailable";return new ZC(e.code??t,e.message??`HTTP ${A.status}`,e.paths,e.retryable===!0)}function rCA(){const A=new Uint8Array(8);return crypto.getRandomValues(A),Array.from(A,e=>e.toString(16).padStart(2,"0")).join("")}function nP(A={}){const e=new URL(A.base??"./",location.href),t=rCA(),n=(G,U)=>{const L=new URL(G,e);for(const[K,H]of Object.entries(U??{}))L.searchParams.set(K,H);return L.toString()},o=async(G,U,L)=>{let K;try{K=await fetch(n(G,L),U)}catch(H){throw new ZC("unavailable",H instanceof Error?H.message:String(H))}if(!K.ok)throw await yU(K);return await K.json()},i=(G,U)=>o(G,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(U)}),r=new Map,a=(G,U)=>{for(const L of r.get(G)??[])L(U)},c=(G,U)=>{let L=r.get(G);return L||(L=new Set,r.set(G,L),C?.addEventListener(G,Q)),L.add(U),m(),()=>L.delete(U)};let l=null,u=!1,C=null,B=null;const Q=G=>{a(G.type,JSON.parse(G.data))},f=()=>{const G=new EventSource(n(it.events,{client:t}));C=G;for(const U of r.keys())G.addEventListener(U,Q);G.onerror=()=>{D().then(U=>{U||G.readyState!==EventSource.CLOSED||C!==G||(C=null,B=setTimeout(()=>{B=null,m()},2e3))})}};let w=!1,p=!1;const h=G=>{w||(w=!0,B&&clearTimeout(B),B=null,C?.close(),C=null,l?.close(),l=null,A.onAccessChange?A.onAccessChange(G):location.reload())},D=async()=>{if(w)return!0;if(!y||p)return!1;p=!0;try{const G=(await y.catch(()=>null))?.viewer;if(!G)return!1;let U;try{U=await fetch(n(it.session),{cache:"no-store"})}catch{return!1}const L=U.ok?(await U.json().catch(()=>null))?.viewer:null,K=sCA(G,U.status,L);return K&&h(K),K!==null}finally{p=!1}};function m(){if(l||C||B||w)return;if(typeof WebSocket>"u")return f();const G=new URL(n(it.events,{client:t}));G.protocol=G.protocol==="https:"?"wss:":"ws:";const U=new WebSocket(G);l=U,U.onopen=()=>{u=!0},U.onmessage=L=>{let K;try{K=JSON.parse(String(L.data))}catch{return}K.event&&a(K.event,K.data)},U.onclose=()=>{if(l===U&&(l=null),!w){if(!u)return f();D().then(L=>{L||l||C||B||(B=setTimeout(()=>{B=null,m()},2e3))})}}}let y=null;const R=()=>y??=o(it.session),M={async artifact(){const{artifact:G}=await R();return{id:G.id,title:async()=>(await o(it.session)).artifact.title,list:async()=>(await o(it.files)).files,readText:async L=>new TextDecoder().decode(await k(L)),readBytes:L=>k(L),publish:async L=>{const K={files:L,client:t};return o(it.publish,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(K)})},onChange:L=>c("files",L)}},async assets(){const{viewer:G}=await R();return nCA(G.role)?{upload:async(L,K)=>o(it.assets,{method:"POST",headers:{"content-type":L.type||"application/octet-stream"},body:L},K?.name?{name:K.name}:void 0)}:null},async user(){const{viewer:G}=await R();return{me:async()=>G}},async agent(){return{send:async(U,L)=>{const K={request:U,deliver:L?.deliver??"send"};return o(it.agentSend,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(K)})},status:async()=>(await o(it.session)).agent,onStatus:U=>c("agent",U)}},async room(){return{self:async()=>t,presence:async U=>{const L={client:t,patch:U};await o(it.presence,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(L)})},peers:async()=>(await o(it.peers)).peers,onPeers:U=>c("peers",U),emit:async(U,L)=>{const K={client:t,topic:U,data:L};await i(it.roomEmit,K)},onMessage:U=>c("room",U)}},async db(){const{stores:G}=await R();return G?.db?{get:async L=>(await o(it.dbGet,{cache:"no-store"},{path:L})).data,list:async L=>(await o(it.dbList,{cache:"no-store"},{collection:L})).documents,write:async L=>{const K={writes:L,client:t};await i(it.dbWrite,K)},onChange:L=>c("db",L)}:null},async comments(){const{stores:G}=await R();if(!G?.comments)return null;const U=async(K,H)=>(await i(K,H)).thread;return{list:async()=>(await o(it.comments,{cache:"no-store"})).threads,create:K=>U(it.commentsCreate,{input:K}),reply:(K,H)=>U(it.commentsReply,{threadId:K,text:H}),setResolved:(K,H)=>U(it.commentsResolve,{threadId:K,resolved:H}),move:(K,H,x)=>U(it.commentsMove,{threadId:K,anchor:H,...x?{location:x}:{}}),remove:async(K,H)=>{await i(it.commentsRemove,{threadId:K,...H?{messageId:H}:{}})},sendToAgent:K=>U(it.commentsSend,{threadId:K}),onChange:K=>c("comments",K)}},async history(){const{stores:G}=await R();if(!G?.history)return null;const U=(K,H)=>({n:String(K),...H===void 0?{}:{path:H}});return{list:()=>o(it.history,{cache:"no-store"}),files:async K=>(await o(it.historyFiles,{cache:"no-store"},U(K))).files,read:async(K,H)=>new TextDecoder().decode(await F(it.historyFile,U(K,H))),readBytes:(K,H)=>F(it.historyFile,U(K,H)),diff:(K,H)=>o(it.historyDiff,{cache:"no-store"},U(K,H)),restore:(K,H)=>i(it.historyRestore,{n:K,...H?{paths:H}:{},client:t}),dismissNotice:async K=>{await i(it.historyDismiss,{id:K})},onChange:K=>c("history",K)}},async mcp(){const{viewer:G}=await R();return G.role!=="owner"?null:{callTool:async(L,K,H,x)=>{const Y=x?.signal;Y?.throwIfAborted();const v={server:L,tool:K,args:H,...x?.timeoutMs===void 0?{}:{timeoutMs:x.timeoutMs}};try{return await o(it.mcpCall,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(v),...Y?{signal:Y}:{}})}catch(T){throw Y?.aborted?Y.reason:T}},listTools:L=>o(it.mcpTools,{cache:"no-store"},L===void 0?void 0:{server:L})}},async downloads(){return{save:async({name:U,data:L})=>o(it.downloads,{method:"POST",headers:{"content-type":L.type||"application/octet-stream"},body:L},{name:U})}}};function k(G){return F(it.file,{path:G})}async function F(G,U){let L;try{L=await fetch(n(G,U),{cache:"no-store"})}catch(K){throw new ZC("unavailable",K instanceof Error?K.message:String(K))}if(!L.ok)throw await yU(L);return new Uint8Array(await L.arrayBuffer())}return{get(G){const U=M[G];return U?U():null}}}const aCA="[Artifact comment sent to agent]",gCA="[Artifact edit request sent to agent]",cCA="[Artifact task finished]",lCA=1,uCA=1,ICA=/^[a-z][a-z0-9]{0,23}$/,CCA="may not have run: the artifact was updated before this call was answered",BCA=["quickstart","list","publish","read","open","call","adopt","delete","share"],ECA=["get","list","query","set","update","delete","str_replace","batch"],QCA=["read","reply","resolve","reopen","wait"],fCA=["share","export"],dCA={type:"object",properties:{action:{type:"string",enum:BCA,description:"What to do. Omitted: publish."},intent:{type:"string",description:"quickstart: what is being made (design, design-system, slides, whiteboard, document, data, other), or a few words about it."},scope:{type:"string",enum:["types","mine","all"],description:"list: the installed types, this session's and this workspace's artifacts (default), or every artifact."},type:{type:"string",description:"list: only artifacts of this type (an id, or open-artifact://type/<id>)."},query:{type:"string",description:"list: only artifacts whose title contains this text."},limit:{type:"integer",description:"list: how many to return (default 50, at most 200)."},cursor:{type:"string",description:"list: the next_cursor of the previous page."},type_url:{type:"string",description:"publish without url: the type to create from (open-artifact://type/<id>, from quickstart). read without url: the type to describe."},title:{type:"string",description:"publish without url: the new artifact's name."},folder:{type:"string",description:"publish without url, or adopt: where the artifact's folder goes (absolute, or relative to the workspace). Default <workspace>/artifacts/<slug>."},url:{type:"string",description:"An artifact: open-artifact://artifact/<id>, as publish returned it."},files:{type:"object",additionalProperties:!0,description:'publish with url: files to write under the artifact root, as {"rel/path": "text"} or {"rel/path": {"content": "...", "encoding": "base64"}}; null deletes.'},if_match:{type:"object",additionalProperties:!0,description:'publish with url: {"rel/path": sha256 | null | "*"}. Write only while the file still has the sha256 you read, does not exist (null), or anyway ("*"). One mismatch writes nothing and returns the current versions.'},check:{type:"boolean",description:"publish with url: run the type's check action after writing; its result comes back as check."},open:{type:"string",enum:["after_first_write","now"],description:"publish without url: after_first_write opens the page in your app once your first write lands; now opens it at once. Where your app cannot show pages by itself the result says so: open view_url in your app's built-in browser, if you have one."},related:{type:"boolean",description:"quickstart: list existing artifacts the recommended type can build on, such as design systems (default true)."},path:{type:"string",description:"read: one file or folder under the root (omitted: the record and the file list)."},paths:{type:"array",items:{type:"string"},description:"read: several files under the root at once."},name:{type:"string",description:"call: the action's name (check, upload, ...; read with url lists them)."},args:{type:"object",additionalProperties:!0,description:"call: the action's arguments. upload: {file: absolute path, name?, group?}."},panel:{type:"string",enum:fCA,description:"open: also open the page's Share panel (share), for the person to share it on the network, or its Export tab (export), for them to download a file."}}},hCA={type:"object",properties:{action:{type:"string",enum:ECA},url:{type:"string",description:"The artifact (open-artifact://artifact/<id>)."},collection:{type:"string"},doc_id:{type:"string"},path:{type:"string",description:"collection/doc_id, instead of the two."},data:{type:"object",additionalProperties:!0,description:"set / update: the document's fields."},file_path:{type:"string",description:"set / update: a JSON file holding the fields, instead of data."},if_match:{description:'set / update / delete / str_replace: the sha256 get returned (write only if unchanged), null (only if it does not exist) or "*" (replace whatever is there).'},field:{type:"string",description:"str_replace: the text field, as a dot path (body, notes.text)."},old:{type:"string",description:"str_replace: the passage to replace; it must occur exactly once."},new:{type:"string",description:"str_replace: the passage that replaces it."},where:{type:"array",items:{type:"object",additionalProperties:!0},description:"query: [{field, op, value}], all must hold. op: ==, !=, <, <=, >, >=, in, not-in (up to 30 values), array-contains."},order_by:{type:"object",additionalProperties:!0,description:'query: {field, dir: "asc" | "desc"}.'},limit:{type:"integer",description:"list / query: how many documents (default 100, at most 1000)."},cursor:{type:"string",description:"list / query: the next_cursor of the previous page."},out_file:{type:"string",description:"get / list / query: write the result to this JSON file (absolute, or relative to the workspace) and return only its path and counts."},writes:{type:"array",items:{type:"object",additionalProperties:!0},description:"batch: [{op: set|update|delete|str_replace, path | collection+doc_id, data | file_path, if_match?, field?, old?, new?}], at most 500."}},required:["action","url"]},wCA={type:"object",properties:{action:{type:"string",enum:QCA},url:{type:"string",description:"The artifact (open-artifact://artifact/<id>). wait: optional."},thread_id:{type:"string",description:'reply / resolve / reopen: the thread (after ";thread=" in the message).'},text:{type:"string",description:"reply: the answer."},resolve:{type:"boolean",description:"reply: resolve the thread too."},all:{type:"boolean",description:"read: resolved threads too."},since:{type:"string",description:"read: only threads with a message at or after this time (ISO 8601)."},acknowledge_duplicate:{type:"boolean",description:"reply: send the same text as your last reply in this thread again, on purpose."},timeout_ms:{type:"number",description:"wait: how long (default 600000)."}},required:["action"]},mU={Artifact:dCA,ArtifactData:hCA,ArtifactComments:wCA},pCA={Artifact:["Make and change artifacts: typed folders of files that open as live pages the person can view, edit, comment on and export. Actions:","- quickstart {intent}: call first for a new artifact; recommends a type and returns the call that creates it.",'- list {scope: "mine" | "all" | "types", type?, query?}: find existing artifacts, or the installed types.',"- publish {type_url, title, folder?, open?}: create an artifact; the result carries its root folder and the type's instructions. publish {url, files, if_match?, check?}: write files when you have no file tools of your own.","- read {url, path? | paths?}: the artifact's record, files and actions, or some of its files with their sha256. read {type_url}: a type's instructions, before creating.",`- open {url, panel?}: show it to the person in the computer's browser (or the app, when it shows pages), once its content is written. When your app has a built-in browser, open view_url there instead. panel "share" or "export" opens its Share panel or Export tab for them.`,"- call {url, name, args?}: run one of the type's actions (check, upload, ...). A long one answers {task, pending: true}; its result comes later as a message.","- adopt {url | folder}: take over an artifact, or add an existing folder. Only when the person asks.","- share {url}: whether it is shared on the local network, and its links. Only the person changes that, in the page's Share panel.","- delete {url}: forget an artifact; its folder stays. Only when the person asks."].join(`
36
36
  `),ArtifactData:'Read and write the document store of an artifact whose type keeps one (its instructions say so). get, list and query read documents with their sha256; set, update, delete, str_replace and batch write them. update merges fields, and {"__delete__": true} removes one; str_replace changes one passage of a long text field. Replacing or deleting an existing document needs if_match: the sha256 you read, or "*". Your writes show live on open pages.',ArtifactComments:`Comments the person leaves on their artifact's page, kept in the artifact's own folder on this computer (no outside service). read lists the threads; reply answers one (thread_id is after ";thread=" in the message), with resolve: true when it is done; resolve and reopen change a thread's state. A thread sent to you is the person asking for your answer in it, so replying there is what they asked for. Answer only threads sent to you, in one or two lines. wait blocks until the next message for this session: use it only when nothing else can wake you.`},DCA={Artifact:{title:"Artifact",openWorldHint:!1},ArtifactData:{title:"Artifact data",openWorldHint:!1},ArtifactComments:{title:"Artifact comments",destructiveHint:!1,openWorldHint:!1}};Object.keys(mU).map(A=>({name:A,description:pCA[A],inputSchema:mU[A],annotations:DCA[A]}));const yCA=300,mCA=12,SU=["Artifact","ArtifactData","ArtifactComments"];function Ia(A,e=yCA){const t=String(A??"").replace(/[<>]/g,"").replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1).trimEnd()}…`:t}function SCA(A){const e=Ia(A,Number.MAX_SAFE_INTEGER),t=e.search(/[.!?。!?](\s|$)/);return t>=0?e.slice(0,t+1):e}function NCA(A){const e=Ia(A,24);return/^[a-z0-9]{1,5}$/i.test(e)?e.toUpperCase():e}const NU=A=>!A||/[.!?。!?…]$/.test(A)?A:`${A}.`;function bCA(A,e=!1){const t=Ia(A.title,80)||A.id;if(e)return`- ${A.id}: ${t}`;const n=Ia(A.when)||Ia(SCA(A.description)),o=(A.exports??[]).map(NCA).filter(Boolean),i=[NU(t),NU(n),o.length?`Exports: ${o.join(", ")}.`:""].filter(Boolean);return`- ${A.id}: ${i.join(" ")}`}const RCA="Open Artifact lets you make artifacts: typed folders of files (a slide deck, a design canvas, a whiteboard, a data dashboard and more) that open as live pages the person can view, edit, comment on and export. You make and change them with the Artifact, ArtifactData and ArtifactComments tools.",MCA=`<where_output_goes>
37
37
  Decide where your output will live before you make anything.
38
38
  - Something the person will read once and move on from (an answer, an explanation, a summary, a short report) goes in your reply, however long it is. A diagram or chart that explains your answer goes in the reply too, when you can show one there.
@@ -4,7 +4,7 @@
4
4
  <meta charset="utf-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
6
6
  <title>Data</title>
7
- <script type="module" crossorigin src="./assets/index-CZiM2XTm.js"></script>
7
+ <script type="module" crossorigin src="./assets/index-B041Zu27.js"></script>
8
8
  <link rel="stylesheet" crossorigin href="./assets/index-BdzD_T3_.css">
9
9
  </head>
10
10
  <body>
@@ -31,7 +31,7 @@ ${n}
31
31
  `};const n=A.text.match(/^\s*/)?.[0].length??0;return{start:n,end:n,text:`<helmet>
32
32
  ${e.trim()}
33
33
  </helmet>
34
- `}}function fK(A,e){if(e.kind==="source")return{source:e.text,created:[]};const t=So(A);if(e.kind==="props"){if(!t.script||!t.props)return null;const c={...t.props};for(const[I,B]of Object.entries(e.values)){const u=c[I];!u||I==="$preview"||!("editor"in u)||(c[I]={...u,default:B})}return{source:V8(t,c),created:[]}}if(e.kind==="scriptText"){if(!t.script)return null;const c=t.script.body.text,I=ey(c),B=I.filter(E=>E.value===e.value),u=I.find(E=>E.start===e.start&&E.end===e.end&&E.value===e.value)??(B.length===1?B[0]:void 0);if(!u)return null;const Q=c.slice(0,u.start)+hP(e.text,u.quote)+c.slice(u.end);return Q===c?null:{source:P8(t,Q),created:[]}}if(!t.template)return null;const n=jg(t.template.text);let o;try{switch(e.kind){case"style":{const c=Ts(n,e.targets);if(!c)return null;o=c.flatMap(I=>Fh(n,I,e.patch));break}case"styles":{const c=Ts(n,e.edits.map(I=>I.target));if(!c)return null;o=c.flatMap((I,B)=>Fh(n,I,e.edits[B].patch));break}case"attr":{const c=nt(n,e.target.tid,e.target.path);if(!c)return null;o=vh(n,c,e.name,e.value);break}case"text":{const c=nt(n,e.target.tid,e.target.path);if(!c)return null;o=MP(c,e.text);break}case"richText":{const c=nt(n,e.target.tid,e.target.path);if(!c||!na(c))return null;const I=dP(e.html);if(o=[{start:c.openEnd,end:c.closeStart,text:I}],c.tag==="p"&&QP(I)){const B=c.start+1;o.push({start:B,end:B+c.rawTag.length,text:"div"});const u=c.closeStart+2;o.push({start:u,end:u+c.rawTag.length,text:"div"})}break}case"wrapText":{const c=nt(n,e.target.tid,e.target.path);if(!c)return null;const I=aK(c,n.text,e.inline);if(!I.length)return null;o=I.flatMap(B=>[{start:B.start,end:B.start,text:"<span>"},{start:B.end,end:B.end,text:"</span>"}]);break}case"importText":{const c=nt(n,e.target.tid,e.target.path);if(!c||c.tag!=="x-import")return null;const I=lK(e,e.text,IK(c,dK(A)));if(I.kind!=="commit")return null;o=I.key==="__text"?xP(c,Hg(I.text)):vh(n,c,I.key.slice(1),I.text);break}case"linkText":{const c=nt(n,e.target.tid,e.target.path);if(!c||c.closeStart<=c.openEnd||c.tag==="a")return null;o=[{start:c.openEnd,end:c.openEnd,text:`<a ${uK("href",e.href)}>`},{start:c.closeStart,end:c.closeStart,text:"</a>"}];break}case"remove":{const c=Ts(n,e.targets);if(!c)return null;o=BK(n,c);break}case"duplicate":{const c=Ts(n,e.targets);if(!c)return null;o=NP(n,c);break}case"insert":{const c=e.target?nt(n,e.target.tid,e.target.path):null;if(e.target&&!c)return null;o=Qu(n,c,e.position,e.html),e.helmet&&o.push(hk(n,e.helmet));break}case"move":{const c=Ts(n,e.targets),I=nt(n,e.target.tid,e.target.path);if(!c||!I)return null;o=GP(n,c,I,e.position);break}case"wrap":{const c=Ts(n,e.targets);if(!c||c.length===0)return null;o=RP(n,c,e.open,e.close);break}case"unwrap":{const c=nt(n,e.target.tid,e.target.path);if(!c)return null;o=vP(n,c);break}case"replace":{const c=Ts(n,e.edits.map(I=>I.target));if(!c||!c.length)return null;o=c.map((I,B)=>({start:I.start,end:I.end,text:e.edits[B].html})),e.helmet&&o.push(hk(n,e.helmet));break}}}catch{return null}const s=CK(n.text,o),g=jg(s);let a=e.kind==="style"||e.kind==="styles"||e.kind==="attr"||e.kind==="text"||e.kind==="importText"?[]:LP(g,YP(o)).filter(c=>!JP(g.elements[c.tid]));if(e.kind==="richText"){const c=nt(n,e.target.tid,e.target.path),I=c?g.elements.find(E=>E.start===c.start):void 0,B=[],u=E=>{for(const f of pe(E.children))f.tag==="a"&&B.push(f),u(f)};I&&e.link!=null&&u(I);const Q=e.link!=null?B[e.link]:void 0;a=Q?[EK(g,Q)]:[]}return{source:q8(t,s),created:a}}function TP(A,e){let t=A;const n=[];for(const o of e){const s=fK(t,o);s&&(t=s.source,n.push(o))}return{source:t,kept:n,dropped:e.length-n.length}}const pk=A=>{if(A===null)return{canvas:uu(),error:null};try{return{canvas:YB(JSON.parse(A)),error:null}}catch(e){return{canvas:uu(),error:e instanceof Error?e.message:String(e)}}},_i=(A,e)=>[...A.slice(-199),e],iA=Wn()((A,e)=>({status:"loading",error:null,title:"",readOnly:!1,canvas:uu(),canvasSaved:uu(),canvasHash:null,canvasError:null,boards:{},trash:[],undo:[],redo:[],edits:0,save:"saved",revision:0,gesture:null,load({title:t,readOnly:n,canvas:o,boards:s}){const g=pk(o.text),a={};for(const[c,I]of Object.entries(s))a[c]={source:I.text,saved:I.text,hash:I.hash,pending:[]};A({status:"ready",title:g.canvas.title||t,readOnly:n,canvas:g.canvas,canvasSaved:g.canvas,canvasHash:o.hash,canvasError:g.error,boards:a,save:n?"readonly":"saved"})},fail(t){A({status:"error",error:t})},editBoard(t,n,o={}){const s=e(),g=s.boards[t];if(s.readOnly||!g?.source)return null;const a=fK(g.source,n);if(!a||a.source===g.source)return a;const c={source:a.source,pending:[...g.pending,n]},I=s.undo[s.undo.length-1],B=o.coalesce&&I?.scope==="board"&&I.path===t&&I.key===o.coalesce&&I.after.source===g.source,u=B?I.before:{source:g.source,pending:g.pending},Q={scope:"board",path:t,before:u,after:c,...o.coalesce?{key:o.coalesce}:{}};return A({boards:{...s.boards,[t]:{...g,...c}},undo:B?[...s.undo.slice(0,-1),Q]:_i(s.undo,Q),redo:[],edits:s.edits+1,revision:s.revision+1}),a},updateCanvas(t){const n=e();if(n.readOnly||n.canvasError)return;const o=t(n.canvas);o!==n.canvas&&A({canvas:o,...n.gesture?{}:{undo:_i(n.undo,{scope:"canvas",before:n.canvas,after:o}),redo:[]},revision:n.revision+1})},beginGesture(){e().gesture||A({gesture:e().canvas})},endGesture(){const{gesture:t,canvas:n,undo:o}=e();t&&A({gesture:null,...t!==n?{undo:_i(o,{scope:"canvas",before:t,after:n}),redo:[]}:{}})},createBoard(t,n,o){const s=e();if(s.readOnly)return;const g=s.boards[t],a={...s.canvas,boards:{...s.canvas.boards,[t]:o},order:[...s.canvas.order.filter(c=>c!==t),t]};A({boards:{...s.boards,[t]:{source:n,saved:g?.saved??null,hash:g?.hash??null,pending:[]}},canvas:a,trash:s.trash.filter(c=>c!==t),undo:_i(s.undo,{scope:"canvas",before:s.canvas,after:a}),redo:[],edits:s.edits+1,revision:s.revision+1})},deleteBoards(t){const n=e();if(n.readOnly||t.length===0)return;const o={...n.canvas.boards};for(const g of t)delete o[g];const s={...n.canvas,boards:o,order:n.canvas.order.filter(g=>!t.includes(g))};A({canvas:s,trash:[...new Set([...n.trash,...t])],undo:_i(n.undo,{scope:"canvas",before:n.canvas,after:s}),redo:[],edits:n.edits+1,revision:n.revision+1})},undoLast(){const t=e(),n=t.undo[t.undo.length-1];if(!n||t.readOnly)return null;if(n.scope==="canvas"){const o=ZE(n.after,n.before,t.canvas);A({canvas:o,undo:t.undo.slice(0,-1),redo:_i(t.redo,n),revision:t.revision+1})}else{const o=t.boards[n.path];if(!o)return null;A({boards:{...t.boards,[n.path]:{...o,...n.before}},undo:t.undo.slice(0,-1),redo:_i(t.redo,n),revision:t.revision+1})}return n},redoLast(){const t=e(),n=t.redo[t.redo.length-1];if(!n||t.readOnly)return null;if(n.scope==="canvas"){const o=ZE(n.before,n.after,t.canvas);A({canvas:o,redo:t.redo.slice(0,-1),undo:_i(t.undo,n),revision:t.revision+1})}else{const o=t.boards[n.path];if(!o)return null;A({boards:{...t.boards,[n.path]:{...o,...n.after}},redo:t.redo.slice(0,-1),undo:_i(t.undo,n),revision:t.revision+1})}return n},remoteBoard(t,n,o){const s=e(),g=s.boards[t],a=I=>I.filter(B=>B.scope!=="board"||B.path!==t);if(n===null)return g&&A({boards:{...s.boards,[t]:{...g,saved:null,hash:null,...g.pending.length?{}:{source:null}}}}),0;const c=g?.pending.length?TP(n,g.pending):{source:n,kept:[],dropped:0};return A({boards:{...s.boards,[t]:{source:c.source,saved:n,hash:o,pending:c.kept}},undo:a(s.undo),redo:a(s.redo),...c.kept.length?{revision:s.revision+1}:{}}),c.dropped},remoteCanvas(t,n){const o=e(),s=pk(t);if(s.error){A({canvasError:s.error,canvasHash:n});return}const g=o.canvas!==o.canvasSaved,a=g?ZE(o.canvasSaved,o.canvas,s.canvas):s.canvas;A({canvas:a,canvasSaved:s.canvas,canvasHash:n,canvasError:null,title:s.canvas.title||o.title,...g?{revision:o.revision+1}:{}})},acknowledge(t,n){const o=e(),s={...o.boards};for(const[g,{source:a,pendingCount:c}]of Object.entries(t.boards)){const I=s[g];!I||!(g in n)||(s[g]={...I,saved:a,hash:n[g]??null,pending:I.pending.slice(c)})}for(const g of t.deleted){const a=s[g];a&&(s[g]={...a,saved:null,hash:null})}A({boards:s,trash:o.trash.filter(g=>!t.deleted.includes(g)),...t.canvas&&"canvas.json"in n?{canvasSaved:t.canvas.canvas,canvasHash:n["canvas.json"]??null}:{}})},setSave(t){e().save!==t&&A({save:t})},setTitle(t){A({title:t})}}));function Eu(A){return A.readOnly?!1:A.canvas!==A.canvasSaved||A.trash.some(e=>A.boards[e]?.hash)?!0:Object.entries(A.boards).some(([e,t])=>t.source!==null&&hK(A,e,t))}function hK(A,e,t){return t.source===null?!1:t.source!==t.saved?!0:t.hash===null&&e in A.canvas.boards}const ia=.01,dI=8,Tn={kind:"none"},HP=[1.5,3,5,8],pK="mc-toolbar/top";function OP(){try{return typeof localStorage<"u"&&localStorage.getItem(pK)==="1"}catch{return!1}}const eA=Wn()((A,e)=>({camera:{x:0,y:0,zoom:1},page:null,tool:"select",selection:Tn,hover:null,peek:null,textEdit:null,noteEdit:null,mode:"canvas",focused:null,panel:"properties",panelOpen:!1,frames:{},layoutTick:0,overrides:{},composer:!1,spacePan:!1,pen:{stroke:3,dash:"solid"},findOpen:!1,toolbarTop:OP(),crop:null,setCamera(t){const n=Math.min(dI,Math.max(ia,t.zoom));A({camera:{...t,zoom:n}})},setPage(t){e().page!==t&&A({page:t,selection:Tn,hover:null,peek:null,crop:null})},setTool(t){A({tool:t})},select(t){A({selection:t,noteEdit:null,...e().crop?{crop:null}:{}})},setHover(t){const n=e().hover;n?.board===t?.board&&n?.tid===t?.tid&&n?.instance===t?.instance||A({hover:t})},setPeek(t){e().peek!==t&&A({peek:t})},setTextEdit(t){A({textEdit:t})},patchTextEdit(t){const{textEdit:n}=e();n&&A({textEdit:{...n,...t}})},setNoteEdit(t){A({noteEdit:t})},focus(t){A(t?{mode:"focused",focused:t,hover:null}:{mode:"canvas",focused:null})},setPanel(t,n=!0){A({panel:t,panelOpen:n})},togglePanel(){A({panelOpen:!e().panelOpen})},frame(t,n){const o=e().frames,s=o[t]??{booted:!1,errors:[],size:null};A({frames:{...o,[t]:{...s,...n}},layoutTick:e().layoutTick+1})},dropFrame(t){const{[t]:n,...o}=e().frames;A({frames:o})},parkFrame(t){const n=e().frames[t];if(!n)return;const o=structuredClone(n.errors),s=n.size?structuredClone(n.size):null;A({frames:{...e().frames,[t]:{booted:!1,errors:o,size:s}}})},tick(){A({layoutTick:e().layoutTick+1})},setOverride(t,n,o){const s=e().overrides;A({overrides:{...s,[t]:{...s[t]??{},[n]:o}}})},clearOverrides(t){const{[t]:n,...o}=e().overrides;A({overrides:o})},setComposer(t){A({composer:t})},setPen(t){A({pen:{...e().pen,...t}})},setSpacePan(t){e().spacePan!==t&&A({spacePan:t})},setFindOpen(t){e().findOpen!==t&&A({findOpen:t})},setToolbarTop(t){try{localStorage.setItem(pK,t?"1":"0")}catch{}A({toolbarTop:t})},setCrop(t){A({crop:t})}}));function cc(A,e,t){return{x:(e-A.x)/A.zoom,y:(t-A.y)/A.zoom}}const jP=4e3;function qP(A){return A.wakesIdle===!1?`${A.name} gets this on its next turn: send it a message to start one`:"Waiting for the agent"}function PP(A,e){return e===!1?{title:`Sent to ${A}`,description:`${A} gets it on its next turn. If it is idle, send it a message there to start one.`}:{title:`Sent to ${A}`}}function wK(A){return A.reduce((e,t)=>t.status==="open"?e+t.messages.length:e,0)}function zP(A){return A==="detached"?"What this was on is gone; shown on what held it.":A==="orphaned"?"What this was on has been deleted.":null}function VP(A){const e=A.maxThreads??500,t=A.noun??"document",n=D=>A.notify?.(D);let o=null,s,g=0;const a=Wn()(D=>({available:!1,threads:[],on:!1,listOpen:!1,active:null,draft:null,showResolved:!1,sendNew:!1,draftText:"",replies:{},setOn(M){D({on:M,draft:null}),A.onModeChange?.(M)},setListOpen(M){D({listOpen:M})},setActive(M){D({active:M,draft:null})},setDraft(M){D(M===null?{draft:M,active:null,draftText:"",sendNew:!1}:{draft:M,active:null})},setShowResolved(M){D({showResolved:M})},setSendNew(M){D({sendNew:M})},setDraftText(M){D({draftText:M})},setReply(M,y){D(S=>({replies:{...S.replies,[M]:y}}))}})),c=new Map,I=D=>{let M=c.get(D.anchor);return M===void 0&&(M=A.parse(D.anchor),c.size>2e3&&c.clear(),c.set(D.anchor,M)),M},B=D=>{n({title:"The comment could not be saved",description:D instanceof Error?D.message:String(D)})},u=D=>{a.setState(M=>({threads:M.threads.map(y=>y.id===D.id?D:y)})),A.heard?.([D])},Q=D=>A.checkText?A.checkText(D):D.trim().slice(0,jP)||void 0,E=()=>!!o&&A.canComment(),f=()=>!!o&&A.canSendToAgent(),w={store:a,adapter:A,async start(D,M){if(!D)return;o=D;const y=g;a.setState({available:!0});try{const x=await D.list();if(y!==g)return;a.setState({threads:x}),A.heard?.(x)}catch{}if(y!==g)return;s=D.onChange(x=>{const k=a.getState().active;a.setState({threads:x,active:k&&x.some(G=>G.id===k)?k:null}),A.heard?.(x)});const S=M?a.getState().threads.find(x=>x.id===M):void 0;S&&w.reveal(S)},stop(){g+=1,s?.(),s=void 0},capability:()=>o,canComment:E,canSendToAgent:f,canRemove:()=>!!o&&(A.canRemove?A.canRemove():A.canComment()),anchorOf:I,labelOf:D=>A.label(D),stateOf:D=>A.state?.(D)??"ok",stateNote:D=>A.stateNote?A.stateNote(D??"ok"):zP(D),async create(D,M,y){if(!o)return!1;const S=Q(M);if(!S)return!1;if(a.getState().threads.length>=e)return n({title:`This ${t} already has ${e} comments`}),!1;try{const x=A.detail?.(D),k=await o.create({anchor:A.serialize(D),label:A.label(D),...x!==void 0?{detail:x}:{},location:A.location?.(D)??{},text:S});return a.setState(G=>({threads:G.threads.some(N=>N.id===k.id)?G.threads:[...G.threads,k],draft:null,draftText:"",sendNew:!1,active:k.id})),A.heard?.([k]),y?.send&&f()&&await w.sendToAgent(k.id),!0}catch(x){return B(x),!1}},async reply(D,M,y){if(!o)return!1;const S=Q(M);if(!S)return!1;try{let x=await o.reply(D,S);return x.status==="resolved"&&(x=await o.setResolved(D,!1)),u(x),a.setState(k=>{const{[D]:G,...N}=k.replies;return{replies:N}}),y?.send&&f()&&await w.sendToAgent(D),!0}catch(x){return B(x),!1}},async resolve(D,M){if(o)try{u(await o.setResolved(D,M));const y=a.getState();M&&y.active===D&&!y.showResolved&&a.setState({active:null})}catch(y){B(y)}},async remove(D,M){if(!(!o||A.canRemove&&!A.canRemove()))try{await o.remove(D,M),M||a.setState(y=>({threads:y.threads.filter(S=>S.id!==D),active:y.active===D?null:y.active}))}catch(y){B(y)}},async move(D,M){if(o)try{u(await o.move(D,A.serialize(M),A.location?.(M)))}catch(y){B(y)}},async sendToAgent(D){if(!o||!f())return!1;const M=A.sendToAgent?a.getState().threads.find(y=>y.id===D):void 0;if(A.sendToAgent)return M?A.sendToAgent(M,I(M)):!1;try{return u(await o.sendToAgent(D)),n(PP(A.agentName?.()||"the agent",A.agentWakesIdle?.())),!0}catch(y){return B(y),!1}},async sendAllToAgent(){const D=a.getState().threads.filter(M=>w.canSendThread(M));for(const M of D)await w.sendToAgent(M.id)},canSendThread(D){if(D.status!=="open")return!1;const M=D.messages.at(-1);return!M||M.author.kind!=="person"?!1:!D.agent||D.agent.status==="replied"},reveal(D){A.reveal?.(I(D)),a.getState().setActive(D.id)},show(D){const M=a.getState();M.on||M.setOn(!0),D.status==="resolved"&&!a.getState().showResolved&&a.getState().setShowResolved(!0),w.reveal(D)},viewerName:()=>A.viewerName?.()||"You"};return w}const XE=A=>A instanceof Error?A.message:String(A);function ZP(A){const e=A.noun??"document",t=a=>A.notify?.(a);let n=null,o=0;const s=Wn()(a=>({available:!1,open:!1,previewing:null,preview:null,loading:!1,error:null,canRestore:!1,setOpen(c){a(c?{open:c}:{open:c,previewing:null,preview:null,error:null,loading:!1})}})),g={store:s,start(a){if(n=a,!a)return;s.setState({available:!0});const c=()=>{a.list().then(I=>s.setState({canRestore:I.canRestore}),()=>{})};c(),a.onChange(c)},capability:()=>n,toggle(a){const c=s.getState();c.available&&c.setOpen(a??!c.open)},async preview(a){const c=++o;if(a===null||!n){s.setState({previewing:null,preview:null,loading:!1,error:null});return}s.setState({previewing:a,loading:!0,error:null});try{const I=await A.loadPreview(n,a);c===o&&s.setState({preview:I,loading:!1})}catch(I){c===o&&s.setState({loading:!1,error:XE(I)})}},async restore(a){if(n)try{const c=await n.restore(a);t({title:c.changed.length?`Restored version ${a}`:`The ${e} already matches version ${a}`}),await g.preview(null)}catch(c){t({title:"The version could not be restored",description:XE(c)})}},async restorePaths(a,c,I){if(!n)return null;try{return(await n.restore(a,c)).changed}catch(B){return t({title:`${I} could not be restored`,description:XE(B)}),null}}};return g}const wk=["#e5484d","#0091ff","#30a46c","#f76b15","#8e4ec6","#d6409f","#12a594","#ad7f58"],ty="#6e56cf",yk=8e3,WP=80,Kg=50;function _P(A){let e=0;for(let t=0;t<A.length;t++)e=e*31+A.charCodeAt(t)|0;return wk[Math.abs(e)%wk.length]}const to={str:(A,e=512)=>typeof A=="string"&&A.length<=e?A:null,num:A=>typeof A=="number"&&Number.isFinite(A)?A:null,strList:(A,e=Kg)=>Array.isArray(A)?A.map(t=>to.str(t)).filter(t=>t!==null).slice(0,e):[],point:A=>{if(!A||typeof A!="object")return null;const e=A,t=to.num(e.x),n=to.num(e.y);return t!==null&&n!==null?{x:t,y:n}:null}};function XP(A,e,t,n){return A.filter(o=>o.id!==e).map(o=>{const s=o.state?.[t],g=s&&typeof s=="object"&&!Array.isArray(s)?s:null;return{id:o.id,name:(o.name||(o.kind==="agent"?"Agent":"Guest")).slice(0,60),kind:o.kind,color:o.kind==="agent"?ty:_P(o.id),cursor:g?to.point(g.cursor):null,state:g?n(g):null}}).sort((o,s)=>o.kind===s.kind?o.name.localeCompare(s.name):o.kind==="person"?-1:1)}function $P(A){const e=Wn()(()=>({available:!1,peers:[],agentWrote:null}));async function t({room:n,artifact:o}){const s=[];let g=null;if(o&&(s.push(o.onChange(y=>{if(y.author!=="agent")return;const S=Object.keys(y.changes).map(G=>A.wrotePath?A.wrotePath(G):G).filter(G=>G!==null),x=e.getState().agentWrote,k=x&&Date.now()-x.at<yk?x.paths:[];e.setState({agentWrote:{at:Date.now(),paths:[...new Set([...k,...S])].slice(0,Kg)}}),g&&clearTimeout(g),g=setTimeout(()=>e.setState({agentWrote:null}),yk)})),s.push(()=>{g&&clearTimeout(g)})),!n)return()=>s.forEach(y=>y());e.setState({available:!0});const a=await n.self().catch(()=>null),c=A.pointer?.bind(A),I=A.sendMs??WP;let B=null,u="",Q=null;const E=()=>{Q=null;const y=c?{...A.snapshot(),cursor:B}:A.snapshot(),S=JSON.stringify(y);S!==u&&(u=S,n.presence({[A.key]:y}).catch(()=>{}))},f=()=>{Q||(Q=setTimeout(E,I))};E(),s.push(A.watch(f));const h=y=>{const S=c?.(y)??null;if(!S){B&&(B=null,f());return}B={x:Math.round(S.x),y:Math.round(S.y)},f()},w=()=>{B=null,f()},D=()=>{document.visibilityState==="hidden"&&w()};c&&(window.addEventListener("pointermove",h,{passive:!0}),document.addEventListener("pointerleave",w),document.addEventListener("visibilitychange",D)),s.push(()=>{c&&(window.removeEventListener("pointermove",h),document.removeEventListener("pointerleave",w),document.removeEventListener("visibilitychange",D)),Q&&clearTimeout(Q),n.presence({[A.key]:null}).catch(()=>{})});const M=y=>{e.setState({peers:XP(y,a,A.key,A.parse)}),A.onPeers?.(y,a)};return n.peers().then(M,()=>{}),s.push(n.onPeers(M)),()=>s.forEach(y=>y())}return{store:e,start:t}}function Az(A,e){return e.available&&e.open?"history":null}function ez({comments:A,history:e,adapter:t}){const n=s=>{const g=A.store.getState(),a=s??!g.listOpen;g.setListOpen(a),a&&e.store.getState().open&&e.toggle(!1)},o=s=>{const g=s??!e.store.getState().open;e.toggle(g),g&&A.store.getState().setListOpen(!1)};return{chromeReport(){const s=A.store.getState(),g=e.store.getState();return{...s.available?{comments:{available:!0,on:s.on,open:s.listOpen,count:wK(s.threads),pageButton:t.pageButton??!1}}:{},...g.available?{history:!0}:{}}},subscribe(s){const g=A.store.subscribe(s),a=e.store.subscribe((c,I)=>{c.available!==I.available&&s()});return()=>{g(),a()}},handleCommand(s){switch(s.cmd){case"comments_mode":{const g=A.store.getState();if(!g.available)return!0;const a=s.on??!g.on;return a&&!t.onSurface()&&t.showSurface?.(),g.setOn(a),!0}case"comments_list":return n(s.open),!0;case"history":return o(),!0;case"action":return s.id==="comment_selection"&&t.commentOnSelection?(t.commentOnSelection(),!0):!1;default:return!1}},toggleCommentList:n,toggleHistoryPanel:o,useAside(){A.store(a=>a.available),A.store(a=>a.listOpen);const s=e.store(a=>a.available),g=e.store(a=>a.open);return Az({},{available:s,open:g})},runShortcut(s){if(e.store.getState().previewing!==null)return!0;const g=A.store.getState();if(!g.available)return!1;if(s.key==="Escape"){if(g.draft!==null)g.setDraft(null);else if(g.active)g.setActive(null);else if(g.on)g.setOn(!1);else return!1;return!0}return(s.code?.startsWith("Key")?s.code.slice(3).toLowerCase():s.key.toLowerCase())==="c"&&!s.meta&&!s.alt&&!s.shift?!A.canComment()||!t.onSurface()?!1:(g.setOn(!g.on),!0):!!(g.on&&!s.meta&&!t.readOnly()&&(s.key==="Delete"||s.key==="Backspace"))}}}function Dk(A,e){return{x:e.x*A.zoom+A.x,y:e.y*A.zoom+A.y}}function Ic(A,e){const t=A.zoom||1;return{x:(e.x-A.x)/t,y:(e.y-A.y)/t}}function yK(A,e){return{left:e.x*A.zoom+A.x,top:e.y*A.zoom+A.y,width:e.w*A.zoom,height:e.h*A.zoom}}const mk=200,Kh=Wn()(()=>({message:"",serial:0}));function tz(A){const e=A.replace(/\s+/g," ").trim();return e.length>mk?`${e.slice(0,mk-1)}…`:e}function st(A){const e=tz(A);e&&Kh.setState(t=>({message:e,serial:t.serial+1}))}function DK(A){const t=new URLSearchParams(A.replace(/^#/,"")).get("page");return t||null}function mK(A,e){const t=new URLSearchParams(A.replace(/^#/,""));e?t.set("page",e):t.delete("page");const n=t.toString();return n?`#${n}`:""}function nz(A,e){const t=new URL(A);return`${t.origin}${t.pathname}${mK(t.hash,e)}`}function iz(A){let e=!1;const t=(s,g)=>{const a=mK(location.hash,s);if(a===location.hash||!a&&!location.hash)return;const c=`${location.pathname}${location.search}${a}`;try{g?history.pushState(history.state,"",c):history.replaceState(history.state,"",c)}catch{}};t(A.current(),!1);const n=A.subscribe(s=>{e||t(s,!0)}),o=()=>{const s=DK(location.hash),g=s&&A.exists(s)?s:A.fallback();if(g!==A.current()){e=!0;try{A.show(g)}finally{e=!1}}};return window.addEventListener("popstate",o),()=>{n(),window.removeEventListener("popstate",o)}}const oz=4320*60*1e3;function sz(A,e){return e-A<=oz&&A<=e+6e4}function rz(A,e,t=()=>globalThis.localStorage){const n=()=>{try{t()?.removeItem(A)}catch{}};return{read(){try{const o=t()?.getItem(A);return o?e(JSON.parse(o)):null}catch{return null}},write(o){if(o===null)return n();try{t()?.setItem(A,JSON.stringify(o))}catch{}},clear:n}}function Sk(A){try{return JSON.stringify(Uh(JSON.parse(A)))}catch{return A}}function Uh(A){return Array.isArray(A)?A.map(Uh):A&&typeof A=="object"?Object.fromEntries(Object.keys(A).sort().map(e=>[e,Uh(A[e])])):A}const gz="1.3.0";class zc extends Error{code;paths;retryable;constructor(e,t,n,o){super(t),this.name="ArtifactError",this.code=e,n&&(this.paths=n),o&&(this.retryable=!0)}}function bk(A,e){if(!A||typeof A!="object")return!1;const t=A;return t.name!=="ArtifactError"||typeof t.code!="string"?!1:e===void 0||t.code===e}function az(A){return A==="owner"||A==="editor"}const kk={defaultMs:12e4,maxMs:6e5};function cz(A,e={}){const t=e.timeoutMs??1e4,n=new Map;return Object.freeze({version:gz,use:s=>{const g=n.get(s);if(g)return g;const a=new Promise(c=>{const I=setTimeout(()=>c(null),t);Promise.resolve().then(()=>A.get(s)).then(B=>{clearTimeout(I),c(B?Object.freeze(B):null)},()=>{clearTimeout(I),c(null)})});return n.set(s,a),a}})}function Iz(A,e){const t=globalThis.window?.openartifact;if(t)return t;const n=cz(A,e);return Object.defineProperty(window,"openartifact",{value:n,configurable:!1,enumerable:!0,writable:!1}),n}async function ny(A){const e=globalThis.window?.openartifact;if(!e)return null;try{return await e.use(A)}catch{return null}}const ke={session:"_api/session",files:"_api/files",file:"_api/file",publish:"_api/publish",assets:"_api/assets",events:"_api/events",agentSend:"_api/agent/send",presence:"_api/presence",peers:"_api/peers",downloads:"_api/downloads",roomEmit:"_api/room/emit",dbGet:"_api/db/get",dbList:"_api/db/list",dbWrite:"_api/db/write",comments:"_api/comments",commentsCreate:"_api/comments/create",commentsReply:"_api/comments/reply",commentsResolve:"_api/comments/resolve",commentsMove:"_api/comments/move",commentsRemove:"_api/comments/remove",commentsSend:"_api/comments/send",history:"_api/history",historyFiles:"_api/history/files",historyFile:"_api/history/file",historyDiff:"_api/history/diff",historyRestore:"_api/history/restore",historyDismiss:"_api/history/dismiss",mcpTools:"_api/mcp/tools",mcpCall:"_api/mcp/call"};function lz(A,e,t){return e===401||e===403?"removed":e<200||e>=300||!t||t.id===A.id&&t.role===A.role?null:"changed"}async function Mk(A){let e={};try{e=await A.json()}catch{}const t=A.status===409?"conflict":A.status===403?"not_writer":A.status===404?"not_found":"unavailable";return new zc(e.code??t,e.message??`HTTP ${A.status}`,e.paths,e.retryable===!0)}function Cz(){const A=new Uint8Array(8);return crypto.getRandomValues(A),Array.from(A,e=>e.toString(16).padStart(2,"0")).join("")}function SK(A={}){const e=new URL(A.base??"./",location.href),t=Cz(),n=(v,H)=>{const J=new URL(v,e);for(const[R,T]of Object.entries(H??{}))J.searchParams.set(R,T);return J.toString()},o=async(v,H,J)=>{let R;try{R=await fetch(n(v,J),H)}catch(T){throw new zc("unavailable",T instanceof Error?T.message:String(T))}if(!R.ok)throw await Mk(R);return await R.json()},s=(v,H)=>o(v,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(H)}),g=new Map,a=(v,H)=>{for(const J of g.get(v)??[])J(H)},c=(v,H)=>{let J=g.get(v);return J||(J=new Set,g.set(v,J),u?.addEventListener(v,E)),J.add(H),y(),()=>J.delete(H)};let I=null,B=!1,u=null,Q=null;const E=v=>{a(v.type,JSON.parse(v.data))},f=()=>{const v=new EventSource(n(ke.events,{client:t}));u=v;for(const H of g.keys())v.addEventListener(H,E);v.onerror=()=>{M().then(H=>{H||v.readyState!==EventSource.CLOSED||u!==v||(u=null,Q=setTimeout(()=>{Q=null,y()},2e3))})}};let h=!1,w=!1;const D=v=>{h||(h=!0,Q&&clearTimeout(Q),Q=null,u?.close(),u=null,I?.close(),I=null,A.onAccessChange?A.onAccessChange(v):location.reload())},M=async()=>{if(h)return!0;if(!S||w)return!1;w=!0;try{const v=(await S.catch(()=>null))?.viewer;if(!v)return!1;let H;try{H=await fetch(n(ke.session),{cache:"no-store"})}catch{return!1}const J=H.ok?(await H.json().catch(()=>null))?.viewer:null,R=lz(v,H.status,J);return R&&D(R),R!==null}finally{w=!1}};function y(){if(I||u||Q||h)return;if(typeof WebSocket>"u")return f();const v=new URL(n(ke.events,{client:t}));v.protocol=v.protocol==="https:"?"wss:":"ws:";const H=new WebSocket(v);I=H,H.onopen=()=>{B=!0},H.onmessage=J=>{let R;try{R=JSON.parse(String(J.data))}catch{return}R.event&&a(R.event,R.data)},H.onclose=()=>{if(I===H&&(I=null),!h){if(!B)return f();M().then(J=>{J||I||u||Q||(Q=setTimeout(()=>{Q=null,y()},2e3))})}}}let S=null;const x=()=>S??=o(ke.session),k={async artifact(){const{artifact:v}=await x();return{id:v.id,title:async()=>(await o(ke.session)).artifact.title,list:async()=>(await o(ke.files)).files,readText:async J=>new TextDecoder().decode(await G(J)),readBytes:J=>G(J),publish:async J=>{const R={files:J,client:t};return o(ke.publish,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(R)})},onChange:J=>c("files",J)}},async assets(){const{viewer:v}=await x();return az(v.role)?{upload:async(J,R)=>o(ke.assets,{method:"POST",headers:{"content-type":J.type||"application/octet-stream"},body:J},R?.name?{name:R.name}:void 0)}:null},async user(){const{viewer:v}=await x();return{me:async()=>v}},async agent(){return{send:async(H,J)=>{const R={request:H,deliver:J?.deliver??"send"};return o(ke.agentSend,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(R)})},status:async()=>(await o(ke.session)).agent,onStatus:H=>c("agent",H)}},async room(){return{self:async()=>t,presence:async H=>{const J={client:t,patch:H};await o(ke.presence,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(J)})},peers:async()=>(await o(ke.peers)).peers,onPeers:H=>c("peers",H),emit:async(H,J)=>{const R={client:t,topic:H,data:J};await s(ke.roomEmit,R)},onMessage:H=>c("room",H)}},async db(){const{stores:v}=await x();return v?.db?{get:async J=>(await o(ke.dbGet,{cache:"no-store"},{path:J})).data,list:async J=>(await o(ke.dbList,{cache:"no-store"},{collection:J})).documents,write:async J=>{const R={writes:J,client:t};await s(ke.dbWrite,R)},onChange:J=>c("db",J)}:null},async comments(){const{stores:v}=await x();if(!v?.comments)return null;const H=async(R,T)=>(await s(R,T)).thread;return{list:async()=>(await o(ke.comments,{cache:"no-store"})).threads,create:R=>H(ke.commentsCreate,{input:R}),reply:(R,T)=>H(ke.commentsReply,{threadId:R,text:T}),setResolved:(R,T)=>H(ke.commentsResolve,{threadId:R,resolved:T}),move:(R,T,q)=>H(ke.commentsMove,{threadId:R,anchor:T,...q?{location:q}:{}}),remove:async(R,T)=>{await s(ke.commentsRemove,{threadId:R,...T?{messageId:T}:{}})},sendToAgent:R=>H(ke.commentsSend,{threadId:R}),onChange:R=>c("comments",R)}},async history(){const{stores:v}=await x();if(!v?.history)return null;const H=(R,T)=>({n:String(R),...T===void 0?{}:{path:T}});return{list:()=>o(ke.history,{cache:"no-store"}),files:async R=>(await o(ke.historyFiles,{cache:"no-store"},H(R))).files,read:async(R,T)=>new TextDecoder().decode(await N(ke.historyFile,H(R,T))),readBytes:(R,T)=>N(ke.historyFile,H(R,T)),diff:(R,T)=>o(ke.historyDiff,{cache:"no-store"},H(R,T)),restore:(R,T)=>s(ke.historyRestore,{n:R,...T?{paths:T}:{},client:t}),dismissNotice:async R=>{await s(ke.historyDismiss,{id:R})},onChange:R=>c("history",R)}},async mcp(){const{viewer:v}=await x();return v.role!=="owner"?null:{callTool:async(J,R,T,q)=>{const z=q?.signal;z?.throwIfAborted();const L={server:J,tool:R,args:T,...q?.timeoutMs===void 0?{}:{timeoutMs:q.timeoutMs}};try{return await o(ke.mcpCall,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(L),...z?{signal:z}:{}})}catch(K){throw z?.aborted?z.reason:K}},listTools:J=>o(ke.mcpTools,{cache:"no-store"},J===void 0?void 0:{server:J})}},async downloads(){return{save:async({name:H,data:J})=>o(ke.downloads,{method:"POST",headers:{"content-type":J.type||"application/octet-stream"},body:J},{name:H})}}};function G(v){return N(ke.file,{path:v})}async function N(v,H){let J;try{J=await fetch(n(v,H),{cache:"no-store"})}catch(R){throw new zc("unavailable",R instanceof Error?R.message:String(R))}if(!J.ok)throw await Mk(J);return new Uint8Array(await J.arrayBuffer())}return{get(v){const H=k[v];return H?H():null}}}const uz="[Artifact comment sent to agent]",Bz="[Artifact edit request sent to agent]",dz="[Artifact task finished]",Qz=1,Ez=1,fz=/^[a-z][a-z0-9]{0,23}$/,hz="may not have run: the artifact was updated before this call was answered",pz=["quickstart","list","publish","read","open","call","adopt","delete","share"],wz=["get","list","query","set","update","delete","str_replace","batch"],yz=["read","reply","resolve","reopen","wait"],Dz=["share","export"],mz={type:"object",properties:{action:{type:"string",enum:pz,description:"What to do. Omitted: publish."},intent:{type:"string",description:"quickstart: what is being made (design, slides, whiteboard, document, data, other), or a few words about it."},scope:{type:"string",enum:["types","mine","all"],description:"list: the installed types, this session's and this workspace's artifacts (default), or every artifact."},type:{type:"string",description:"list: only artifacts of this type (an id, or open-artifact://type/<id>)."},query:{type:"string",description:"list: only artifacts whose title contains this text."},limit:{type:"integer",description:"list: how many to return (default 50, at most 200)."},cursor:{type:"string",description:"list: the next_cursor of the previous page."},type_url:{type:"string",description:"publish without url: the type to create from (open-artifact://type/<id>, from quickstart). read without url: the type to describe."},title:{type:"string",description:"publish without url: the new artifact's name."},folder:{type:"string",description:"publish without url, or adopt: where the artifact's folder goes (absolute, or relative to the workspace). Default <workspace>/artifacts/<slug>."},url:{type:"string",description:"An artifact: open-artifact://artifact/<id>, as publish returned it."},files:{type:"object",additionalProperties:!0,description:'publish with url: files to write under the artifact root, as {"rel/path": "text"} or {"rel/path": {"content": "...", "encoding": "base64"}}; null deletes.'},if_match:{type:"object",additionalProperties:!0,description:'publish with url: {"rel/path": sha256 | null | "*"}. Write only while the file still has the sha256 you read, does not exist (null), or anyway ("*"). One mismatch writes nothing and returns the current versions.'},check:{type:"boolean",description:"publish with url: run the type's check action after writing; its result comes back as check."},open:{type:"string",enum:["after_first_write","now"],description:"publish without url: after_first_write opens the page in your app once your first write lands; now opens it at once. Where your app cannot show pages by itself the result says so: open view_url in your app's built-in browser, if you have one."},related:{type:"boolean",description:"quickstart: list existing artifacts the recommended type can build on, such as design systems (default true)."},path:{type:"string",description:"read: one file or folder under the root (omitted: the record and the file list)."},paths:{type:"array",items:{type:"string"},description:"read: several files under the root at once."},name:{type:"string",description:"call: the action's name (check, upload, ...; read with url lists them)."},args:{type:"object",additionalProperties:!0,description:"call: the action's arguments. upload: {file: absolute path, name?, group?}."},panel:{type:"string",enum:Dz,description:"open: also open the page's Share panel (share), for the person to share it on the network, or its Export tab (export), for them to download a file."}}},Sz={type:"object",properties:{action:{type:"string",enum:wz},url:{type:"string",description:"The artifact (open-artifact://artifact/<id>)."},collection:{type:"string"},doc_id:{type:"string"},path:{type:"string",description:"collection/doc_id, instead of the two."},data:{type:"object",additionalProperties:!0,description:"set / update: the document's fields."},file_path:{type:"string",description:"set / update: a JSON file holding the fields, instead of data."},if_match:{description:'set / update / delete / str_replace: the sha256 get returned (write only if unchanged), null (only if it does not exist) or "*" (replace whatever is there).'},field:{type:"string",description:"str_replace: the text field, as a dot path (body, notes.text)."},old:{type:"string",description:"str_replace: the passage to replace; it must occur exactly once."},new:{type:"string",description:"str_replace: the passage that replaces it."},where:{type:"array",items:{type:"object",additionalProperties:!0},description:"query: [{field, op, value}], all must hold. op: ==, !=, <, <=, >, >=, in, not-in (up to 30 values), array-contains."},order_by:{type:"object",additionalProperties:!0,description:'query: {field, dir: "asc" | "desc"}.'},limit:{type:"integer",description:"list / query: how many documents (default 100, at most 1000)."},cursor:{type:"string",description:"list / query: the next_cursor of the previous page."},out_file:{type:"string",description:"get / list / query: write the result to this JSON file (absolute, or relative to the workspace) and return only its path and counts."},writes:{type:"array",items:{type:"object",additionalProperties:!0},description:"batch: [{op: set|update|delete|str_replace, path | collection+doc_id, data | file_path, if_match?, field?, old?, new?}], at most 500."}},required:["action","url"]},bz={type:"object",properties:{action:{type:"string",enum:yz},url:{type:"string",description:"The artifact (open-artifact://artifact/<id>). wait: optional."},thread_id:{type:"string",description:'reply / resolve / reopen: the thread (after ";thread=" in the message).'},text:{type:"string",description:"reply: the answer."},resolve:{type:"boolean",description:"reply: resolve the thread too."},all:{type:"boolean",description:"read: resolved threads too."},since:{type:"string",description:"read: only threads with a message at or after this time (ISO 8601)."},acknowledge_duplicate:{type:"boolean",description:"reply: send the same text as your last reply in this thread again, on purpose."},timeout_ms:{type:"number",description:"wait: how long (default 600000)."}},required:["action"]},xk={Artifact:mz,ArtifactData:Sz,ArtifactComments:bz},kz={Artifact:["Make and change artifacts: typed folders of files that open as live pages the person can view, edit, comment on and export. Actions:","- quickstart {intent}: call first for a new artifact; recommends a type and returns the call that creates it.",'- list {scope: "mine" | "all" | "types", type?, query?}: find existing artifacts, or the installed types.',"- publish {type_url, title, folder?, open?}: create an artifact; the result carries its root folder and the type's instructions. publish {url, files, if_match?, check?}: write files when you have no file tools of your own.","- read {url, path? | paths?}: the artifact's record, files and actions, or some of its files with their sha256. read {type_url}: a type's instructions, before creating.",`- open {url, panel?}: show it to the person in the computer's browser (or the app, when it shows pages), once its content is written. When your app has a built-in browser, open view_url there instead. panel "share" or "export" opens its Share panel or Export tab for them.`,"- call {url, name, args?}: run one of the type's actions (check, upload, ...). A long one answers {task, pending: true}; its result comes later as a message.","- adopt {url | folder}: take over an artifact, or add an existing folder. Only when the person asks.","- share {url}: whether it is shared on the local network, and its links. Only the person changes that, in the page's Share panel.","- delete {url}: forget an artifact; its folder stays. Only when the person asks."].join(`
34
+ `}}function fK(A,e){if(e.kind==="source")return{source:e.text,created:[]};const t=So(A);if(e.kind==="props"){if(!t.script||!t.props)return null;const c={...t.props};for(const[I,B]of Object.entries(e.values)){const u=c[I];!u||I==="$preview"||!("editor"in u)||(c[I]={...u,default:B})}return{source:V8(t,c),created:[]}}if(e.kind==="scriptText"){if(!t.script)return null;const c=t.script.body.text,I=ey(c),B=I.filter(E=>E.value===e.value),u=I.find(E=>E.start===e.start&&E.end===e.end&&E.value===e.value)??(B.length===1?B[0]:void 0);if(!u)return null;const Q=c.slice(0,u.start)+hP(e.text,u.quote)+c.slice(u.end);return Q===c?null:{source:P8(t,Q),created:[]}}if(!t.template)return null;const n=jg(t.template.text);let o;try{switch(e.kind){case"style":{const c=Ts(n,e.targets);if(!c)return null;o=c.flatMap(I=>Fh(n,I,e.patch));break}case"styles":{const c=Ts(n,e.edits.map(I=>I.target));if(!c)return null;o=c.flatMap((I,B)=>Fh(n,I,e.edits[B].patch));break}case"attr":{const c=nt(n,e.target.tid,e.target.path);if(!c)return null;o=vh(n,c,e.name,e.value);break}case"text":{const c=nt(n,e.target.tid,e.target.path);if(!c)return null;o=MP(c,e.text);break}case"richText":{const c=nt(n,e.target.tid,e.target.path);if(!c||!na(c))return null;const I=dP(e.html);if(o=[{start:c.openEnd,end:c.closeStart,text:I}],c.tag==="p"&&QP(I)){const B=c.start+1;o.push({start:B,end:B+c.rawTag.length,text:"div"});const u=c.closeStart+2;o.push({start:u,end:u+c.rawTag.length,text:"div"})}break}case"wrapText":{const c=nt(n,e.target.tid,e.target.path);if(!c)return null;const I=aK(c,n.text,e.inline);if(!I.length)return null;o=I.flatMap(B=>[{start:B.start,end:B.start,text:"<span>"},{start:B.end,end:B.end,text:"</span>"}]);break}case"importText":{const c=nt(n,e.target.tid,e.target.path);if(!c||c.tag!=="x-import")return null;const I=lK(e,e.text,IK(c,dK(A)));if(I.kind!=="commit")return null;o=I.key==="__text"?xP(c,Hg(I.text)):vh(n,c,I.key.slice(1),I.text);break}case"linkText":{const c=nt(n,e.target.tid,e.target.path);if(!c||c.closeStart<=c.openEnd||c.tag==="a")return null;o=[{start:c.openEnd,end:c.openEnd,text:`<a ${uK("href",e.href)}>`},{start:c.closeStart,end:c.closeStart,text:"</a>"}];break}case"remove":{const c=Ts(n,e.targets);if(!c)return null;o=BK(n,c);break}case"duplicate":{const c=Ts(n,e.targets);if(!c)return null;o=NP(n,c);break}case"insert":{const c=e.target?nt(n,e.target.tid,e.target.path):null;if(e.target&&!c)return null;o=Qu(n,c,e.position,e.html),e.helmet&&o.push(hk(n,e.helmet));break}case"move":{const c=Ts(n,e.targets),I=nt(n,e.target.tid,e.target.path);if(!c||!I)return null;o=GP(n,c,I,e.position);break}case"wrap":{const c=Ts(n,e.targets);if(!c||c.length===0)return null;o=RP(n,c,e.open,e.close);break}case"unwrap":{const c=nt(n,e.target.tid,e.target.path);if(!c)return null;o=vP(n,c);break}case"replace":{const c=Ts(n,e.edits.map(I=>I.target));if(!c||!c.length)return null;o=c.map((I,B)=>({start:I.start,end:I.end,text:e.edits[B].html})),e.helmet&&o.push(hk(n,e.helmet));break}}}catch{return null}const s=CK(n.text,o),g=jg(s);let a=e.kind==="style"||e.kind==="styles"||e.kind==="attr"||e.kind==="text"||e.kind==="importText"?[]:LP(g,YP(o)).filter(c=>!JP(g.elements[c.tid]));if(e.kind==="richText"){const c=nt(n,e.target.tid,e.target.path),I=c?g.elements.find(E=>E.start===c.start):void 0,B=[],u=E=>{for(const f of pe(E.children))f.tag==="a"&&B.push(f),u(f)};I&&e.link!=null&&u(I);const Q=e.link!=null?B[e.link]:void 0;a=Q?[EK(g,Q)]:[]}return{source:q8(t,s),created:a}}function TP(A,e){let t=A;const n=[];for(const o of e){const s=fK(t,o);s&&(t=s.source,n.push(o))}return{source:t,kept:n,dropped:e.length-n.length}}const pk=A=>{if(A===null)return{canvas:uu(),error:null};try{return{canvas:YB(JSON.parse(A)),error:null}}catch(e){return{canvas:uu(),error:e instanceof Error?e.message:String(e)}}},_i=(A,e)=>[...A.slice(-199),e],iA=Wn()((A,e)=>({status:"loading",error:null,title:"",readOnly:!1,canvas:uu(),canvasSaved:uu(),canvasHash:null,canvasError:null,boards:{},trash:[],undo:[],redo:[],edits:0,save:"saved",revision:0,gesture:null,load({title:t,readOnly:n,canvas:o,boards:s}){const g=pk(o.text),a={};for(const[c,I]of Object.entries(s))a[c]={source:I.text,saved:I.text,hash:I.hash,pending:[]};A({status:"ready",title:g.canvas.title||t,readOnly:n,canvas:g.canvas,canvasSaved:g.canvas,canvasHash:o.hash,canvasError:g.error,boards:a,save:n?"readonly":"saved"})},fail(t){A({status:"error",error:t})},editBoard(t,n,o={}){const s=e(),g=s.boards[t];if(s.readOnly||!g?.source)return null;const a=fK(g.source,n);if(!a||a.source===g.source)return a;const c={source:a.source,pending:[...g.pending,n]},I=s.undo[s.undo.length-1],B=o.coalesce&&I?.scope==="board"&&I.path===t&&I.key===o.coalesce&&I.after.source===g.source,u=B?I.before:{source:g.source,pending:g.pending},Q={scope:"board",path:t,before:u,after:c,...o.coalesce?{key:o.coalesce}:{}};return A({boards:{...s.boards,[t]:{...g,...c}},undo:B?[...s.undo.slice(0,-1),Q]:_i(s.undo,Q),redo:[],edits:s.edits+1,revision:s.revision+1}),a},updateCanvas(t){const n=e();if(n.readOnly||n.canvasError)return;const o=t(n.canvas);o!==n.canvas&&A({canvas:o,...n.gesture?{}:{undo:_i(n.undo,{scope:"canvas",before:n.canvas,after:o}),redo:[]},revision:n.revision+1})},beginGesture(){e().gesture||A({gesture:e().canvas})},endGesture(){const{gesture:t,canvas:n,undo:o}=e();t&&A({gesture:null,...t!==n?{undo:_i(o,{scope:"canvas",before:t,after:n}),redo:[]}:{}})},createBoard(t,n,o){const s=e();if(s.readOnly)return;const g=s.boards[t],a={...s.canvas,boards:{...s.canvas.boards,[t]:o},order:[...s.canvas.order.filter(c=>c!==t),t]};A({boards:{...s.boards,[t]:{source:n,saved:g?.saved??null,hash:g?.hash??null,pending:[]}},canvas:a,trash:s.trash.filter(c=>c!==t),undo:_i(s.undo,{scope:"canvas",before:s.canvas,after:a}),redo:[],edits:s.edits+1,revision:s.revision+1})},deleteBoards(t){const n=e();if(n.readOnly||t.length===0)return;const o={...n.canvas.boards};for(const g of t)delete o[g];const s={...n.canvas,boards:o,order:n.canvas.order.filter(g=>!t.includes(g))};A({canvas:s,trash:[...new Set([...n.trash,...t])],undo:_i(n.undo,{scope:"canvas",before:n.canvas,after:s}),redo:[],edits:n.edits+1,revision:n.revision+1})},undoLast(){const t=e(),n=t.undo[t.undo.length-1];if(!n||t.readOnly)return null;if(n.scope==="canvas"){const o=ZE(n.after,n.before,t.canvas);A({canvas:o,undo:t.undo.slice(0,-1),redo:_i(t.redo,n),revision:t.revision+1})}else{const o=t.boards[n.path];if(!o)return null;A({boards:{...t.boards,[n.path]:{...o,...n.before}},undo:t.undo.slice(0,-1),redo:_i(t.redo,n),revision:t.revision+1})}return n},redoLast(){const t=e(),n=t.redo[t.redo.length-1];if(!n||t.readOnly)return null;if(n.scope==="canvas"){const o=ZE(n.before,n.after,t.canvas);A({canvas:o,redo:t.redo.slice(0,-1),undo:_i(t.undo,n),revision:t.revision+1})}else{const o=t.boards[n.path];if(!o)return null;A({boards:{...t.boards,[n.path]:{...o,...n.after}},redo:t.redo.slice(0,-1),undo:_i(t.undo,n),revision:t.revision+1})}return n},remoteBoard(t,n,o){const s=e(),g=s.boards[t],a=I=>I.filter(B=>B.scope!=="board"||B.path!==t);if(n===null)return g&&A({boards:{...s.boards,[t]:{...g,saved:null,hash:null,...g.pending.length?{}:{source:null}}}}),0;const c=g?.pending.length?TP(n,g.pending):{source:n,kept:[],dropped:0};return A({boards:{...s.boards,[t]:{source:c.source,saved:n,hash:o,pending:c.kept}},undo:a(s.undo),redo:a(s.redo),...c.kept.length?{revision:s.revision+1}:{}}),c.dropped},remoteCanvas(t,n){const o=e(),s=pk(t);if(s.error){A({canvasError:s.error,canvasHash:n});return}const g=o.canvas!==o.canvasSaved,a=g?ZE(o.canvasSaved,o.canvas,s.canvas):s.canvas;A({canvas:a,canvasSaved:s.canvas,canvasHash:n,canvasError:null,title:s.canvas.title||o.title,...g?{revision:o.revision+1}:{}})},acknowledge(t,n){const o=e(),s={...o.boards};for(const[g,{source:a,pendingCount:c}]of Object.entries(t.boards)){const I=s[g];!I||!(g in n)||(s[g]={...I,saved:a,hash:n[g]??null,pending:I.pending.slice(c)})}for(const g of t.deleted){const a=s[g];a&&(s[g]={...a,saved:null,hash:null})}A({boards:s,trash:o.trash.filter(g=>!t.deleted.includes(g)),...t.canvas&&"canvas.json"in n?{canvasSaved:t.canvas.canvas,canvasHash:n["canvas.json"]??null}:{}})},setSave(t){e().save!==t&&A({save:t})},setTitle(t){A({title:t})}}));function Eu(A){return A.readOnly?!1:A.canvas!==A.canvasSaved||A.trash.some(e=>A.boards[e]?.hash)?!0:Object.entries(A.boards).some(([e,t])=>t.source!==null&&hK(A,e,t))}function hK(A,e,t){return t.source===null?!1:t.source!==t.saved?!0:t.hash===null&&e in A.canvas.boards}const ia=.01,dI=8,Tn={kind:"none"},HP=[1.5,3,5,8],pK="mc-toolbar/top";function OP(){try{return typeof localStorage<"u"&&localStorage.getItem(pK)==="1"}catch{return!1}}const eA=Wn()((A,e)=>({camera:{x:0,y:0,zoom:1},page:null,tool:"select",selection:Tn,hover:null,peek:null,textEdit:null,noteEdit:null,mode:"canvas",focused:null,panel:"properties",panelOpen:!1,frames:{},layoutTick:0,overrides:{},composer:!1,spacePan:!1,pen:{stroke:3,dash:"solid"},findOpen:!1,toolbarTop:OP(),crop:null,setCamera(t){const n=Math.min(dI,Math.max(ia,t.zoom));A({camera:{...t,zoom:n}})},setPage(t){e().page!==t&&A({page:t,selection:Tn,hover:null,peek:null,crop:null})},setTool(t){A({tool:t})},select(t){A({selection:t,noteEdit:null,...e().crop?{crop:null}:{}})},setHover(t){const n=e().hover;n?.board===t?.board&&n?.tid===t?.tid&&n?.instance===t?.instance||A({hover:t})},setPeek(t){e().peek!==t&&A({peek:t})},setTextEdit(t){A({textEdit:t})},patchTextEdit(t){const{textEdit:n}=e();n&&A({textEdit:{...n,...t}})},setNoteEdit(t){A({noteEdit:t})},focus(t){A(t?{mode:"focused",focused:t,hover:null}:{mode:"canvas",focused:null})},setPanel(t,n=!0){A({panel:t,panelOpen:n})},togglePanel(){A({panelOpen:!e().panelOpen})},frame(t,n){const o=e().frames,s=o[t]??{booted:!1,errors:[],size:null};A({frames:{...o,[t]:{...s,...n}},layoutTick:e().layoutTick+1})},dropFrame(t){const{[t]:n,...o}=e().frames;A({frames:o})},parkFrame(t){const n=e().frames[t];if(!n)return;const o=structuredClone(n.errors),s=n.size?structuredClone(n.size):null;A({frames:{...e().frames,[t]:{booted:!1,errors:o,size:s}}})},tick(){A({layoutTick:e().layoutTick+1})},setOverride(t,n,o){const s=e().overrides;A({overrides:{...s,[t]:{...s[t]??{},[n]:o}}})},clearOverrides(t){const{[t]:n,...o}=e().overrides;A({overrides:o})},setComposer(t){A({composer:t})},setPen(t){A({pen:{...e().pen,...t}})},setSpacePan(t){e().spacePan!==t&&A({spacePan:t})},setFindOpen(t){e().findOpen!==t&&A({findOpen:t})},setToolbarTop(t){try{localStorage.setItem(pK,t?"1":"0")}catch{}A({toolbarTop:t})},setCrop(t){A({crop:t})}}));function cc(A,e,t){return{x:(e-A.x)/A.zoom,y:(t-A.y)/A.zoom}}const jP=4e3;function qP(A){return A.wakesIdle===!1?`${A.name} gets this on its next turn: send it a message to start one`:"Waiting for the agent"}function PP(A,e){return e===!1?{title:`Sent to ${A}`,description:`${A} gets it on its next turn. If it is idle, send it a message there to start one.`}:{title:`Sent to ${A}`}}function wK(A){return A.reduce((e,t)=>t.status==="open"?e+t.messages.length:e,0)}function zP(A){return A==="detached"?"What this was on is gone; shown on what held it.":A==="orphaned"?"What this was on has been deleted.":null}function VP(A){const e=A.maxThreads??500,t=A.noun??"document",n=D=>A.notify?.(D);let o=null,s,g=0;const a=Wn()(D=>({available:!1,threads:[],on:!1,listOpen:!1,active:null,draft:null,showResolved:!1,sendNew:!1,draftText:"",replies:{},setOn(M){D({on:M,draft:null}),A.onModeChange?.(M)},setListOpen(M){D({listOpen:M})},setActive(M){D({active:M,draft:null})},setDraft(M){D(M===null?{draft:M,active:null,draftText:"",sendNew:!1}:{draft:M,active:null})},setShowResolved(M){D({showResolved:M})},setSendNew(M){D({sendNew:M})},setDraftText(M){D({draftText:M})},setReply(M,y){D(S=>({replies:{...S.replies,[M]:y}}))}})),c=new Map,I=D=>{let M=c.get(D.anchor);return M===void 0&&(M=A.parse(D.anchor),c.size>2e3&&c.clear(),c.set(D.anchor,M)),M},B=D=>{n({title:"The comment could not be saved",description:D instanceof Error?D.message:String(D)})},u=D=>{a.setState(M=>({threads:M.threads.map(y=>y.id===D.id?D:y)})),A.heard?.([D])},Q=D=>A.checkText?A.checkText(D):D.trim().slice(0,jP)||void 0,E=()=>!!o&&A.canComment(),f=()=>!!o&&A.canSendToAgent(),w={store:a,adapter:A,async start(D,M){if(!D)return;o=D;const y=g;a.setState({available:!0});try{const x=await D.list();if(y!==g)return;a.setState({threads:x}),A.heard?.(x)}catch{}if(y!==g)return;s=D.onChange(x=>{const k=a.getState().active;a.setState({threads:x,active:k&&x.some(G=>G.id===k)?k:null}),A.heard?.(x)});const S=M?a.getState().threads.find(x=>x.id===M):void 0;S&&w.reveal(S)},stop(){g+=1,s?.(),s=void 0},capability:()=>o,canComment:E,canSendToAgent:f,canRemove:()=>!!o&&(A.canRemove?A.canRemove():A.canComment()),anchorOf:I,labelOf:D=>A.label(D),stateOf:D=>A.state?.(D)??"ok",stateNote:D=>A.stateNote?A.stateNote(D??"ok"):zP(D),async create(D,M,y){if(!o)return!1;const S=Q(M);if(!S)return!1;if(a.getState().threads.length>=e)return n({title:`This ${t} already has ${e} comments`}),!1;try{const x=A.detail?.(D),k=await o.create({anchor:A.serialize(D),label:A.label(D),...x!==void 0?{detail:x}:{},location:A.location?.(D)??{},text:S});return a.setState(G=>({threads:G.threads.some(N=>N.id===k.id)?G.threads:[...G.threads,k],draft:null,draftText:"",sendNew:!1,active:k.id})),A.heard?.([k]),y?.send&&f()&&await w.sendToAgent(k.id),!0}catch(x){return B(x),!1}},async reply(D,M,y){if(!o)return!1;const S=Q(M);if(!S)return!1;try{let x=await o.reply(D,S);return x.status==="resolved"&&(x=await o.setResolved(D,!1)),u(x),a.setState(k=>{const{[D]:G,...N}=k.replies;return{replies:N}}),y?.send&&f()&&await w.sendToAgent(D),!0}catch(x){return B(x),!1}},async resolve(D,M){if(o)try{u(await o.setResolved(D,M));const y=a.getState();M&&y.active===D&&!y.showResolved&&a.setState({active:null})}catch(y){B(y)}},async remove(D,M){if(!(!o||A.canRemove&&!A.canRemove()))try{await o.remove(D,M),M||a.setState(y=>({threads:y.threads.filter(S=>S.id!==D),active:y.active===D?null:y.active}))}catch(y){B(y)}},async move(D,M){if(o)try{u(await o.move(D,A.serialize(M),A.location?.(M)))}catch(y){B(y)}},async sendToAgent(D){if(!o||!f())return!1;const M=A.sendToAgent?a.getState().threads.find(y=>y.id===D):void 0;if(A.sendToAgent)return M?A.sendToAgent(M,I(M)):!1;try{return u(await o.sendToAgent(D)),n(PP(A.agentName?.()||"the agent",A.agentWakesIdle?.())),!0}catch(y){return B(y),!1}},async sendAllToAgent(){const D=a.getState().threads.filter(M=>w.canSendThread(M));for(const M of D)await w.sendToAgent(M.id)},canSendThread(D){if(D.status!=="open")return!1;const M=D.messages.at(-1);return!M||M.author.kind!=="person"?!1:!D.agent||D.agent.status==="replied"},reveal(D){A.reveal?.(I(D)),a.getState().setActive(D.id)},show(D){const M=a.getState();M.on||M.setOn(!0),D.status==="resolved"&&!a.getState().showResolved&&a.getState().setShowResolved(!0),w.reveal(D)},viewerName:()=>A.viewerName?.()||"You"};return w}const XE=A=>A instanceof Error?A.message:String(A);function ZP(A){const e=A.noun??"document",t=a=>A.notify?.(a);let n=null,o=0;const s=Wn()(a=>({available:!1,open:!1,previewing:null,preview:null,loading:!1,error:null,canRestore:!1,setOpen(c){a(c?{open:c}:{open:c,previewing:null,preview:null,error:null,loading:!1})}})),g={store:s,start(a){if(n=a,!a)return;s.setState({available:!0});const c=()=>{a.list().then(I=>s.setState({canRestore:I.canRestore}),()=>{})};c(),a.onChange(c)},capability:()=>n,toggle(a){const c=s.getState();c.available&&c.setOpen(a??!c.open)},async preview(a){const c=++o;if(a===null||!n){s.setState({previewing:null,preview:null,loading:!1,error:null});return}s.setState({previewing:a,loading:!0,error:null});try{const I=await A.loadPreview(n,a);c===o&&s.setState({preview:I,loading:!1})}catch(I){c===o&&s.setState({loading:!1,error:XE(I)})}},async restore(a){if(n)try{const c=await n.restore(a);t({title:c.changed.length?`Restored version ${a}`:`The ${e} already matches version ${a}`}),await g.preview(null)}catch(c){t({title:"The version could not be restored",description:XE(c)})}},async restorePaths(a,c,I){if(!n)return null;try{return(await n.restore(a,c)).changed}catch(B){return t({title:`${I} could not be restored`,description:XE(B)}),null}}};return g}const wk=["#e5484d","#0091ff","#30a46c","#f76b15","#8e4ec6","#d6409f","#12a594","#ad7f58"],ty="#6e56cf",yk=8e3,WP=80,Kg=50;function _P(A){let e=0;for(let t=0;t<A.length;t++)e=e*31+A.charCodeAt(t)|0;return wk[Math.abs(e)%wk.length]}const to={str:(A,e=512)=>typeof A=="string"&&A.length<=e?A:null,num:A=>typeof A=="number"&&Number.isFinite(A)?A:null,strList:(A,e=Kg)=>Array.isArray(A)?A.map(t=>to.str(t)).filter(t=>t!==null).slice(0,e):[],point:A=>{if(!A||typeof A!="object")return null;const e=A,t=to.num(e.x),n=to.num(e.y);return t!==null&&n!==null?{x:t,y:n}:null}};function XP(A,e,t,n){return A.filter(o=>o.id!==e).map(o=>{const s=o.state?.[t],g=s&&typeof s=="object"&&!Array.isArray(s)?s:null;return{id:o.id,name:(o.name||(o.kind==="agent"?"Agent":"Guest")).slice(0,60),kind:o.kind,color:o.kind==="agent"?ty:_P(o.id),cursor:g?to.point(g.cursor):null,state:g?n(g):null}}).sort((o,s)=>o.kind===s.kind?o.name.localeCompare(s.name):o.kind==="person"?-1:1)}function $P(A){const e=Wn()(()=>({available:!1,peers:[],agentWrote:null}));async function t({room:n,artifact:o}){const s=[];let g=null;if(o&&(s.push(o.onChange(y=>{if(y.author!=="agent")return;const S=Object.keys(y.changes).map(G=>A.wrotePath?A.wrotePath(G):G).filter(G=>G!==null),x=e.getState().agentWrote,k=x&&Date.now()-x.at<yk?x.paths:[];e.setState({agentWrote:{at:Date.now(),paths:[...new Set([...k,...S])].slice(0,Kg)}}),g&&clearTimeout(g),g=setTimeout(()=>e.setState({agentWrote:null}),yk)})),s.push(()=>{g&&clearTimeout(g)})),!n)return()=>s.forEach(y=>y());e.setState({available:!0});const a=await n.self().catch(()=>null),c=A.pointer?.bind(A),I=A.sendMs??WP;let B=null,u="",Q=null;const E=()=>{Q=null;const y=c?{...A.snapshot(),cursor:B}:A.snapshot(),S=JSON.stringify(y);S!==u&&(u=S,n.presence({[A.key]:y}).catch(()=>{}))},f=()=>{Q||(Q=setTimeout(E,I))};E(),s.push(A.watch(f));const h=y=>{const S=c?.(y)??null;if(!S){B&&(B=null,f());return}B={x:Math.round(S.x),y:Math.round(S.y)},f()},w=()=>{B=null,f()},D=()=>{document.visibilityState==="hidden"&&w()};c&&(window.addEventListener("pointermove",h,{passive:!0}),document.addEventListener("pointerleave",w),document.addEventListener("visibilitychange",D)),s.push(()=>{c&&(window.removeEventListener("pointermove",h),document.removeEventListener("pointerleave",w),document.removeEventListener("visibilitychange",D)),Q&&clearTimeout(Q),n.presence({[A.key]:null}).catch(()=>{})});const M=y=>{e.setState({peers:XP(y,a,A.key,A.parse)}),A.onPeers?.(y,a)};return n.peers().then(M,()=>{}),s.push(n.onPeers(M)),()=>s.forEach(y=>y())}return{store:e,start:t}}function Az(A,e){return e.available&&e.open?"history":null}function ez({comments:A,history:e,adapter:t}){const n=s=>{const g=A.store.getState(),a=s??!g.listOpen;g.setListOpen(a),a&&e.store.getState().open&&e.toggle(!1)},o=s=>{const g=s??!e.store.getState().open;e.toggle(g),g&&A.store.getState().setListOpen(!1)};return{chromeReport(){const s=A.store.getState(),g=e.store.getState();return{...s.available?{comments:{available:!0,on:s.on,open:s.listOpen,count:wK(s.threads),pageButton:t.pageButton??!1}}:{},...g.available?{history:!0}:{}}},subscribe(s){const g=A.store.subscribe(s),a=e.store.subscribe((c,I)=>{c.available!==I.available&&s()});return()=>{g(),a()}},handleCommand(s){switch(s.cmd){case"comments_mode":{const g=A.store.getState();if(!g.available)return!0;const a=s.on??!g.on;return a&&!t.onSurface()&&t.showSurface?.(),g.setOn(a),!0}case"comments_list":return n(s.open),!0;case"history":return o(),!0;case"action":return s.id==="comment_selection"&&t.commentOnSelection?(t.commentOnSelection(),!0):!1;default:return!1}},toggleCommentList:n,toggleHistoryPanel:o,useAside(){A.store(a=>a.available),A.store(a=>a.listOpen);const s=e.store(a=>a.available),g=e.store(a=>a.open);return Az({},{available:s,open:g})},runShortcut(s){if(e.store.getState().previewing!==null)return!0;const g=A.store.getState();if(!g.available)return!1;if(s.key==="Escape"){if(g.draft!==null)g.setDraft(null);else if(g.active)g.setActive(null);else if(g.on)g.setOn(!1);else return!1;return!0}return(s.code?.startsWith("Key")?s.code.slice(3).toLowerCase():s.key.toLowerCase())==="c"&&!s.meta&&!s.alt&&!s.shift?!A.canComment()||!t.onSurface()?!1:(g.setOn(!g.on),!0):!!(g.on&&!s.meta&&!t.readOnly()&&(s.key==="Delete"||s.key==="Backspace"))}}}function Dk(A,e){return{x:e.x*A.zoom+A.x,y:e.y*A.zoom+A.y}}function Ic(A,e){const t=A.zoom||1;return{x:(e.x-A.x)/t,y:(e.y-A.y)/t}}function yK(A,e){return{left:e.x*A.zoom+A.x,top:e.y*A.zoom+A.y,width:e.w*A.zoom,height:e.h*A.zoom}}const mk=200,Kh=Wn()(()=>({message:"",serial:0}));function tz(A){const e=A.replace(/\s+/g," ").trim();return e.length>mk?`${e.slice(0,mk-1)}…`:e}function st(A){const e=tz(A);e&&Kh.setState(t=>({message:e,serial:t.serial+1}))}function DK(A){const t=new URLSearchParams(A.replace(/^#/,"")).get("page");return t||null}function mK(A,e){const t=new URLSearchParams(A.replace(/^#/,""));e?t.set("page",e):t.delete("page");const n=t.toString();return n?`#${n}`:""}function nz(A,e){const t=new URL(A);return`${t.origin}${t.pathname}${mK(t.hash,e)}`}function iz(A){let e=!1;const t=(s,g)=>{const a=mK(location.hash,s);if(a===location.hash||!a&&!location.hash)return;const c=`${location.pathname}${location.search}${a}`;try{g?history.pushState(history.state,"",c):history.replaceState(history.state,"",c)}catch{}};t(A.current(),!1);const n=A.subscribe(s=>{e||t(s,!0)}),o=()=>{const s=DK(location.hash),g=s&&A.exists(s)?s:A.fallback();if(g!==A.current()){e=!0;try{A.show(g)}finally{e=!1}}};return window.addEventListener("popstate",o),()=>{n(),window.removeEventListener("popstate",o)}}const oz=4320*60*1e3;function sz(A,e){return e-A<=oz&&A<=e+6e4}function rz(A,e,t=()=>globalThis.localStorage){const n=()=>{try{t()?.removeItem(A)}catch{}};return{read(){try{const o=t()?.getItem(A);return o?e(JSON.parse(o)):null}catch{return null}},write(o){if(o===null)return n();try{t()?.setItem(A,JSON.stringify(o))}catch{}},clear:n}}function Sk(A){try{return JSON.stringify(Uh(JSON.parse(A)))}catch{return A}}function Uh(A){return Array.isArray(A)?A.map(Uh):A&&typeof A=="object"?Object.fromEntries(Object.keys(A).sort().map(e=>[e,Uh(A[e])])):A}const gz="1.3.0";class zc extends Error{code;paths;retryable;constructor(e,t,n,o){super(t),this.name="ArtifactError",this.code=e,n&&(this.paths=n),o&&(this.retryable=!0)}}function bk(A,e){if(!A||typeof A!="object")return!1;const t=A;return t.name!=="ArtifactError"||typeof t.code!="string"?!1:e===void 0||t.code===e}function az(A){return A==="owner"||A==="editor"}const kk={defaultMs:12e4,maxMs:6e5};function cz(A,e={}){const t=e.timeoutMs??1e4,n=new Map;return Object.freeze({version:gz,use:s=>{const g=n.get(s);if(g)return g;const a=new Promise(c=>{const I=setTimeout(()=>c(null),t);Promise.resolve().then(()=>A.get(s)).then(B=>{clearTimeout(I),c(B?Object.freeze(B):null)},()=>{clearTimeout(I),c(null)})});return n.set(s,a),a}})}function Iz(A,e){const t=globalThis.window?.openartifact;if(t)return t;const n=cz(A,e);return Object.defineProperty(window,"openartifact",{value:n,configurable:!1,enumerable:!0,writable:!1}),n}async function ny(A){const e=globalThis.window?.openartifact;if(!e)return null;try{return await e.use(A)}catch{return null}}const ke={session:"_api/session",files:"_api/files",file:"_api/file",publish:"_api/publish",assets:"_api/assets",events:"_api/events",agentSend:"_api/agent/send",presence:"_api/presence",peers:"_api/peers",downloads:"_api/downloads",roomEmit:"_api/room/emit",dbGet:"_api/db/get",dbList:"_api/db/list",dbWrite:"_api/db/write",comments:"_api/comments",commentsCreate:"_api/comments/create",commentsReply:"_api/comments/reply",commentsResolve:"_api/comments/resolve",commentsMove:"_api/comments/move",commentsRemove:"_api/comments/remove",commentsSend:"_api/comments/send",history:"_api/history",historyFiles:"_api/history/files",historyFile:"_api/history/file",historyDiff:"_api/history/diff",historyRestore:"_api/history/restore",historyDismiss:"_api/history/dismiss",mcpTools:"_api/mcp/tools",mcpCall:"_api/mcp/call"};function lz(A,e,t){return e===401||e===403?"removed":e<200||e>=300||!t||t.id===A.id&&t.role===A.role?null:"changed"}async function Mk(A){let e={};try{e=await A.json()}catch{}const t=A.status===409?"conflict":A.status===403?"not_writer":A.status===404?"not_found":"unavailable";return new zc(e.code??t,e.message??`HTTP ${A.status}`,e.paths,e.retryable===!0)}function Cz(){const A=new Uint8Array(8);return crypto.getRandomValues(A),Array.from(A,e=>e.toString(16).padStart(2,"0")).join("")}function SK(A={}){const e=new URL(A.base??"./",location.href),t=Cz(),n=(v,H)=>{const J=new URL(v,e);for(const[R,T]of Object.entries(H??{}))J.searchParams.set(R,T);return J.toString()},o=async(v,H,J)=>{let R;try{R=await fetch(n(v,J),H)}catch(T){throw new zc("unavailable",T instanceof Error?T.message:String(T))}if(!R.ok)throw await Mk(R);return await R.json()},s=(v,H)=>o(v,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(H)}),g=new Map,a=(v,H)=>{for(const J of g.get(v)??[])J(H)},c=(v,H)=>{let J=g.get(v);return J||(J=new Set,g.set(v,J),u?.addEventListener(v,E)),J.add(H),y(),()=>J.delete(H)};let I=null,B=!1,u=null,Q=null;const E=v=>{a(v.type,JSON.parse(v.data))},f=()=>{const v=new EventSource(n(ke.events,{client:t}));u=v;for(const H of g.keys())v.addEventListener(H,E);v.onerror=()=>{M().then(H=>{H||v.readyState!==EventSource.CLOSED||u!==v||(u=null,Q=setTimeout(()=>{Q=null,y()},2e3))})}};let h=!1,w=!1;const D=v=>{h||(h=!0,Q&&clearTimeout(Q),Q=null,u?.close(),u=null,I?.close(),I=null,A.onAccessChange?A.onAccessChange(v):location.reload())},M=async()=>{if(h)return!0;if(!S||w)return!1;w=!0;try{const v=(await S.catch(()=>null))?.viewer;if(!v)return!1;let H;try{H=await fetch(n(ke.session),{cache:"no-store"})}catch{return!1}const J=H.ok?(await H.json().catch(()=>null))?.viewer:null,R=lz(v,H.status,J);return R&&D(R),R!==null}finally{w=!1}};function y(){if(I||u||Q||h)return;if(typeof WebSocket>"u")return f();const v=new URL(n(ke.events,{client:t}));v.protocol=v.protocol==="https:"?"wss:":"ws:";const H=new WebSocket(v);I=H,H.onopen=()=>{B=!0},H.onmessage=J=>{let R;try{R=JSON.parse(String(J.data))}catch{return}R.event&&a(R.event,R.data)},H.onclose=()=>{if(I===H&&(I=null),!h){if(!B)return f();M().then(J=>{J||I||u||Q||(Q=setTimeout(()=>{Q=null,y()},2e3))})}}}let S=null;const x=()=>S??=o(ke.session),k={async artifact(){const{artifact:v}=await x();return{id:v.id,title:async()=>(await o(ke.session)).artifact.title,list:async()=>(await o(ke.files)).files,readText:async J=>new TextDecoder().decode(await G(J)),readBytes:J=>G(J),publish:async J=>{const R={files:J,client:t};return o(ke.publish,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(R)})},onChange:J=>c("files",J)}},async assets(){const{viewer:v}=await x();return az(v.role)?{upload:async(J,R)=>o(ke.assets,{method:"POST",headers:{"content-type":J.type||"application/octet-stream"},body:J},R?.name?{name:R.name}:void 0)}:null},async user(){const{viewer:v}=await x();return{me:async()=>v}},async agent(){return{send:async(H,J)=>{const R={request:H,deliver:J?.deliver??"send"};return o(ke.agentSend,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(R)})},status:async()=>(await o(ke.session)).agent,onStatus:H=>c("agent",H)}},async room(){return{self:async()=>t,presence:async H=>{const J={client:t,patch:H};await o(ke.presence,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(J)})},peers:async()=>(await o(ke.peers)).peers,onPeers:H=>c("peers",H),emit:async(H,J)=>{const R={client:t,topic:H,data:J};await s(ke.roomEmit,R)},onMessage:H=>c("room",H)}},async db(){const{stores:v}=await x();return v?.db?{get:async J=>(await o(ke.dbGet,{cache:"no-store"},{path:J})).data,list:async J=>(await o(ke.dbList,{cache:"no-store"},{collection:J})).documents,write:async J=>{const R={writes:J,client:t};await s(ke.dbWrite,R)},onChange:J=>c("db",J)}:null},async comments(){const{stores:v}=await x();if(!v?.comments)return null;const H=async(R,T)=>(await s(R,T)).thread;return{list:async()=>(await o(ke.comments,{cache:"no-store"})).threads,create:R=>H(ke.commentsCreate,{input:R}),reply:(R,T)=>H(ke.commentsReply,{threadId:R,text:T}),setResolved:(R,T)=>H(ke.commentsResolve,{threadId:R,resolved:T}),move:(R,T,q)=>H(ke.commentsMove,{threadId:R,anchor:T,...q?{location:q}:{}}),remove:async(R,T)=>{await s(ke.commentsRemove,{threadId:R,...T?{messageId:T}:{}})},sendToAgent:R=>H(ke.commentsSend,{threadId:R}),onChange:R=>c("comments",R)}},async history(){const{stores:v}=await x();if(!v?.history)return null;const H=(R,T)=>({n:String(R),...T===void 0?{}:{path:T}});return{list:()=>o(ke.history,{cache:"no-store"}),files:async R=>(await o(ke.historyFiles,{cache:"no-store"},H(R))).files,read:async(R,T)=>new TextDecoder().decode(await N(ke.historyFile,H(R,T))),readBytes:(R,T)=>N(ke.historyFile,H(R,T)),diff:(R,T)=>o(ke.historyDiff,{cache:"no-store"},H(R,T)),restore:(R,T)=>s(ke.historyRestore,{n:R,...T?{paths:T}:{},client:t}),dismissNotice:async R=>{await s(ke.historyDismiss,{id:R})},onChange:R=>c("history",R)}},async mcp(){const{viewer:v}=await x();return v.role!=="owner"?null:{callTool:async(J,R,T,q)=>{const z=q?.signal;z?.throwIfAborted();const L={server:J,tool:R,args:T,...q?.timeoutMs===void 0?{}:{timeoutMs:q.timeoutMs}};try{return await o(ke.mcpCall,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(L),...z?{signal:z}:{}})}catch(K){throw z?.aborted?z.reason:K}},listTools:J=>o(ke.mcpTools,{cache:"no-store"},J===void 0?void 0:{server:J})}},async downloads(){return{save:async({name:H,data:J})=>o(ke.downloads,{method:"POST",headers:{"content-type":J.type||"application/octet-stream"},body:J},{name:H})}}};function G(v){return N(ke.file,{path:v})}async function N(v,H){let J;try{J=await fetch(n(v,H),{cache:"no-store"})}catch(R){throw new zc("unavailable",R instanceof Error?R.message:String(R))}if(!J.ok)throw await Mk(J);return new Uint8Array(await J.arrayBuffer())}return{get(v){const H=k[v];return H?H():null}}}const uz="[Artifact comment sent to agent]",Bz="[Artifact edit request sent to agent]",dz="[Artifact task finished]",Qz=1,Ez=1,fz=/^[a-z][a-z0-9]{0,23}$/,hz="may not have run: the artifact was updated before this call was answered",pz=["quickstart","list","publish","read","open","call","adopt","delete","share"],wz=["get","list","query","set","update","delete","str_replace","batch"],yz=["read","reply","resolve","reopen","wait"],Dz=["share","export"],mz={type:"object",properties:{action:{type:"string",enum:pz,description:"What to do. Omitted: publish."},intent:{type:"string",description:"quickstart: what is being made (design, design-system, slides, whiteboard, document, data, other), or a few words about it."},scope:{type:"string",enum:["types","mine","all"],description:"list: the installed types, this session's and this workspace's artifacts (default), or every artifact."},type:{type:"string",description:"list: only artifacts of this type (an id, or open-artifact://type/<id>)."},query:{type:"string",description:"list: only artifacts whose title contains this text."},limit:{type:"integer",description:"list: how many to return (default 50, at most 200)."},cursor:{type:"string",description:"list: the next_cursor of the previous page."},type_url:{type:"string",description:"publish without url: the type to create from (open-artifact://type/<id>, from quickstart). read without url: the type to describe."},title:{type:"string",description:"publish without url: the new artifact's name."},folder:{type:"string",description:"publish without url, or adopt: where the artifact's folder goes (absolute, or relative to the workspace). Default <workspace>/artifacts/<slug>."},url:{type:"string",description:"An artifact: open-artifact://artifact/<id>, as publish returned it."},files:{type:"object",additionalProperties:!0,description:'publish with url: files to write under the artifact root, as {"rel/path": "text"} or {"rel/path": {"content": "...", "encoding": "base64"}}; null deletes.'},if_match:{type:"object",additionalProperties:!0,description:'publish with url: {"rel/path": sha256 | null | "*"}. Write only while the file still has the sha256 you read, does not exist (null), or anyway ("*"). One mismatch writes nothing and returns the current versions.'},check:{type:"boolean",description:"publish with url: run the type's check action after writing; its result comes back as check."},open:{type:"string",enum:["after_first_write","now"],description:"publish without url: after_first_write opens the page in your app once your first write lands; now opens it at once. Where your app cannot show pages by itself the result says so: open view_url in your app's built-in browser, if you have one."},related:{type:"boolean",description:"quickstart: list existing artifacts the recommended type can build on, such as design systems (default true)."},path:{type:"string",description:"read: one file or folder under the root (omitted: the record and the file list)."},paths:{type:"array",items:{type:"string"},description:"read: several files under the root at once."},name:{type:"string",description:"call: the action's name (check, upload, ...; read with url lists them)."},args:{type:"object",additionalProperties:!0,description:"call: the action's arguments. upload: {file: absolute path, name?, group?}."},panel:{type:"string",enum:Dz,description:"open: also open the page's Share panel (share), for the person to share it on the network, or its Export tab (export), for them to download a file."}}},Sz={type:"object",properties:{action:{type:"string",enum:wz},url:{type:"string",description:"The artifact (open-artifact://artifact/<id>)."},collection:{type:"string"},doc_id:{type:"string"},path:{type:"string",description:"collection/doc_id, instead of the two."},data:{type:"object",additionalProperties:!0,description:"set / update: the document's fields."},file_path:{type:"string",description:"set / update: a JSON file holding the fields, instead of data."},if_match:{description:'set / update / delete / str_replace: the sha256 get returned (write only if unchanged), null (only if it does not exist) or "*" (replace whatever is there).'},field:{type:"string",description:"str_replace: the text field, as a dot path (body, notes.text)."},old:{type:"string",description:"str_replace: the passage to replace; it must occur exactly once."},new:{type:"string",description:"str_replace: the passage that replaces it."},where:{type:"array",items:{type:"object",additionalProperties:!0},description:"query: [{field, op, value}], all must hold. op: ==, !=, <, <=, >, >=, in, not-in (up to 30 values), array-contains."},order_by:{type:"object",additionalProperties:!0,description:'query: {field, dir: "asc" | "desc"}.'},limit:{type:"integer",description:"list / query: how many documents (default 100, at most 1000)."},cursor:{type:"string",description:"list / query: the next_cursor of the previous page."},out_file:{type:"string",description:"get / list / query: write the result to this JSON file (absolute, or relative to the workspace) and return only its path and counts."},writes:{type:"array",items:{type:"object",additionalProperties:!0},description:"batch: [{op: set|update|delete|str_replace, path | collection+doc_id, data | file_path, if_match?, field?, old?, new?}], at most 500."}},required:["action","url"]},bz={type:"object",properties:{action:{type:"string",enum:yz},url:{type:"string",description:"The artifact (open-artifact://artifact/<id>). wait: optional."},thread_id:{type:"string",description:'reply / resolve / reopen: the thread (after ";thread=" in the message).'},text:{type:"string",description:"reply: the answer."},resolve:{type:"boolean",description:"reply: resolve the thread too."},all:{type:"boolean",description:"read: resolved threads too."},since:{type:"string",description:"read: only threads with a message at or after this time (ISO 8601)."},acknowledge_duplicate:{type:"boolean",description:"reply: send the same text as your last reply in this thread again, on purpose."},timeout_ms:{type:"number",description:"wait: how long (default 600000)."}},required:["action"]},xk={Artifact:mz,ArtifactData:Sz,ArtifactComments:bz},kz={Artifact:["Make and change artifacts: typed folders of files that open as live pages the person can view, edit, comment on and export. Actions:","- quickstart {intent}: call first for a new artifact; recommends a type and returns the call that creates it.",'- list {scope: "mine" | "all" | "types", type?, query?}: find existing artifacts, or the installed types.',"- publish {type_url, title, folder?, open?}: create an artifact; the result carries its root folder and the type's instructions. publish {url, files, if_match?, check?}: write files when you have no file tools of your own.","- read {url, path? | paths?}: the artifact's record, files and actions, or some of its files with their sha256. read {type_url}: a type's instructions, before creating.",`- open {url, panel?}: show it to the person in the computer's browser (or the app, when it shows pages), once its content is written. When your app has a built-in browser, open view_url there instead. panel "share" or "export" opens its Share panel or Export tab for them.`,"- call {url, name, args?}: run one of the type's actions (check, upload, ...). A long one answers {task, pending: true}; its result comes later as a message.","- adopt {url | folder}: take over an artifact, or add an existing folder. Only when the person asks.","- share {url}: whether it is shared on the local network, and its links. Only the person changes that, in the page's Share panel.","- delete {url}: forget an artifact; its folder stays. Only when the person asks."].join(`
35
35
  `),ArtifactData:'Read and write the document store of an artifact whose type keeps one (its instructions say so). get, list and query read documents with their sha256; set, update, delete, str_replace and batch write them. update merges fields, and {"__delete__": true} removes one; str_replace changes one passage of a long text field. Replacing or deleting an existing document needs if_match: the sha256 you read, or "*". Your writes show live on open pages.',ArtifactComments:`Comments the person leaves on their artifact's page, kept in the artifact's own folder on this computer (no outside service). read lists the threads; reply answers one (thread_id is after ";thread=" in the message), with resolve: true when it is done; resolve and reopen change a thread's state. A thread sent to you is the person asking for your answer in it, so replying there is what they asked for. Answer only threads sent to you, in one or two lines. wait blocks until the next message for this session: use it only when nothing else can wake you.`},Mz={Artifact:{title:"Artifact",openWorldHint:!1},ArtifactData:{title:"Artifact data",openWorldHint:!1},ArtifactComments:{title:"Artifact comments",destructiveHint:!1,openWorldHint:!1}};Object.keys(xk).map(A=>({name:A,description:kz[A],inputSchema:xk[A],annotations:Mz[A]}));const xz=300,Nz=12,Nk=["Artifact","ArtifactData","ArtifactComments"];function cs(A,e=xz){const t=String(A??"").replace(/[<>]/g,"").replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1).trimEnd()}…`:t}function Gz(A){const e=cs(A,Number.MAX_SAFE_INTEGER),t=e.search(/[.!?。!?](\s|$)/);return t>=0?e.slice(0,t+1):e}function Rz(A){const e=cs(A,24);return/^[a-z0-9]{1,5}$/i.test(e)?e.toUpperCase():e}const Gk=A=>!A||/[.!?。!?…]$/.test(A)?A:`${A}.`;function vz(A,e=!1){const t=cs(A.title,80)||A.id;if(e)return`- ${A.id}: ${t}`;const n=cs(A.when)||cs(Gz(A.description)),o=(A.exports??[]).map(Rz).filter(Boolean),s=[Gk(t),Gk(n),o.length?`Exports: ${o.join(", ")}.`:""].filter(Boolean);return`- ${A.id}: ${s.join(" ")}`}const Fz="Open Artifact lets you make artifacts: typed folders of files (a slide deck, a design canvas, a whiteboard, a data dashboard and more) that open as live pages the person can view, edit, comment on and export. You make and change them with the Artifact, ArtifactData and ArtifactComments tools.",Kz=`<where_output_goes>
36
36
  Decide where your output will live before you make anything.
37
37
  - Something the person will read once and move on from (an answer, an explanation, a summary, a short report) goes in your reply, however long it is. A diagram or chart that explains your answer goes in the reply too, when you can show one there.