@qfei-design/make-ai-assistant 0.2.9 → 0.2.11

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 (38) hide show
  1. package/PUBLIC_API.md +17 -23
  2. package/README.md +12 -24
  3. package/capabilities.json +36 -9
  4. package/dist/conversation-CZfbgCXd.js +1111 -0
  5. package/dist/conversation-Cvh-IVRV.cjs +1 -0
  6. package/dist/core/conversation-management.d.ts +212 -0
  7. package/dist/core/conversation.d.ts +34 -2
  8. package/dist/core/index.d.ts +2 -0
  9. package/dist/core/response-state.d.ts +8 -0
  10. package/dist/index.cjs +1 -1
  11. package/dist/index.mjs +4 -4
  12. package/dist/make-app/protocol.d.ts +27 -0
  13. package/dist/make-app/stream.d.ts +20 -0
  14. package/dist/make-app.cjs +1 -1
  15. package/dist/make-app.d.ts +46 -11
  16. package/dist/make-app.mjs +698 -259
  17. package/dist/make-console.cjs +1 -1
  18. package/dist/make-console.mjs +1 -1
  19. package/dist/react/conversation-controls.d.ts +20 -0
  20. package/dist/react/use-attachments.d.ts +33 -0
  21. package/dist/react/use-conversation-manager.d.ts +35 -0
  22. package/dist/react.cjs +4 -4
  23. package/dist/react.mjs +2000 -845
  24. package/dist/sse.cjs +1 -1
  25. package/dist/sse.mjs +1 -1
  26. package/dist/styles.css +428 -13
  27. package/docs/backend-contract.md +8 -21
  28. package/docs/make-app-integration.md +80 -0
  29. package/examples/make-app/README.md +11 -0
  30. package/examples/make-app/index.html +5 -0
  31. package/examples/make-app/main.tsx +34 -0
  32. package/examples/make-app/style.css +4 -0
  33. package/examples/make-app/transport.ts +163 -0
  34. package/examples/make-app/vite.config.ts +7 -0
  35. package/package.json +10 -2
  36. package/recipes.json +36 -13
  37. package/dist/conversation-B7eGUXi-.js +0 -727
  38. package/dist/conversation-Cv1wdvCR.cjs +0 -1
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const N=require("./sse.cjs"),E=require("./conversation-Cv1wdvCR.cjs"),M=4e3,x=200,U=30,P=1e3,K={AI_AGENT_UNAVAILABLE:"当前应用没有可用 Agent。",AI_AUTH_EXPIRED:"登录已失效,请重新登录。",AI_AUTH_REQUIRED:"登录已失效,请重新登录。",AI_FORBIDDEN:"当前账号无权使用该 AI 助手。",AI_RUN_FAILED:"本次 AI 处理失败,请重试。",AI_UPSTREAM_ERROR:"AI 服务暂时不可用,请稍后重试。"},O=new Set(["AI_AGENT_UNAVAILABLE","AI_AUTH_EXPIRED","AI_AUTH_REQUIRED","AI_FORBIDDEN"]),y=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),A=(e,t,n=E.MAKE_AI_CONVERSATION_LIMITS.identifierCharacters)=>{if(typeof e!="string"||!e.trim()||E.countCodePointsUpTo(e,n)>n)throw new Error(`Invalid Make Console assistant response: ${t}`);return e},S=(e,t)=>{if(!(e==null||e===""))return A(e,t)},m=(e,t)=>{if(!Number.isSafeInteger(e)||Number(e)<0)throw new Error(`Invalid Make Console assistant response: ${t}`);return Number(e)},k=()=>new DOMException("Aborted","AbortError"),u=e=>{if(e?.aborted)throw k()},q=(e,t)=>(u(t),e===0?Promise.resolve():new Promise((n,i)=>{const f=setTimeout(()=>{t?.removeEventListener("abort",I),n()},e),I=()=>{clearTimeout(f),t?.removeEventListener("abort",I),i(k())};t?.addEventListener("abort",I,{once:!0})})),F=e=>{if(!y(e)||!Array.isArray(e.agents)||e.agents.length>1e3)throw new Error("Invalid Make Console assistant response: agents");const t=new Set;return e.agents.map(n=>{if(!y(n))throw new Error("Invalid Make Console assistant response: agent");const i=A(n.agentID,"agentID");if(t.has(i))throw new Error("Invalid Make Console assistant response: duplicate agentID");return t.add(i),{agentID:i,...typeof n.name=="string"&&n.name.trim()?{name:A(n.name,"agent name")}:{},status:A(n.status,"agent status")}})},V=e=>{if(!y(e))throw new Error("Invalid Make Console assistant response: session");return{nextSeq:m(e.nextSeq,"nextSeq"),sessionID:A(e.sessionID,"sessionID")}},H=e=>{if(!y(e))throw new Error("Invalid Make Console assistant response: sent message");const t=S(e.runID,"runID"),n=S(e.mergedInto,"mergedInto");if(t&&n)throw new Error("Invalid Make Console assistant response: multiple Run IDs");return{effectiveRunID:t??n,seq:m(e.seq,"seq"),sessionID:A(e.sessionID,"sessionID")}},$=e=>{if(!y(e)||!Array.isArray(e.blocks)||e.blocks.length>1e3)throw new Error("Invalid Make Console assistant response: payload blocks");let t="";for(const n of e.blocks)if(!(!y(n)||n.kind!=="text"||typeof n.text!="string")&&(t+=n.text,E.countCodePointsUpTo(t,E.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)>E.MAKE_AI_CONVERSATION_LIMITS.messageCharacters))throw new Error("Invalid Make Console assistant response: message text budget");return A(t,"message text",E.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)},T=(e,t)=>{if(!Array.isArray(e)||e.length>t)throw new Error("Invalid Make Console assistant response: durable events");const n=new Set;return e.flatMap(i=>{if(!y(i))throw new Error("Invalid Make Console assistant response: durable event");const c=m(i.seq,"event seq");if(n.has(c))throw new Error("Invalid Make Console assistant response: duplicate event seq");n.add(c);const f=typeof i.type=="string"?i.type:"",I=y(i.actor)&&typeof i.actor.kind=="string"?i.actor.kind:"";return!(f==="user_message")&&!(f==="message"&&I==="agent")?[]:[{actorKind:I,content:$(i.payload),runID:S(i.runID,"event runID"),seq:c,type:f}]})},G=(e,t,n)=>{const i=T(e,n);let c=0;return{messages:i.map(I=>{if(c+=E.countCodePointsUpTo(I.content,E.MAKE_AI_CONVERSATION_LIMITS.historyCharacters-c),c>E.MAKE_AI_CONVERSATION_LIMITS.historyCharacters)throw new Error("Invalid Make Console assistant response: history text budget");return{artifacts:[],content:I.content,id:`console-${t}-${String(I.seq)}`,role:I.type==="user_message"?"user":"assistant"}}),threadId:t}},B=()=>{const e=[],t=[];return{next:()=>{const c=e.shift();return c?Promise.resolve(c):new Promise(f=>t.push(f))},push:c=>{const f=t.shift();f?f(c):e.push(c)}}},X=(e,t)=>{if(E.countCodePointsUpTo(e.data,t)>t)throw new Error("Make Console assistant SSE event exceeds maxEventCharacters");try{const n=JSON.parse(e.data);if(!y(n))throw new Error("invalid data");return n}catch{throw new Error("Invalid Make Console assistant SSE JSON")}},b=(e,t)=>{if(!Number.isInteger(e)||e<1)throw new Error(`${t} must be a positive integer`)},Q=(e,t,n)=>T(e,t).find(c=>c.type==="message"&&c.actorKind==="agent"&&(n===void 0||c.runID===n)),j=e=>{const t=e.historyLimit??x,n=e.maxEventCharacters??N.DEFAULT_MAX_SSE_EVENT_CHARACTERS,i=e.maxPollingAttempts??U,c=e.pollIntervalMs??P,f=e.wait??q;if(!Number.isInteger(t)||t<1||t>200)throw new Error("historyLimit must be an integer between 1 and 200");if(b(n,"maxEventCharacters"),b(i,"maxPollingAttempts"),!Number.isInteger(c)||c<0)throw new Error("pollIntervalMs must be a non-negative integer");const I=async(s,r)=>{u(r?.signal),console.info("[make-ai-assistant] Make Console Agent lookup start",{appId:s.app.id});const o=F(await e.listAgents({appKey:s.app.id},{signal:r?.signal}));u(r?.signal);const l=o.filter(g=>g.status==="enabled"),p=e.selectAgent?e.selectAgent(l,s):l[0]?.agentID,d=l.find(g=>g.agentID===p);if(!d)throw new Error("当前应用没有可用 Agent");return console.info("[make-ai-assistant] Make Console Agent lookup success",{appId:s.app.id,enabledAgentCount:l.length}),d},C=async(s,r,o)=>(u(o?.signal),V(await e.getOrCreateSession({agentID:r,appKey:s.app.id},{signal:o?.signal}))),_=async s=>{for(let r=1;r<=i;r+=1){u(s.signal);const o=await e.loadEvents({agentID:s.agentID,appKey:s.appKey,from:s.from,limit:t,sessionID:s.sessionID},{signal:s.signal});u(s.signal);const l=Q(o,t,s.effectiveRunID);if(l)return l;r<i&&await f(c,s.signal)}throw new Error("Make Console assistant durable response unavailable")},L=async function*(s){u(s.signal);const r=B(),o=e.eventSourceFactory({agentID:s.agentID,appKey:s.appKey,cursor:"0-0",runID:s.effectiveRunID,sessionID:s.sessionID},{withCredentials:!0});let l=!1;const p=a=>{l||(l=!0,r.push(a))},d=new Map,g=(a,h)=>{const D=v=>{if(!l)try{h(X(v,n),v)}catch(R){p({type:"error",error:R})}};d.set(a,D),o.addEventListener(a,D)};g("ready",a=>{if(typeof a.after!="string")throw new Error("Invalid Make Console assistant response: ready cursor")}),g("run-output",a=>{if(A(a.runID,"SSE runID")!==s.effectiveRunID)throw new Error("Invalid Make Console assistant response: SSE runID mismatch");m(a.sequence,"SSE sequence");const h=A(a.type,"SSE output type");if(h==="output_text.delta"){if(typeof a.delta!="string")throw new Error("Invalid Make Console assistant response: SSE delta");r.push({type:"event",event:{type:"message.delta",messageId:s.messageId,delta:a.delta}})}else h==="response.completed"?p({type:"completed"}):h==="response.failed"&&p({type:"failed",code:A(a.failureCode,"failureCode")})}),g("fallback",a=>{if(a.reason!=="stream_unavailable")throw new Error("Invalid Make Console assistant response: fallback reason");p({type:"fallback"})}),o.onerror=()=>{l||o.readyState!==void 0&&o.readyState!==2||p({type:"error",error:new Error("Make Console assistant SSE disconnected")})};const w=()=>p({type:"error",error:k()});s.signal?.addEventListener("abort",w,{once:!0}),s.signal?.aborted&&w();try{for(;;){const a=await r.next();if(a.type==="event")yield a.event;else{if(a.type==="completed"||a.type==="fallback")return a.type;if(a.type==="failed")return yield{type:"error",code:a.code,message:K[a.code]??"本次 AI 处理失败,请重试。",retryable:!O.has(a.code),requestId:s.effectiveRunID},"failed";throw a.error}}}finally{l=!0,s.signal?.removeEventListener("abort",w),o.onerror=null;for(const[a,h]of d)o.removeEventListener(a,h);o.close()}};return{features:{history:!0,newConversation:!1,regeneration:!1,remoteCancellation:!1},async loadConversation(s,r){console.info("[make-ai-assistant] Make Console history load start",{appId:s.app.id});try{const o=await I(s,r),l=await C(s,o.agentID,r),p=Math.max(0,l.nextSeq-t),d=await e.loadEvents({agentID:o.agentID,appKey:s.app.id,from:p,limit:t,sessionID:l.sessionID},{signal:r?.signal});u(r?.signal);const g=G(d,l.sessionID,t);return console.info("[make-ai-assistant] Make Console history load success",{appId:s.app.id,messageCount:g.messages.length}),g}catch(o){throw(r?.signal?.aborted?console.info:console.error)(r?.signal?.aborted?"[make-ai-assistant] Make Console history load cancelled":"[make-ai-assistant] Make Console history load failed",{appId:s.app.id,errorType:o instanceof Error?o.name:typeof o}),o}},async*run(s,r){console.info("[make-ai-assistant] Make Console run start",{appId:s.context.app.id});try{const o=s.message.content.trim();if(!o||E.countCodePointsUpTo(o,M)>M)throw new Error(o?"Console 消息不能超过 4000 个字符":"Console 消息不能为空");const l=await I(s.context,r),p=await C(s.context,l.agentID,r);u(r?.signal);const d=H(await e.sendMessage({agentID:l.agentID,appKey:s.context.app.id,text:o},{signal:r?.signal}));if(u(r?.signal),d.sessionID!==p.sessionID)throw new Error("Invalid Make Console assistant response: sessionID mismatch");const g=d.effectiveRunID??`${d.sessionID}:${String(d.seq)}`,w=`assistant:${g}`;if(yield{type:"message.start",runId:g,messageId:w},d.effectiveRunID){const D=yield*L({agentID:l.agentID,appKey:s.context.app.id,effectiveRunID:d.effectiveRunID,messageId:w,sessionID:d.sessionID,signal:r?.signal});if(D==="failed")return;D==="fallback"&&console.info("[make-ai-assistant] Make Console SSE fallback",{appId:s.context.app.id})}const a=await _({agentID:l.agentID,appKey:s.context.app.id,effectiveRunID:d.effectiveRunID,from:d.seq+1,sessionID:d.sessionID,signal:r?.signal});yield{type:"message.replace",messageId:w,content:a.content},yield{type:"message.complete",messageId:w},yield{type:"run.complete",runId:g,threadId:d.sessionID},console.info("[make-ai-assistant] Make Console run complete",{appId:s.context.app.id})}catch(o){throw r?.signal?.aborted?console.info("[make-ai-assistant] Make Console run cancelled",{appId:s.context.app.id}):console.error("[make-ai-assistant] Make Console run failed",{appId:s.context.app.id,errorType:o instanceof Error?o.name:typeof o}),o}}}};exports.MAKE_CONSOLE_MESSAGE_CHARACTERS=M;exports.createMakeConsoleAssistantTransport=j;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const N=require("./sse.cjs"),E=require("./conversation-Cvh-IVRV.cjs"),M=4e3,x=200,U=30,P=1e3,K={AI_AGENT_UNAVAILABLE:"当前应用没有可用 Agent。",AI_AUTH_EXPIRED:"登录已失效,请重新登录。",AI_AUTH_REQUIRED:"登录已失效,请重新登录。",AI_FORBIDDEN:"当前账号无权使用该 AI 助手。",AI_RUN_FAILED:"本次 AI 处理失败,请重试。",AI_UPSTREAM_ERROR:"AI 服务暂时不可用,请稍后重试。"},O=new Set(["AI_AGENT_UNAVAILABLE","AI_AUTH_EXPIRED","AI_AUTH_REQUIRED","AI_FORBIDDEN"]),y=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),A=(e,t,n=E.MAKE_AI_CONVERSATION_LIMITS.identifierCharacters)=>{if(typeof e!="string"||!e.trim()||E.countCodePointsUpTo(e,n)>n)throw new Error(`Invalid Make Console assistant response: ${t}`);return e},S=(e,t)=>{if(!(e==null||e===""))return A(e,t)},m=(e,t)=>{if(!Number.isSafeInteger(e)||Number(e)<0)throw new Error(`Invalid Make Console assistant response: ${t}`);return Number(e)},k=()=>new DOMException("Aborted","AbortError"),u=e=>{if(e?.aborted)throw k()},q=(e,t)=>(u(t),e===0?Promise.resolve():new Promise((n,i)=>{const f=setTimeout(()=>{t?.removeEventListener("abort",I),n()},e),I=()=>{clearTimeout(f),t?.removeEventListener("abort",I),i(k())};t?.addEventListener("abort",I,{once:!0})})),F=e=>{if(!y(e)||!Array.isArray(e.agents)||e.agents.length>1e3)throw new Error("Invalid Make Console assistant response: agents");const t=new Set;return e.agents.map(n=>{if(!y(n))throw new Error("Invalid Make Console assistant response: agent");const i=A(n.agentID,"agentID");if(t.has(i))throw new Error("Invalid Make Console assistant response: duplicate agentID");return t.add(i),{agentID:i,...typeof n.name=="string"&&n.name.trim()?{name:A(n.name,"agent name")}:{},status:A(n.status,"agent status")}})},V=e=>{if(!y(e))throw new Error("Invalid Make Console assistant response: session");return{nextSeq:m(e.nextSeq,"nextSeq"),sessionID:A(e.sessionID,"sessionID")}},H=e=>{if(!y(e))throw new Error("Invalid Make Console assistant response: sent message");const t=S(e.runID,"runID"),n=S(e.mergedInto,"mergedInto");if(t&&n)throw new Error("Invalid Make Console assistant response: multiple Run IDs");return{effectiveRunID:t??n,seq:m(e.seq,"seq"),sessionID:A(e.sessionID,"sessionID")}},$=e=>{if(!y(e)||!Array.isArray(e.blocks)||e.blocks.length>1e3)throw new Error("Invalid Make Console assistant response: payload blocks");let t="";for(const n of e.blocks)if(!(!y(n)||n.kind!=="text"||typeof n.text!="string")&&(t+=n.text,E.countCodePointsUpTo(t,E.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)>E.MAKE_AI_CONVERSATION_LIMITS.messageCharacters))throw new Error("Invalid Make Console assistant response: message text budget");return A(t,"message text",E.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)},T=(e,t)=>{if(!Array.isArray(e)||e.length>t)throw new Error("Invalid Make Console assistant response: durable events");const n=new Set;return e.flatMap(i=>{if(!y(i))throw new Error("Invalid Make Console assistant response: durable event");const c=m(i.seq,"event seq");if(n.has(c))throw new Error("Invalid Make Console assistant response: duplicate event seq");n.add(c);const f=typeof i.type=="string"?i.type:"",I=y(i.actor)&&typeof i.actor.kind=="string"?i.actor.kind:"";return!(f==="user_message")&&!(f==="message"&&I==="agent")?[]:[{actorKind:I,content:$(i.payload),runID:S(i.runID,"event runID"),seq:c,type:f}]})},G=(e,t,n)=>{const i=T(e,n);let c=0;return{messages:i.map(I=>{if(c+=E.countCodePointsUpTo(I.content,E.MAKE_AI_CONVERSATION_LIMITS.historyCharacters-c),c>E.MAKE_AI_CONVERSATION_LIMITS.historyCharacters)throw new Error("Invalid Make Console assistant response: history text budget");return{artifacts:[],content:I.content,id:`console-${t}-${String(I.seq)}`,role:I.type==="user_message"?"user":"assistant"}}),threadId:t}},B=()=>{const e=[],t=[];return{next:()=>{const c=e.shift();return c?Promise.resolve(c):new Promise(f=>t.push(f))},push:c=>{const f=t.shift();f?f(c):e.push(c)}}},X=(e,t)=>{if(E.countCodePointsUpTo(e.data,t)>t)throw new Error("Make Console assistant SSE event exceeds maxEventCharacters");try{const n=JSON.parse(e.data);if(!y(n))throw new Error("invalid data");return n}catch{throw new Error("Invalid Make Console assistant SSE JSON")}},b=(e,t)=>{if(!Number.isInteger(e)||e<1)throw new Error(`${t} must be a positive integer`)},Q=(e,t,n)=>T(e,t).find(c=>c.type==="message"&&c.actorKind==="agent"&&(n===void 0||c.runID===n)),j=e=>{const t=e.historyLimit??x,n=e.maxEventCharacters??N.DEFAULT_MAX_SSE_EVENT_CHARACTERS,i=e.maxPollingAttempts??U,c=e.pollIntervalMs??P,f=e.wait??q;if(!Number.isInteger(t)||t<1||t>200)throw new Error("historyLimit must be an integer between 1 and 200");if(b(n,"maxEventCharacters"),b(i,"maxPollingAttempts"),!Number.isInteger(c)||c<0)throw new Error("pollIntervalMs must be a non-negative integer");const I=async(s,r)=>{u(r?.signal),console.info("[make-ai-assistant] Make Console Agent lookup start",{appId:s.app.id});const o=F(await e.listAgents({appKey:s.app.id},{signal:r?.signal}));u(r?.signal);const l=o.filter(g=>g.status==="enabled"),p=e.selectAgent?e.selectAgent(l,s):l[0]?.agentID,d=l.find(g=>g.agentID===p);if(!d)throw new Error("当前应用没有可用 Agent");return console.info("[make-ai-assistant] Make Console Agent lookup success",{appId:s.app.id,enabledAgentCount:l.length}),d},C=async(s,r,o)=>(u(o?.signal),V(await e.getOrCreateSession({agentID:r,appKey:s.app.id},{signal:o?.signal}))),_=async s=>{for(let r=1;r<=i;r+=1){u(s.signal);const o=await e.loadEvents({agentID:s.agentID,appKey:s.appKey,from:s.from,limit:t,sessionID:s.sessionID},{signal:s.signal});u(s.signal);const l=Q(o,t,s.effectiveRunID);if(l)return l;r<i&&await f(c,s.signal)}throw new Error("Make Console assistant durable response unavailable")},L=async function*(s){u(s.signal);const r=B(),o=e.eventSourceFactory({agentID:s.agentID,appKey:s.appKey,cursor:"0-0",runID:s.effectiveRunID,sessionID:s.sessionID},{withCredentials:!0});let l=!1;const p=a=>{l||(l=!0,r.push(a))},d=new Map,g=(a,h)=>{const D=v=>{if(!l)try{h(X(v,n),v)}catch(R){p({type:"error",error:R})}};d.set(a,D),o.addEventListener(a,D)};g("ready",a=>{if(typeof a.after!="string")throw new Error("Invalid Make Console assistant response: ready cursor")}),g("run-output",a=>{if(A(a.runID,"SSE runID")!==s.effectiveRunID)throw new Error("Invalid Make Console assistant response: SSE runID mismatch");m(a.sequence,"SSE sequence");const h=A(a.type,"SSE output type");if(h==="output_text.delta"){if(typeof a.delta!="string")throw new Error("Invalid Make Console assistant response: SSE delta");r.push({type:"event",event:{type:"message.delta",messageId:s.messageId,delta:a.delta}})}else h==="response.completed"?p({type:"completed"}):h==="response.failed"&&p({type:"failed",code:A(a.failureCode,"failureCode")})}),g("fallback",a=>{if(a.reason!=="stream_unavailable")throw new Error("Invalid Make Console assistant response: fallback reason");p({type:"fallback"})}),o.onerror=()=>{l||o.readyState!==void 0&&o.readyState!==2||p({type:"error",error:new Error("Make Console assistant SSE disconnected")})};const w=()=>p({type:"error",error:k()});s.signal?.addEventListener("abort",w,{once:!0}),s.signal?.aborted&&w();try{for(;;){const a=await r.next();if(a.type==="event")yield a.event;else{if(a.type==="completed"||a.type==="fallback")return a.type;if(a.type==="failed")return yield{type:"error",code:a.code,message:K[a.code]??"本次 AI 处理失败,请重试。",retryable:!O.has(a.code),requestId:s.effectiveRunID},"failed";throw a.error}}}finally{l=!0,s.signal?.removeEventListener("abort",w),o.onerror=null;for(const[a,h]of d)o.removeEventListener(a,h);o.close()}};return{features:{history:!0,newConversation:!1,regeneration:!1,remoteCancellation:!1},async loadConversation(s,r){console.info("[make-ai-assistant] Make Console history load start",{appId:s.app.id});try{const o=await I(s,r),l=await C(s,o.agentID,r),p=Math.max(0,l.nextSeq-t),d=await e.loadEvents({agentID:o.agentID,appKey:s.app.id,from:p,limit:t,sessionID:l.sessionID},{signal:r?.signal});u(r?.signal);const g=G(d,l.sessionID,t);return console.info("[make-ai-assistant] Make Console history load success",{appId:s.app.id,messageCount:g.messages.length}),g}catch(o){throw(r?.signal?.aborted?console.info:console.error)(r?.signal?.aborted?"[make-ai-assistant] Make Console history load cancelled":"[make-ai-assistant] Make Console history load failed",{appId:s.app.id,errorType:o instanceof Error?o.name:typeof o}),o}},async*run(s,r){console.info("[make-ai-assistant] Make Console run start",{appId:s.context.app.id});try{const o=s.message.content.trim();if(!o||E.countCodePointsUpTo(o,M)>M)throw new Error(o?"Console 消息不能超过 4000 个字符":"Console 消息不能为空");const l=await I(s.context,r),p=await C(s.context,l.agentID,r);u(r?.signal);const d=H(await e.sendMessage({agentID:l.agentID,appKey:s.context.app.id,text:o},{signal:r?.signal}));if(u(r?.signal),d.sessionID!==p.sessionID)throw new Error("Invalid Make Console assistant response: sessionID mismatch");const g=d.effectiveRunID??`${d.sessionID}:${String(d.seq)}`,w=`assistant:${g}`;if(yield{type:"message.start",runId:g,messageId:w},d.effectiveRunID){const D=yield*L({agentID:l.agentID,appKey:s.context.app.id,effectiveRunID:d.effectiveRunID,messageId:w,sessionID:d.sessionID,signal:r?.signal});if(D==="failed")return;D==="fallback"&&console.info("[make-ai-assistant] Make Console SSE fallback",{appId:s.context.app.id})}const a=await _({agentID:l.agentID,appKey:s.context.app.id,effectiveRunID:d.effectiveRunID,from:d.seq+1,sessionID:d.sessionID,signal:r?.signal});yield{type:"message.replace",messageId:w,content:a.content},yield{type:"message.complete",messageId:w},yield{type:"run.complete",runId:g,threadId:d.sessionID},console.info("[make-ai-assistant] Make Console run complete",{appId:s.context.app.id})}catch(o){throw r?.signal?.aborted?console.info("[make-ai-assistant] Make Console run cancelled",{appId:s.context.app.id}):console.error("[make-ai-assistant] Make Console run failed",{appId:s.context.app.id,errorType:o instanceof Error?o.name:typeof o}),o}}}};exports.MAKE_CONSOLE_MESSAGE_CHARACTERS=M;exports.createMakeConsoleAssistantTransport=j;
@@ -1,5 +1,5 @@
1
1
  import { DEFAULT_MAX_SSE_EVENT_CHARACTERS as N } from "./sse.mjs";
2
- import { c as D, M as m } from "./conversation-B7eGUXi-.js";
2
+ import { c as D, M as m } from "./conversation-CZfbgCXd.js";
3
3
  const _ = 4e3, U = 200, P = 30, K = 1e3, F = {
4
4
  AI_AGENT_UNAVAILABLE: "当前应用没有可用 Agent。",
5
5
  AI_AUTH_EXPIRED: "登录已失效,请重新登录。",
@@ -0,0 +1,20 @@
1
+ import { type RefObject } from "react";
2
+ import type { AssistantMessage, AssistantTransport, MakeAssistantHostContext } from "../core/index.js";
3
+ import { type ConversationManager } from "./use-conversation-manager.js";
4
+ export declare function ConversationControls({ id, manager, onDismiss, onNewConversation, triggerRef, }: {
5
+ id: string;
6
+ manager: ConversationManager;
7
+ onDismiss: () => void;
8
+ onNewConversation?: () => void;
9
+ triggerRef: RefObject<HTMLButtonElement | null>;
10
+ }): import("react").JSX.Element;
11
+ export declare function MessageFeedback({ message, manager, }: {
12
+ message: AssistantMessage;
13
+ manager: ConversationManager;
14
+ }): import("react").JSX.Element | null;
15
+ export declare function MessageAttachments({ message, context, transport, chatId, }: {
16
+ message: AssistantMessage;
17
+ context: MakeAssistantHostContext;
18
+ transport: AssistantTransport;
19
+ chatId: string;
20
+ }): import("react").JSX.Element;
@@ -0,0 +1,33 @@
1
+ import { type Ref } from "react";
2
+ import type { AssistantContentPart, AssistantTransport, AssistantUpload, MakeAssistantHostContext } from "../core/index.js";
3
+ import { type ConversationManager } from "./use-conversation-manager.js";
4
+ export interface AttachmentDraft {
5
+ id: string;
6
+ fileId: string;
7
+ name: string;
8
+ size: number;
9
+ status: "queued" | "uploading" | "completing" | "ready" | "paused" | "failed";
10
+ progress: number;
11
+ error?: string;
12
+ upload?: AssistantUpload;
13
+ }
14
+ export declare function useAttachments(context: MakeAssistantHostContext, transport: AssistantTransport, manager: ConversationManager): {
15
+ enabled: boolean;
16
+ drafts: AttachmentDraft[];
17
+ parts: AssistantContentPart[];
18
+ pending: boolean;
19
+ add: (files: File[]) => void;
20
+ retry: (id: string) => void;
21
+ remove: (id: string) => void;
22
+ pause: (id: string) => void | undefined;
23
+ clear: () => void;
24
+ };
25
+ export declare function AttachmentComposer({ attachments, onOpenChange, open, triggerRef, }: {
26
+ attachments: ReturnType<typeof useAttachments>;
27
+ onOpenChange: (open: boolean) => void;
28
+ open: boolean;
29
+ triggerRef: Ref<HTMLButtonElement>;
30
+ }): import("react").JSX.Element;
31
+ export declare function AttachmentDraftList({ attachments, }: {
32
+ attachments: ReturnType<typeof useAttachments>;
33
+ }): import("react").JSX.Element | null;
@@ -0,0 +1,35 @@
1
+ import { type Dispatch, type SetStateAction } from "react";
2
+ import { type AssistantChat, type AssistantConversationState, type AssistantContentPart, type AssistantFeedbackWrite, type AssistantMessage, type AssistantTransport, type MakeAssistantHostContext } from "../core/index.js";
3
+ export declare const newRequestId: () => `${string}-${string}-${string}-${string}-${string}`;
4
+ export declare const operationError: (error: unknown) => string;
5
+ export declare function useConversationManager(context: MakeAssistantHostContext, transport: AssistantTransport): {
6
+ enabled: boolean;
7
+ state: AssistantConversationState;
8
+ setState: Dispatch<SetStateAction<AssistantConversationState>>;
9
+ chats: AssistantChat[];
10
+ chat: AssistantChat | undefined;
11
+ listCursor: string;
12
+ historyMore: boolean;
13
+ historyTruncated: boolean;
14
+ loading: boolean;
15
+ busy: boolean;
16
+ error: string | undefined;
17
+ cancelling: string[];
18
+ feedbackBusy: string[];
19
+ refresh: (cursor?: string) => Promise<void>;
20
+ select: (next: AssistantChat) => Promise<void>;
21
+ create: () => Promise<void>;
22
+ ensureChat: () => Promise<AssistantChat>;
23
+ send: (content: string, parts?: AssistantContentPart[]) => Promise<void>;
24
+ retry: () => Promise<void>;
25
+ stop: (responseId?: string | undefined) => Promise<void>;
26
+ update: (patch: {
27
+ title?: string;
28
+ pinned?: boolean;
29
+ }, target?: AssistantChat | undefined) => Promise<void>;
30
+ remove: (target?: AssistantChat | undefined) => Promise<void>;
31
+ feedback: (message: AssistantMessage, rating: AssistantFeedbackWrite["rating"], reason?: string, comment?: string) => Promise<boolean | undefined>;
32
+ moreHistory: () => Promise<void>;
33
+ setError: Dispatch<SetStateAction<string | undefined>>;
34
+ };
35
+ export type ConversationManager = ReturnType<typeof useConversationManager>;
package/dist/react.cjs CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),l=require("react"),G=require("./index.cjs"),p=require("./conversation-Cv1wdvCR.cjs"),gt=e=>e?.trim()||void 0,P=(e,s)=>gt(e)??s,Oe=e=>{const s=gt(e?.primary);if(s)return{"--make-ai-theme-primary":s,"--make-ai-theme-primary-hover":P(e?.primaryHover,"color-mix(in srgb, var(--make-ai-theme-primary) 84%, #15233d)"),"--make-ai-theme-on-primary":P(e?.onPrimary,"#fcfcff"),"--make-ai-theme-bg":P(e?.background,"color-mix(in srgb, var(--make-ai-theme-primary) 2%, #fcfcff)"),"--make-ai-theme-surface":P(e?.surface,"color-mix(in srgb, var(--make-ai-theme-primary) 4%, var(--make-ai-theme-bg))"),"--make-ai-theme-surface-strong":P(e?.surfaceStrong,"color-mix(in srgb, var(--make-ai-theme-primary) 8%, var(--make-ai-theme-bg))"),"--make-ai-theme-text":P(e?.text,"color-mix(in srgb, var(--make-ai-theme-primary) 12%, #252631)"),"--make-ai-theme-text-secondary":P(e?.textSecondary,"color-mix(in srgb, var(--make-ai-theme-text) 74%, var(--make-ai-theme-primary))"),"--make-ai-theme-border":P(e?.border,"color-mix(in srgb, var(--make-ai-theme-primary) 14%, var(--make-ai-theme-bg))"),"--make-ai-theme-overlay":P(e?.overlay,"color-mix(in srgb, var(--make-ai-theme-text) 88%, var(--make-ai-theme-primary))"),"--make-ai-theme-on-overlay":P(e?.onOverlay,"#fcfcff")}},dt=(e,s)=>!s||!l.isValidElement(e)||typeof e.type!="string"?e:l.cloneElement(e,{style:{...e.props.style,...s}});function xt({artifact:e,context:s,fallback:a,onAction:r,onActionError:n,registry:i,theme:c}){const m=Oe(c),x=G.resolveArtifactTemplate(i,e,s);if(!x){const M=a?a(e):t.jsxs("section",{className:"make-ai-artifact make-ai-artifact--unsupported",role:"status",children:[t.jsx("strong",{children:"暂不支持展示此结果"}),t.jsxs("span",{children:["结果类型:",e.kind]})]});return dt(M,m)}const f={context:s,onAction:r,onActionError:n,theme:c,themeStyle:m},T=x.template.render(e,s,f);return dt(T,m)}const Y=(e,s,a)=>{if(e==null||e==="")return"—";if(typeof e=="boolean")return e?"是":"否";if(typeof e!="number")return`${e}${s?.unit??""}`;const r=s?.precision,n={maximumFractionDigits:r??2,minimumFractionDigits:r};s?.style==="currency"&&s.currency?(n.style="currency",n.currency=s.currency):s?.style==="percent"&&(n.style="percent");try{const i=s?.style==="percent"?e/100:e;return`${new Intl.NumberFormat(a,n).format(i)}${s?.unit??""}`}catch{return`${e}${s?.unit??""}`}},_t=e=>{let s=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(const r of e)s=Math.min(s,r),a=Math.max(a,r);return Number.isFinite(s)&&Number.isFinite(a)?{min:s,max:a}:{min:0,max:0}},vt=(e,s,a)=>{if(!a.onAction)return;const r=i=>{console.error("[make-ai-assistant] host action error handler failed",{actionId:e.id,artifactId:s.artifact.id,errorType:i instanceof Error?i.name:typeof i,intent:e.intent})},n=i=>{if(a.onActionError){try{Promise.resolve(a.onActionError(i,e,s)).catch(r)}catch(c){r(c)}return}console.error("[make-ai-assistant] host action failed",{actionId:e.id,artifactId:s.artifact.id,errorType:i instanceof Error?i.name:typeof i,intent:e.intent})};try{Promise.resolve(a.onAction(e,s)).catch(n)}catch(i){n(i)}},ce=(e,s)=>e.actions?.length&&s.onAction?t.jsx("div",{className:"make-ai-artifact__actions",children:e.actions.map(a=>t.jsxs("button",{className:`make-ai-artifact__action make-ai-artifact__action--${a.appearance??"link"}`,type:"button",onClick:()=>vt(a,{artifact:e,context:s.context},s),children:[a.label,t.jsx("span",{"aria-hidden":"true",children:"→"})]},a.id))}):null,le=(e,s,a="",r)=>t.jsxs("section",{"aria-label":e.title??`${e.kind} result`,className:`make-ai-artifact ${a}`.trim(),"data-artifact-density":e.presentation?.density,"data-artifact-kind":e.kind,style:r,children:[e.title?t.jsx("h4",{className:"make-ai-artifact__title",children:e.title}):null,e.summary?t.jsx("p",{className:"make-ai-artifact__summary",children:e.summary}):null,s]}),Bt=({artifact:e,renderContext:s})=>{const a=e.data.delta,r=a?Y(a.value,a.format==="percent"?{style:"percent"}:void 0,s.context.locale):void 0;return le(e,t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"make-ai-artifact__metric-value",children:Y(e.data.value,e.data.format,s.context.locale)}),a?t.jsxs("div",{className:`make-ai-artifact__delta make-ai-artifact__delta--${a.direction??"flat"}`,children:[t.jsx("span",{"aria-hidden":"true",children:a.direction==="up"?"↗":a.direction==="down"?"↘":"→"}),t.jsx("span",{children:r}),a.label?t.jsx("span",{children:a.label}):null]}):null,e.data.context?t.jsx("p",{className:"make-ai-artifact__context",children:e.data.context}):null,ce(e,s)]}),"make-ai-artifact--metric",s.themeStyle)},Ut=({artifact:e,renderContext:s})=>le(e,t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"make-ai-artifact__comparison",children:e.data.items.map(a=>t.jsxs("div",{className:"make-ai-artifact__comparison-item",children:[t.jsx("span",{children:a.label}),t.jsx("strong",{children:Y(a.value,a.format,s.context.locale)}),a.hint?t.jsx("small",{children:a.hint}):null]},a.id))}),ce(e,s)]}),"make-ai-artifact--comparison",s.themeStyle),zt=({artifact:e,renderContext:s})=>{const a=e.data.series.flatMap(c=>c.points.map(m=>m.y)),{max:r,min:n}=_t(a),i=r-n||1;return le(e,t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"make-ai-artifact__trend",children:e.data.series.map(c=>t.jsxs("div",{className:"make-ai-artifact__trend-series",children:[t.jsx("div",{className:"make-ai-artifact__trend-label",children:c.label}),t.jsx("div",{className:"make-ai-artifact__trend-bars",children:c.points.map((m,x)=>{const f=18+(m.y-n)/i*70;return t.jsxs("div",{className:"make-ai-artifact__trend-point",children:[t.jsx("span",{"aria-label":`${m.x}: ${Y(m.y,c.format,s.context.locale)}`,className:"make-ai-artifact__trend-bar",role:"img",style:{height:`${f}%`},title:`${m.x}: ${Y(m.y,c.format,s.context.locale)}`}),t.jsx("small",{children:m.x})]},`${m.x}-${x}`)})})]},c.id))}),ce(e,s)]}),"make-ai-artifact--trend",s.themeStyle)},qt=({artifact:e,renderContext:s})=>{const{max:a}=_t(e.data.items.map(n=>Math.abs(n.value))),r=Math.max(a,1);return le(e,t.jsxs(t.Fragment,{children:[t.jsx("ol",{className:"make-ai-artifact__ranking",children:e.data.items.map((n,i)=>t.jsxs("li",{children:[t.jsx("span",{className:"make-ai-artifact__rank",children:i+1}),t.jsxs("span",{className:"make-ai-artifact__ranking-label",children:[t.jsx("span",{children:n.label}),n.description?t.jsx("small",{children:n.description}):null]}),t.jsx("span",{className:"make-ai-artifact__ranking-track","aria-hidden":"true",children:t.jsx("span",{style:{width:`${Math.abs(n.value)/r*100}%`}})}),t.jsx("strong",{children:Y(n.value,n.format,s.context.locale)})]},n.id))}),ce(e,s)]}),"make-ai-artifact--ranking",s.themeStyle)},Xt=(e,s)=>s.action??{id:`open-${s.id}`,label:s.title??s.id,intent:"open-record",target:{entityKey:e.data.entity.key,recordId:s.id}},Yt=({artifact:e,renderContext:s})=>le(e,t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"make-ai-artifact__record-list",children:e.data.records.length===0?t.jsx("p",{className:"make-ai-artifact__empty",children:"没有符合条件的记录"}):e.data.records.map(a=>{const r=Xt(e,a),n=t.jsxs(t.Fragment,{children:[t.jsx("strong",{children:a.title??a.id}),t.jsx("span",{className:"make-ai-artifact__record-values",children:e.data.columns.map(i=>t.jsxs("span",{children:[t.jsx("small",{children:i.label}),Y(a.values[i.key],i.format,s.context.locale)]},i.key))}),s.onAction?t.jsx("span",{"aria-hidden":"true",children:"›"}):null]});return s.onAction?t.jsx("button",{className:"make-ai-artifact__record",type:"button",onClick:()=>vt(r,{artifact:e,context:s.context},s),children:n},a.id):t.jsx("div",{className:"make-ai-artifact__record",children:n},a.id)})}),e.data.total!==void 0?t.jsxs("p",{className:"make-ai-artifact__record-total",children:["共 ",e.data.total," 条"]}):null,ce(e,s)]}),"make-ai-artifact--record-list",s.themeStyle),Gt=({artifact:e,renderContext:s})=>le(e,t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:`make-ai-artifact__notice make-ai-artifact__notice--${e.data.tone}`,children:[t.jsx("span",{"aria-hidden":"true",children:e.data.tone==="success"?"✓":e.data.tone==="warning"?"!":e.data.tone==="danger"?"×":"i"}),t.jsx("p",{children:e.data.body})]}),ce(e,s)]}),"make-ai-artifact--notice",s.themeStyle),oe=(e,s,a)=>({id:e,kinds:[s],priority:0,render:a}),Zt=[oe("platform.metric.default","metric",(e,s,a)=>t.jsx(Bt,{artifact:e,renderContext:a})),oe("platform.comparison.default","comparison",(e,s,a)=>t.jsx(Ut,{artifact:e,renderContext:a})),oe("platform.trend.default","trend",(e,s,a)=>t.jsx(zt,{artifact:e,renderContext:a})),oe("platform.ranking.default","ranking",(e,s,a)=>t.jsx(qt,{artifact:e,renderContext:a})),oe("platform.record-list.default","record-list",(e,s,a)=>t.jsx(Yt,{artifact:e,renderContext:a})),oe("platform.notice.default","notice",(e,s,a)=>t.jsx(Gt,{artifact:e,renderContext:a}))],jt=G.createArtifactTemplateRegistry(Zt).templates,yt=(e=jt)=>G.createArtifactTemplateRegistry(e),Qt=e=>`${e}-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,Jt="Make",es=["总结当前页面数据","找出需要关注的记录","列出我有权限查看的数据对象"],At=(e,s)=>s??`${e?.trim()||Jt} AI 助手`,ts=e=>e??es,ss=/^只读分析\s*[·•]\s*/u,as=(e,s)=>e?.trim().replace(ss,"").trim()||`当前对象:${s??"未命名应用"}`,ns=480,kt=1024,rs=.72,mt=16,V=16,xe=8,Ce=(e,s,a)=>Math.min(Math.max(e,Math.min(s,a)),a),is=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0,os=(e,s,a)=>{const r=Math.min(kt,a*rs);return Math.max(e,Math.min(s??r,a))},ut=(e,s,a)=>Math.min(Math.max(e,s),Math.max(s,a)),cs=(e,s,a,r)=>{const n=Math.min(Math.max(s.width,1),Math.max(1,r-V*2)),i=Math.min(Math.max(s.height,1),Math.max(1,a-V*2)),c=e.left+e.width/2,m=e.top+e.height/2,f=[{left:e.right+xe,placement:"right",top:m-i/2},{left:e.left-xe-n,placement:"left",top:m-i/2},{left:c-n/2,placement:"bottom",top:e.bottom+xe},{left:c-n/2,placement:"top",top:e.top-xe-i}].find(({left:T,top:M})=>T>=V&&M>=V&&T+n<=r-V&&M+i<=a-V);return f||{left:ut(c-n/2,V,r-V-n),placement:"bottom",top:ut(e.bottom+xe,V,a-V-i)}},ls=e=>typeof e=="number"?Number.isFinite(e)?`${e}px`:void 0:e?.trim()||void 0;class k extends Error{}const Te=(e,s)=>{if(!(typeof e!="object"||e===null))return e[s]},ds=e=>{const s=Te(e,"status");return typeof s=="number"?s:Te(Te(e,"response"),"status")},ms=e=>{const s=Te(e,"code"),a=ds(e),r=e instanceof Error?e.message:"",n=[s,r].filter(x=>typeof x=="string").join(" ").toLowerCase(),c=globalThis.navigator?.onLine===!1||/network|fetch|timeout|offline|connection|网络|连接|超时/.test(n),m=typeof a=="number"&&a>=500||/server|service|服务器|服务异常/.test(n);return c?{actionLabel:"重新连接",description:"请检查网络后再试。",kind:"network",label:"网络连接",title:"网络连接不可用"}:m?{actionLabel:"重新加载",description:"服务暂时未能响应,请稍后重试。",kind:"service",label:"服务异常",title:"服务暂时不可用"}:{actionLabel:"重新加载",description:"请稍后重试;若问题持续出现,请联系管理员。",kind:"unknown",label:"加载异常",title:"暂时无法加载对话"}},pt=e=>{try{const s=e?.return?.();if(!s)return;Promise.resolve(s).catch(a=>{console.error("[make-ai-assistant] transport iterator close failed",{errorType:a instanceof Error?a.name:typeof a})})}catch(s){console.error("[make-ai-assistant] transport iterator close failed",{errorType:s instanceof Error?s.name:typeof s})}},us=async e=>{if(globalThis.navigator?.clipboard?.writeText){await globalThis.navigator.clipboard.writeText(e);return}if(typeof document>"u"||!document.body)throw new Error("Clipboard API is unavailable");const s=document.createElement("textarea");s.value=e,s.setAttribute("readonly",""),s.style.position="fixed",s.style.inset="0 auto auto 0",s.style.opacity="0",document.body.append(s),s.select();const a=document.execCommand("copy");if(s.remove(),!a)throw new Error("Clipboard copy failed")},It=()=>t.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[t.jsx("path",{d:"M12 2.8c.5 4.4 2.8 6.8 7.2 7.2-4.4.5-6.8 2.8-7.2 7.2-.5-4.4-2.8-6.8-7.2-7.2 4.4-.5 6.8-2.8 7.2-7.2Z"}),t.jsx("path",{d:"M18.3 16.1c.2 1.8 1.2 2.8 3 3-1.8.2-2.8 1.2-3 3-.2-1.8-1.2-2.8-3-3 1.8-.2 2.8-1.2 3-3Z"})]}),ps=()=>t.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:t.jsx("path",{d:"m6 6 12 12M18 6 6 18"})}),hs=()=>t.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[t.jsx("path",{d:"M8 8h10v12H8z"}),t.jsx("path",{d:"M6 16H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),fs=()=>t.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[t.jsx("path",{d:"M20 11a8 8 0 0 0-14.7-4.4L4 8"}),t.jsx("path",{d:"M4 4v4h4"}),t.jsx("path",{d:"M4 13a8 8 0 0 0 14.7 4.4L20 16"}),t.jsx("path",{d:"M20 20v-4h-4"})]}),gs=()=>t.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[t.jsx("circle",{cx:"12",cy:"12",r:"8"}),t.jsx("path",{d:"M9.8 9.4a2.35 2.35 0 1 1 3.93 1.73c-.96.86-1.73 1.42-1.73 2.87"}),t.jsx("path",{d:"M12 17h.01"})]}),xs=()=>t.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[t.jsx("path",{d:"M12 4v11"}),t.jsx("path",{d:"m7 10 5 5 5-5"}),t.jsx("path",{d:"M5 20h14"})]}),_s=()=>t.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:t.jsx("path",{d:"M12 5v14M5 12h14"})}),vs=()=>t.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[t.jsx("path",{d:"m4 4 17 8-17 8 3-8-3-8Z"}),t.jsx("path",{d:"M7 12h14"})]}),bt=()=>t.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[t.jsx("path",{d:"M20 11a8 8 0 0 0-14.7-4.4L4 8"}),t.jsx("path",{d:"M4 4v4h4"}),t.jsx("path",{d:"M4 13a8 8 0 0 0 14.7 4.4L20 16"}),t.jsx("path",{d:"M20 20v-4h-4"})]}),js=()=>t.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[t.jsx("circle",{cx:"12",cy:"12",r:"8"}),t.jsx("path",{d:"M12 8v4.5"}),t.jsx("path",{d:"M12 16h.01"})]}),Me=({className:e=""})=>t.jsx("span",{className:`make-ai-assistant__avatar ${e}`.trim(),"aria-hidden":"true",children:t.jsx(It,{})}),ys=({src:e})=>e?t.jsx("span",{className:"make-ai-assistant__user-avatar","aria-hidden":"true",children:t.jsx("img",{alt:"",src:e})}):null,As=({userAvatarUrl:e,userName:s})=>{const a=s?.trim();return!a&&!e?null:t.jsxs("div",{className:"make-ai-assistant__message-identity",children:[a?t.jsx("span",{className:"make-ai-assistant__message-sender",children:a}):null,t.jsx(ys,{src:e})]})},$e=e=>{const s=e.trim();if(!(!s.startsWith("|")||!s.endsWith("|")))return s.slice(1,-1).split("|").map(a=>a.trim())},ks=e=>e.length>0&&e.every(s=>/^:?-{3,}:?$/.test(s)),Is=(e,s)=>{const a=$e(e[s]??""),r=$e(e[s+1]??"");if(!a||!r||a.length!==r.length||!ks(r))return;const n=[];let i=s+2;for(;i<e.length;){const c=$e(e[i]??"");if(!c||c.length!==a.length)break;n.push(c),i+=1}return{headers:a,lastIndex:i-1,rows:n}},bs=e=>{const s=[],a=[],r=[],n=[],i=e.replace(/\r\n?/g,`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),r=require("react"),Ce=require("./index.cjs"),x=require("./conversation-Cvh-IVRV.cjs"),Dt=t=>t?.trim()||void 0,fe=(t,s)=>Dt(t)??s,mt=t=>{const s=Dt(t?.primary);if(s)return{"--make-ai-theme-primary":s,"--make-ai-theme-primary-hover":fe(t?.primaryHover,"color-mix(in srgb, var(--make-ai-theme-primary) 84%, #15233d)"),"--make-ai-theme-on-primary":fe(t?.onPrimary,"#fcfcff"),"--make-ai-theme-bg":fe(t?.background,"color-mix(in srgb, var(--make-ai-theme-primary) 2%, #fcfcff)"),"--make-ai-theme-surface":fe(t?.surface,"color-mix(in srgb, var(--make-ai-theme-primary) 4%, var(--make-ai-theme-bg))"),"--make-ai-theme-surface-strong":fe(t?.surfaceStrong,"color-mix(in srgb, var(--make-ai-theme-primary) 8%, var(--make-ai-theme-bg))"),"--make-ai-theme-text":fe(t?.text,"color-mix(in srgb, var(--make-ai-theme-primary) 12%, #252631)"),"--make-ai-theme-text-secondary":fe(t?.textSecondary,"color-mix(in srgb, var(--make-ai-theme-text) 74%, var(--make-ai-theme-primary))"),"--make-ai-theme-border":fe(t?.border,"color-mix(in srgb, var(--make-ai-theme-primary) 14%, var(--make-ai-theme-bg))"),"--make-ai-theme-overlay":fe(t?.overlay,"color-mix(in srgb, var(--make-ai-theme-text) 88%, var(--make-ai-theme-primary))"),"--make-ai-theme-on-overlay":fe(t?.onOverlay,"#fcfcff")}},Tt=(t,s)=>!s||!r.isValidElement(t)||typeof t.type!="string"?t:r.cloneElement(t,{style:{...t.props.style,...s}});function Ot({artifact:t,context:s,fallback:a,onAction:o,onActionError:n,registry:c,theme:d}){const g=mt(d),p=Ce.resolveArtifactTemplate(c,t,s);if(!p){const E=a?a(t):e.jsxs("section",{className:"make-ai-artifact make-ai-artifact--unsupported",role:"status",children:[e.jsx("strong",{children:"暂不支持展示此结果"}),e.jsxs("span",{children:["结果类型:",t.kind]})]});return Tt(E,g)}const f={context:s,onAction:o,onActionError:n,theme:d,themeStyle:g},j=p.template.render(t,s,f);return Tt(j,g)}const Re=(t,s,a)=>{if(t==null||t==="")return"—";if(typeof t=="boolean")return t?"是":"否";if(typeof t!="number")return`${t}${s?.unit??""}`;const o=s?.precision,n={maximumFractionDigits:o??2,minimumFractionDigits:o};s?.style==="currency"&&s.currency?(n.style="currency",n.currency=s.currency):s?.style==="percent"&&(n.style="percent");try{const c=s?.style==="percent"?t/100:t;return`${new Intl.NumberFormat(a,n).format(c)}${s?.unit??""}`}catch{return`${t}${s?.unit??""}`}},Ft=t=>{let s=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(const o of t)s=Math.min(s,o),a=Math.max(a,o);return Number.isFinite(s)&&Number.isFinite(a)?{min:s,max:a}:{min:0,max:0}},Pt=(t,s,a)=>{if(!a.onAction)return;const o=c=>{console.error("[make-ai-assistant] host action error handler failed",{actionId:t.id,artifactId:s.artifact.id,errorType:c instanceof Error?c.name:typeof c,intent:t.intent})},n=c=>{if(a.onActionError){try{Promise.resolve(a.onActionError(c,t,s)).catch(o)}catch(d){o(d)}return}console.error("[make-ai-assistant] host action failed",{actionId:t.id,artifactId:s.artifact.id,errorType:c instanceof Error?c.name:typeof c,intent:t.intent})};try{Promise.resolve(a.onAction(t,s)).catch(n)}catch(c){n(c)}},Fe=(t,s)=>t.actions?.length&&s.onAction?e.jsx("div",{className:"make-ai-artifact__actions",children:t.actions.map(a=>e.jsxs("button",{className:`make-ai-artifact__action make-ai-artifact__action--${a.appearance??"link"}`,type:"button",onClick:()=>Pt(a,{artifact:t,context:s.context},s),children:[a.label,e.jsx("span",{"aria-hidden":"true",children:"→"})]},a.id))}):null,Pe=(t,s,a="",o)=>e.jsxs("section",{"aria-label":t.title??`${t.kind} result`,className:`make-ai-artifact ${a}`.trim(),"data-artifact-density":t.presentation?.density,"data-artifact-kind":t.kind,style:o,children:[t.title?e.jsx("h4",{className:"make-ai-artifact__title",children:t.title}):null,t.summary?e.jsx("p",{className:"make-ai-artifact__summary",children:t.summary}):null,s]}),ls=({artifact:t,renderContext:s})=>{const a=t.data.delta,o=a?Re(a.value,a.format==="percent"?{style:"percent"}:void 0,s.context.locale):void 0;return Pe(t,e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"make-ai-artifact__metric-value",children:Re(t.data.value,t.data.format,s.context.locale)}),a?e.jsxs("div",{className:`make-ai-artifact__delta make-ai-artifact__delta--${a.direction??"flat"}`,children:[e.jsx("span",{"aria-hidden":"true",children:a.direction==="up"?"↗":a.direction==="down"?"↘":"→"}),e.jsx("span",{children:o}),a.label?e.jsx("span",{children:a.label}):null]}):null,t.data.context?e.jsx("p",{className:"make-ai-artifact__context",children:t.data.context}):null,Fe(t,s)]}),"make-ai-artifact--metric",s.themeStyle)},ds=({artifact:t,renderContext:s})=>Pe(t,e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"make-ai-artifact__comparison",children:t.data.items.map(a=>e.jsxs("div",{className:"make-ai-artifact__comparison-item",children:[e.jsx("span",{children:a.label}),e.jsx("strong",{children:Re(a.value,a.format,s.context.locale)}),a.hint?e.jsx("small",{children:a.hint}):null]},a.id))}),Fe(t,s)]}),"make-ai-artifact--comparison",s.themeStyle),us=({artifact:t,renderContext:s})=>{const a=t.data.series.flatMap(d=>d.points.map(g=>g.y)),{max:o,min:n}=Ft(a),c=o-n||1;return Pe(t,e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"make-ai-artifact__trend",children:t.data.series.map(d=>e.jsxs("div",{className:"make-ai-artifact__trend-series",children:[e.jsx("div",{className:"make-ai-artifact__trend-label",children:d.label}),e.jsx("div",{className:"make-ai-artifact__trend-bars",children:d.points.map((g,p)=>{const f=18+(g.y-n)/c*70;return e.jsxs("div",{className:"make-ai-artifact__trend-point",children:[e.jsx("span",{"aria-label":`${g.x}: ${Re(g.y,d.format,s.context.locale)}`,className:"make-ai-artifact__trend-bar",role:"img",style:{height:`${f}%`},title:`${g.x}: ${Re(g.y,d.format,s.context.locale)}`}),e.jsx("small",{children:g.x})]},`${g.x}-${p}`)})})]},d.id))}),Fe(t,s)]}),"make-ai-artifact--trend",s.themeStyle)},ms=({artifact:t,renderContext:s})=>{const{max:a}=Ft(t.data.items.map(n=>Math.abs(n.value))),o=Math.max(a,1);return Pe(t,e.jsxs(e.Fragment,{children:[e.jsx("ol",{className:"make-ai-artifact__ranking",children:t.data.items.map((n,c)=>e.jsxs("li",{children:[e.jsx("span",{className:"make-ai-artifact__rank",children:c+1}),e.jsxs("span",{className:"make-ai-artifact__ranking-label",children:[e.jsx("span",{children:n.label}),n.description?e.jsx("small",{children:n.description}):null]}),e.jsx("span",{className:"make-ai-artifact__ranking-track","aria-hidden":"true",children:e.jsx("span",{style:{width:`${Math.abs(n.value)/o*100}%`}})}),e.jsx("strong",{children:Re(n.value,n.format,s.context.locale)})]},n.id))}),Fe(t,s)]}),"make-ai-artifact--ranking",s.themeStyle)},hs=(t,s)=>s.action??{id:`open-${s.id}`,label:s.title??s.id,intent:"open-record",target:{entityKey:t.data.entity.key,recordId:s.id}},fs=({artifact:t,renderContext:s})=>Pe(t,e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"make-ai-artifact__record-list",children:t.data.records.length===0?e.jsx("p",{className:"make-ai-artifact__empty",children:"没有符合条件的记录"}):t.data.records.map(a=>{const o=hs(t,a),n=e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:a.title??a.id}),e.jsx("span",{className:"make-ai-artifact__record-values",children:t.data.columns.map(c=>e.jsxs("span",{children:[e.jsx("small",{children:c.label}),Re(a.values[c.key],c.format,s.context.locale)]},c.key))}),s.onAction?e.jsx("span",{"aria-hidden":"true",children:"›"}):null]});return s.onAction?e.jsx("button",{className:"make-ai-artifact__record",type:"button",onClick:()=>Pt(o,{artifact:t,context:s.context},s),children:n},a.id):e.jsx("div",{className:"make-ai-artifact__record",children:n},a.id)})}),t.data.total!==void 0?e.jsxs("p",{className:"make-ai-artifact__record-total",children:["共 ",t.data.total," 条"]}):null,Fe(t,s)]}),"make-ai-artifact--record-list",s.themeStyle),ps=({artifact:t,renderContext:s})=>Pe(t,e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`make-ai-artifact__notice make-ai-artifact__notice--${t.data.tone}`,children:[e.jsx("span",{"aria-hidden":"true",children:t.data.tone==="success"?"✓":t.data.tone==="warning"?"!":t.data.tone==="danger"?"×":"i"}),e.jsx("p",{children:t.data.body})]}),Fe(t,s)]}),"make-ai-artifact--notice",s.themeStyle),De=(t,s,a)=>({id:t,kinds:[s],priority:0,render:a}),vs=[De("platform.metric.default","metric",(t,s,a)=>e.jsx(ls,{artifact:t,renderContext:a})),De("platform.comparison.default","comparison",(t,s,a)=>e.jsx(ds,{artifact:t,renderContext:a})),De("platform.trend.default","trend",(t,s,a)=>e.jsx(us,{artifact:t,renderContext:a})),De("platform.ranking.default","ranking",(t,s,a)=>e.jsx(ms,{artifact:t,renderContext:a})),De("platform.record-list.default","record-list",(t,s,a)=>e.jsx(fs,{artifact:t,renderContext:a})),De("platform.notice.default","notice",(t,s,a)=>e.jsx(ps,{artifact:t,renderContext:a}))],Bt=Ce.createArtifactTemplateRegistry(vs).templates,zt=(t=Bt)=>Ce.createArtifactTemplateRegistry(t),Oe=()=>globalThis.crypto.randomUUID(),ht=t=>{const s=t,a=s?.status??s?.response?.status;return a===409?"数据已变化或对话仍在运行,请刷新后重试":a===401||s?.code==="AI_AUTH_REQUIRED"||s?.code==="AI_AUTH_EXPIRED"?"登录已失效,请重新登录":a===403?"当前账号无权访问该对话":a===404?"对话或回答已不可见,请刷新列表":s?.message?.startsWith("输入内容过长")?s.message:"操作未完成,请重试或刷新对话"};function gs(t,s){const a=s.features?.conversationManagement===!0,o=a?s.scopeKey?.(t)??t.app.id:"",n=r.useRef(o);n.current=o;const c=r.useRef(o),[d,g]=r.useState(x.createAssistantConversationState),p=r.useRef(d),f=i=>{const h=typeof i=="function"?i(p.current):i;p.current=h,g(h)},[j,E]=r.useState([]),[B,H]=r.useState(),y=r.useRef(void 0),[V,Q]=r.useState(""),[W,v]=r.useState(-1),[u,l]=r.useState(!1),[T,N]=r.useState(!1),[ae,R]=r.useState(a),[G,K]=r.useState(!1),[L,q]=r.useState(),[ne,re]=r.useState([]),[de,ye]=r.useState([]),be=r.useRef(new Set),X=r.useRef(new Map),k=r.useRef(0),b=r.useRef(0),P=r.useRef(0),Y=r.useRef(void 0),ee=r.useRef(void 0),Se=r.useRef(new Map),C=(i,h=o)=>b.current===i&&n.current===h,te=()=>{const i=new AbortController;return be.current.add(i),i},ie=i=>be.current.delete(i),ue=i=>{y.current=i,H(i)},je=()=>{for(const i of X.current.values())i.abort();X.current.clear()},J=i=>{i instanceof Error&&i.name==="AbortError"||(console.warn("[make-ai-assistant] conversation operation failed",{errorType:i instanceof Error?i.name:typeof i}),q(ht(i)))},ve=async i=>{if(!a||!s.listConversations)return;const h=b.current,_=++P.current,A=te();try{const w=await s.listConversations(t,{cursor:i},{signal:A.signal});if(!C(h)||A.signal.aborted||_!==P.current)return;E(S=>[...new Map([...i?S:[],...w.chats].map(I=>[I.chatId,I])).values()]),Q(w.nextCursor)}catch(w){C(h)&&!A.signal.aborted&&J(w)}finally{ie(A),C(h)&&R(!1)}},_e=async(i,h,_)=>{const A=b.current,w=k.current;let S;try{for await(const I of i){if(!C(A)||h.signal.aborted||w!==k.current||y.current?.chatId!==_)return;const z=x.parseAssistantEvent(I);if(z.type==="response.accepted"||z.type==="response.state"){S=z.responseId;const F=X.current.get(S);if(F&&F!==h){z.type==="response.accepted"&&f(O=>x.reduceAssistantEvent(O,z)),h.abort();return}X.current.set(S,h)}f(F=>x.reduceAssistantEvent(F,z)),z.type==="response.terminal"&&(re(F=>F.filter(O=>O!==z.responseId)),ve())}}catch(I){C(A)&&!h.signal.aborted&&w===k.current&&(J(I),S||f(z=>({...z,status:Object.values(z.responses??{}).some(F=>!x.isResponseTerminal(F.status))?"streaming":"error"})))}finally{S&&X.current.get(S)===h&&X.current.delete(S),ie(h)}},Xe=async(i,h,_,A)=>{if(!s.getResponse||!s.watchResponse)return;const w=new Set(i.filter(I=>I.role==="assistant"&&I.persistent).map(I=>I.responseId)),S=[...new Map(i.filter(I=>I.role==="user"&&I.responseId&&!w.has(I.responseId)).map(I=>[I.responseId,I.cursor??-1])).entries()].slice(-20);for(const[I,z]of S){if(!C(A)||_!==k.current)return;if(X.current.has(I))continue;const F=te();try{const O=await s.getResponse(t,{chatId:h,responseId:I},{signal:F.signal});if(!C(A)||F.signal.aborted||_!==k.current||X.current.has(I))continue;f(he=>x.reduceAssistantEvent(he,x.isResponseTerminal(O.status)?{type:"response.snapshot",snapshot:O}:{type:"response.state",chatId:h,responseId:I,status:O.status})),O.status==="failed"||O.status==="cancelled"?f(he=>x.reduceAssistantEvent(he,{type:"response.terminal",chatId:h,responseId:I,status:O.status})):(X.current.set(I,F),_e(s.watchResponse(t,{chatId:h,responseId:I,historyCursor:z},{signal:F.signal}),F,h))}catch(O){C(A)&&!F.signal.aborted&&J(O)}finally{X.current.get(I)!==F&&ie(F)}}},oe=async i=>{const h=++k.current,_=b.current,A=te();je(),q(void 0),R(!0),re([]),ee.current=void 0,ue(i),f({messages:[],status:"idle",threadId:i.chatId}),v(-1),l(!1),N(!1);try{const[w,S]=await Promise.all([s.getConversation(t,{chatId:i.chatId},{signal:A.signal}),s.loadConversation(t,{threadId:i.chatId,cursor:-1,signal:A.signal})]);if(!C(_)||A.signal.aborted||h!==k.current)return;if(w.chatId!==i.chatId||S.threadId!==i.chatId)throw new Error("Conversation mismatch");ue(w),f(x.createAssistantConversationState(S)),v(S.nextCursor??-1),l(S.hasMore??!1),Xe(S.messages,i.chatId,h,_)}catch(w){C(_)&&!A.signal.aborted&&h===k.current&&J(w)}finally{ie(A),C(_)&&h===k.current&&R(!1)}},me=async()=>{if(y.current)return y.current;if(Y.current??={requestId:Oe()},Y.current.promise)return Y.current.promise;const i=b.current,h=k.current,_=te(),A=Y.current;return K(!0),A.promise=s.createConversation(t,{requestId:A.requestId},{signal:_.signal}).then(w=>{if(!C(i)||_.signal.aborted||h!==k.current)throw Object.assign(new Error("Stale create"),{name:"AbortError"});return Y.current=void 0,ue(w),f({messages:[],status:"idle",threadId:w.chatId}),ve(),w}).finally(()=>{ie(_),A.promise=void 0,C(i)&&K(!1)}),A.promise},Ye=async()=>{if(!(G||Y.current?.promise)){k.current+=1,je(),ue(void 0),q(void 0),ee.current=void 0,f(x.createAssistantConversationState()),l(!1),v(-1);try{await me()}catch(i){J(i)}}},ke=async i=>{const h=te();ee.current=i,q(void 0),p.current.messages.some(_=>_.id===i.message.id)||f(_=>x.appendUserMessage(_,i.message)),await _e(s.run(i,{signal:h.signal}),h,i.threadId)},Ze=async(i,h)=>{if(!(!i.trim()&&!h?.length))try{const _=await me(),A={id:Oe(),content:i,...h?{parts:h}:{}};await ke({threadId:_.chatId,message:A,context:t,capabilities:{artifactSchemaVersions:[],artifactKinds:[],templates:[]}})}catch(_){J(_)}},Ie=async()=>{const i=ee.current;if(!i||i.threadId!==y.current?.chatId){y.current&&await oe(y.current);return}const h=p.current.messages.find(_=>_.id===i.message.id);if(h?.responseId&&s.watchResponse){const _=h.responseId;if(X.current.has(_))return;const A=te();X.current.set(_,A),q(void 0),await _e(s.watchResponse(t,{chatId:i.threadId,responseId:_,historyCursor:h.cursor},{signal:A.signal}),A,i.threadId)}else await ke(i)},Ae=async(i=p.current.activeRunId)=>{const h=y.current;if(!h||!i||!s.cancelResponse||ne.includes(i))return;const _=b.current,A=k.current,w=te();re(S=>[...S,i]),q(void 0);try{const S=await s.cancelResponse(t,{chatId:h.chatId,responseId:i},{signal:w.signal});if(!C(_)||A!==k.current)return;if(x.isResponseTerminal(S.status))f(I=>x.reduceAssistantEvent(I,{type:"response.snapshot",snapshot:S})),re(I=>I.filter(z=>z!==i));else if(!X.current.has(i)&&s.watchResponse){const I=te();X.current.set(i,I),_e(s.watchResponse(t,{chatId:h.chatId,responseId:i},{signal:I.signal}),I,h.chatId)}}catch(S){C(_)&&A===k.current&&(J(S),re(I=>I.filter(z=>z!==i)))}finally{ie(w)}},we=async(i,h=y.current)=>{if(!h||G)return;const _=b.current,A=te();K(!0),q(void 0);try{const w=await s.updateConversation(t,{chatId:h.chatId,expectedRevision:h.revision,...i},{signal:A.signal});if(!C(_))return;y.current?.chatId===w.chatId&&ue(w),await ve()}catch(w){if(C(_)){J(w);try{const S=await s.getConversation(t,{chatId:h.chatId},{signal:A.signal});C(_)&&y.current?.chatId===h.chatId&&ue(S)}catch{}ve()}}finally{ie(A),C(_)&&K(!1)}},Ge=async(i=y.current)=>{if(!i||G)return;const h=b.current,_=te();K(!0),q(void 0);try{if(await s.deleteConversation(t,{chatId:i.chatId,expectedRevision:i.revision},{signal:_.signal}),!C(h))return;y.current?.chatId===i.chatId&&(k.current+=1,je(),ue(void 0),f(x.createAssistantConversationState())),await ve()}catch(A){C(h)&&J(A)}finally{ie(_),C(h)&&K(!1)}},Ee=async(i,h,_="",A="")=>{const w=y.current;if(!w||!i.persistent||!s.setFeedback||de.includes(i.id))return;const S={chatId:w.chatId,messageId:i.id,rating:h,..._?{reason:_}:{},...A?{comment:A}:{}},I=Se.current.get(i.id),{requestId:z,...F}=I??{requestId:""},O=I&&JSON.stringify(F)===JSON.stringify(S)?I:{...S,requestId:Oe()};Se.current.set(i.id,O);const he=b.current,Be=k.current,ze=te();ye(ce=>[...ce,i.id]),q(void 0);try{const ce=await s.setFeedback(t,O,{signal:ze.signal});return!C(he)||Be!==k.current||Se.current.get(i.id)!==O?void 0:(f(Ne=>({...Ne,messages:Ne.messages.map(ge=>ge.id===i.id&&ce.revision>=(ge.feedback?.revision??0)?{...ge,feedback:ce}:ge)})),Se.current.delete(i.id),!0)}catch(ce){return C(he)&&Be===k.current&&J(ce),!1}finally{ie(ze),C(he)&&ye(ce=>ce.filter(Ne=>Ne!==i.id))}},Je=async()=>{if(!y.current||!u||ae)return;const i=b.current,h=k.current,_=y.current,A=te();R(!0);try{const w=await s.loadConversation(t,{threadId:_.chatId,cursor:W,signal:A.signal});if(!C(i)||h!==k.current)return;const S=x.createAssistantConversationState(w),I=[...new Map([...p.current.messages,...S.messages].map(O=>[O.id,O])).values()];let z=0;const F=[];for(const O of I.slice(-200).reverse()){if(z+=[...O.content].length,z>1e6)break;F.unshift(O)}F.length<I.length&&N(!0),f(O=>({...O,messages:F})),v(w.nextCursor??W),l(w.hasMore??!1),Xe(w.messages,_.chatId,h,i)}catch(w){C(i)&&J(w)}finally{ie(A),C(i)&&R(!1)}};r.useEffect(()=>(b.current+=1,c.current=o,Y.current=void 0,ee.current=void 0,Se.current.clear(),ue(void 0),E([]),Q(""),f(x.createAssistantConversationState()),q(void 0),R(a),K(!1),re([]),ye([]),a&&ve(),()=>{b.current+=1,k.current+=1;for(const i of be.current)i.abort();be.current.clear(),X.current.clear()}),[a,o,s]);const Te=c.current===o;return{enabled:a,state:Te?d:x.createAssistantConversationState(),setState:f,chats:Te?j:[],chat:Te?B:void 0,listCursor:V,historyMore:u,historyTruncated:T,loading:!Te||ae,busy:G,error:Te?L:void 0,cancelling:ne,feedbackBusy:de,refresh:ve,select:oe,create:Ye,ensureChat:me,send:Ze,retry:Ie,stop:Ae,update:we,remove:Ge,feedback:Ee,moreHistory:Je,setError:q}}const xs=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M5 5.5h14v10H9l-4 3v-13Z"}),e.jsx("path",{d:"M8 9h8M8 12h6"})]}),ys=()=>e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"M12 5v14M5 12h14"})});function bs({id:t,manager:s,onDismiss:a,onNewConversation:o,triggerRef:n}){const[c,d]=r.useState(""),[g,p]=r.useState(!1),f=r.useRef(null);return r.useEffect(()=>{d(s.chat?.title??""),p(!1)},[s.chat?.chatId,s.chat?.title]),r.useEffect(()=>{const j=E=>{const B=E.target;B instanceof Node&&(f.current?.contains(B)||n.current?.contains(B)||a())};return document.addEventListener("pointerdown",j),()=>{document.removeEventListener("pointerdown",j)}},[a,n]),e.jsxs("div",{"aria-label":"任务列表",className:"make-ai-assistant__conversation-controls",id:t,ref:f,role:"dialog",children:[e.jsxs("div",{className:"make-ai-assistant__conversation-heading",children:[e.jsx("span",{children:"最近对话"}),e.jsx("button",{"aria-label":"刷新任务列表",className:"make-ai-assistant__conversation-refresh",disabled:s.busy,type:"button",onClick:()=>{s.refresh()},children:"刷新"})]}),e.jsxs("nav",{"aria-label":"对话列表",className:"make-ai-assistant__conversation-list",children:[s.chats.map(j=>e.jsxs("div",{className:"make-ai-assistant__conversation-row",children:[e.jsxs("button",{type:"button","aria-pressed":s.chat?.chatId===j.chatId,onClick:()=>{a(),s.select(j)},children:[e.jsx(xs,{}),e.jsx("span",{children:j.title||"未命名对话"})]}),e.jsx("button",{type:"button",disabled:s.busy,"aria-label":`${j.pinned?"取消置顶":"置顶"} ${j.title}`,onClick:()=>{s.update({pinned:!j.pinned},j)},children:j.pinned?"★":"☆"})]},j.chatId)),!s.loading&&!s.chats.length?e.jsx("p",{children:"暂无对话,发送消息即可新建"}):null,s.listCursor?e.jsx("button",{className:"make-ai-assistant__conversation-more",type:"button",onClick:()=>{s.refresh(s.listCursor)},children:"更多对话"}):null]}),s.chat?e.jsxs("details",{className:"make-ai-assistant__conversation-management",children:[e.jsx("summary",{children:"管理当前对话"}),e.jsxs("div",{className:"make-ai-assistant__conversation-actions",children:[e.jsx("input",{"aria-label":"对话标题",maxLength:255,value:c,onChange:j=>d(j.currentTarget.value)}),e.jsx("button",{type:"button",disabled:s.busy||!c.trim(),onClick:()=>{s.update({title:c})},children:"保存标题"}),e.jsx("button",{type:"button",disabled:s.busy,onClick:()=>p(!0),children:"删除对话"}),g?e.jsxs("div",{role:"group","aria-label":"确认删除对话",children:[e.jsxs("span",{children:["删除“",s.chat.title,"”?"]}),e.jsx("button",{type:"button",disabled:s.busy,onClick:()=>{p(!1),s.remove()},children:"确认删除"}),e.jsx("button",{type:"button",onClick:()=>p(!1),children:"保留"})]}):null,s.historyMore?e.jsx("button",{type:"button",disabled:s.loading,onClick:()=>{s.moreHistory()},children:"继续加载历史"}):null,s.historyTruncated||s.state.historyTruncated?e.jsx("p",{children:"当前展示有界消息窗口,可重新选择对话从头读取。"}):null]})]}):null,s.error?e.jsxs("div",{className:"make-ai-assistant__conversation-error",role:"alert",children:[e.jsx("span",{children:s.error}),e.jsx("button",{type:"button",onClick:()=>{s.retry()},children:"恢复对话"})]}):null,o?e.jsxs("button",{className:"make-ai-assistant__conversation-new",type:"button",onClick:o,children:[e.jsx(ys,{}),e.jsx("span",{children:"新建对话"})]}):null]})}function js({message:t,manager:s}){const[a,o]=r.useState(!1),[n,c]=r.useState(""),[d,g]=r.useState(""),p=s.feedbackBusy.includes(t.id);if(!t.persistent||t.role!=="assistant"||t.intermediate)return null;const f=t.feedback?.rating??"none";return e.jsxs("div",{className:"make-ai-assistant__feedback","aria-label":"回答反馈",children:[e.jsx("button",{type:"button","aria-label":"点赞","aria-pressed":f==="like",disabled:p,onClick:()=>{s.feedback(t,f==="like"?"none":"like")},children:"赞"}),e.jsx("button",{type:"button","aria-label":"点踩","aria-pressed":f==="dislike",disabled:p,onClick:()=>{if(f==="dislike"){s.feedback(t,"none");return}c(t.feedback?.reason??""),g(t.feedback?.comment??""),o(!0)},children:"踩"}),f==="dislike"?e.jsx("button",{type:"button",disabled:p,onClick:()=>{c(t.feedback?.reason??""),g(t.feedback?.comment??""),o(!0)},children:"修改反馈"}):null,a?e.jsxs("form",{onSubmit:j=>{j.preventDefault(),s.feedback(t,"dislike",n,d).then(E=>{E&&o(!1)})},children:[e.jsx("input",{"aria-label":"反馈原因",maxLength:128,value:n,onChange:j=>c(j.currentTarget.value),placeholder:"原因(可选)"}),e.jsx("textarea",{"aria-label":"反馈说明",maxLength:4e3,value:d,onChange:j=>g(j.currentTarget.value),placeholder:"补充说明(可选)"}),e.jsx("button",{type:"submit",disabled:p,children:"提交反馈"}),e.jsx("button",{type:"button",onClick:()=>o(!1),children:"取消"})]}):null]})}const Mt=new Set(["image/png","image/jpeg","image/webp","image/gif","audio/mpeg","audio/wav","audio/ogg","audio/webm","video/mp4","video/webm","video/ogg"]);function _s({part:t,context:s,transport:a,chatId:o}){const[n,c]=r.useState(),[d,g]=r.useState(),[p,f]=r.useState(!1),j=r.useRef([]),E=r.useRef(void 0);r.useEffect(()=>()=>{E.current?.abort(),j.current.forEach(H=>URL.revokeObjectURL(H))},[]);const B=async H=>{if(!a.readContent||p)return;const y=new AbortController;E.current=y,f(!0),g(void 0);try{const V=await a.readContent(s,{chatId:o,contentRef:t.media.contentRef},{signal:y.signal});if(y.signal.aborted)return;const Q=new Blob([new Uint8Array(V).buffer],{type:H&&Mt.has(t.media.contentType)?t.media.contentType:"application/octet-stream"}),W=URL.createObjectURL(Q);if(j.current.push(W),H)c(W);else{const v=document.createElement("a");v.href=W,v.download=t.name??"attachment",v.click()}}catch(V){y.signal.aborted||g(ht(V))}finally{y.signal.aborted||f(!1)}};return e.jsxs("div",{className:"make-ai-assistant__attachment",children:[e.jsxs("span",{children:[t.name??"附件"," · ",t.media.sizeBytes," 字节"]}),e.jsx("button",{type:"button",disabled:p,onClick:()=>{B(!1)},children:"下载附件"}),Mt.has(t.media.contentType)?e.jsx("button",{type:"button",disabled:p,onClick:()=>{B(!0)},children:"预览附件"}):null,d?e.jsx("span",{role:"alert",children:d}):null,n&&t.kind==="image"?e.jsx("img",{src:n,alt:t.name??"附件图片"}):null,n&&t.kind==="audio"?e.jsx("audio",{src:n,controls:!0}):null,n&&t.kind==="video"?e.jsx("video",{src:n,controls:!0}):null]})}function ks({message:t,context:s,transport:a,chatId:o}){return e.jsx(e.Fragment,{children:t.parts?.map((n,c)=>n.kind==="text"?null:e.jsx(_s,{part:n,context:s,transport:a,chatId:o},n.id??`${t.id}:${c}`))})}const Is=(t,s)=>new Promise((a,o)=>{const n=new FileReader,c=()=>s.removeEventListener("abort",d),d=()=>{n.abort(),c(),o(Object.assign(new Error("Read aborted"),{name:"AbortError"}))};if(s.aborted){d();return}s.addEventListener("abort",d,{once:!0}),n.onload=()=>{c(),a(new Uint8Array(n.result))},n.onerror=()=>{c(),o(new Error("无法读取文件"))},n.readAsArrayBuffer(t)});function As(t,s,a){const[o,n]=r.useState([]),c=r.useRef(new Map),d=r.useRef(Promise.resolve()),g=s.scopeKey?.(t)??t.app.id,p=r.useRef(g);p.current=g;const f=r.useRef(void 0),j=a.enabled&&s.features?.attachments===!0,E=(u,l)=>{!c.current.has(u.draft.id)||u.scope!==p.current||(u.draft={...u.draft,...l},n([...c.current.values()].map(T=>T.draft)))},B=()=>{for(const u of c.current.values())u.controller.abort();c.current.clear(),n([]),f.current=void 0,d.current=Promise.resolve()};r.useEffect(()=>(B(),B),[g,s]),r.useEffect(()=>{f.current&&a.chat?.chatId!==f.current&&B()},[a.chat?.chatId]);const H=async u=>{const l=u.controller.signal,T=()=>{if(l.aborted||u.scope!==p.current||!c.current.has(u.draft.id))throw Object.assign(new Error("Upload aborted"),{name:"AbortError"})};try{if(T(),u.file.size>64<<20)throw new Error("文件不能超过 64 MiB");const N=await a.ensureChat();T(),f.current=N.chatId;const ae=u.file.type.split(";")[0].trim().toLowerCase()||"application/octet-stream";E(u,{status:"uploading",error:void 0});let R=u.draft.upload?await s.getUpload(t,{chatId:N.chatId,uploadId:u.draft.upload.id},{signal:l}):await s.startUpload(t,{chatId:N.chatId,fileId:u.draft.fileId,name:u.file.name,contentType:ae,sizeBytes:u.file.size},{signal:l});if(T(),E(u,{upload:R}),R.name!==u.file.name||R.contentType!==ae||R.sizeBytes!==u.file.size)throw new Error("上传文件身份不一致");if(R.status!=="ready"){R=await s.getUpload(t,{chatId:N.chatId,uploadId:R.id},{signal:l}),T();const G=new Set(R.completedParts),K=Math.ceil(u.file.size/R.partSize);for(let L=0;L<K;L+=1){if(T(),!G.has(L)){const q=await Is(u.file.slice(L*R.partSize,Math.min(u.file.size,(L+1)*R.partSize)),l);T(),await s.uploadPart(t,{chatId:N.chatId,uploadId:R.id,part:L,bytes:q},{signal:l}),T(),G.add(L)}E(u,{progress:G.size/Math.max(K,1)})}E(u,{status:"completing"}),R=await s.completeUpload(t,{chatId:N.chatId,uploadId:R.id},{signal:l}),T()}if(R.status!=="ready"||!R.content)throw new Error("上传尚未完成");E(u,{status:"ready",progress:1,upload:R})}catch(N){E(u,{status:l.aborted?"paused":"failed",error:l.aborted?void 0:ht(N)})}},y=u=>{if(j){if(u.length+c.current.size>32){a.setError("每条消息最多包含 32 个附件或文本片段");return}for(const l of u){const T={id:Oe(),fileId:Oe(),name:l.name,size:l.size,status:"queued",progress:0},N={draft:T,file:l,controller:new AbortController,scope:g};c.current.set(T.id,N),d.current=d.current.then(()=>H(N))}n([...c.current.values()].map(l=>l.draft))}},V=u=>{const l=c.current.get(u);!l||!["paused","failed"].includes(l.draft.status)||(l.controller=new AbortController,E(l,{status:"queued"}),d.current=d.current.then(()=>H(l)))},Q=u=>{c.current.get(u)?.controller.abort(),c.current.delete(u),n([...c.current.values()].map(T=>T.draft))},W=u=>c.current.get(u)?.controller.abort(),v=o.flatMap(u=>{const l=u.upload;if(u.status!=="ready"||!l?.content)return[];const T=l.contentType.startsWith("image/")&&l.contentType!=="image/svg+xml"?"image":l.contentType.startsWith("audio/")?"audio":l.contentType.startsWith("video/")?"video":"file";return[{id:u.id,kind:T,name:l.name,media:{contentRef:l.content.contentRef,contentType:l.contentType,sizeBytes:l.content.sizeBytes,digestSha256:l.content.digestSha256}}]});return{enabled:j,drafts:o,parts:v,pending:o.some(u=>u.status!=="ready"),add:y,retry:V,remove:Q,pause:W,clear:B}}function ws({attachments:t,onOpenChange:s,open:a,triggerRef:o}){const n=r.useRef(null),c=r.useRef(null),d=r.useRef(null);r.useEffect(()=>{if(!a)return;const p=f=>{const j=f.target;j instanceof Node&&!n.current?.contains(j)&&s(!1)};return document.addEventListener("pointerdown",p),()=>{document.removeEventListener("pointerdown",p)}},[s,a]);const g=p=>{t.add(Array.from(p.files??[])),p.value="",s(!1)};return e.jsxs("div",{className:"make-ai-assistant__attachment-composer",ref:n,children:[e.jsx("button",{"aria-expanded":a,"aria-haspopup":"menu","aria-label":"添加附件",className:"make-ai-assistant__attachment-trigger",ref:o,title:"添加附件",type:"button",onClick:()=>s(!a),children:e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"M12 5v14M5 12h14"})})}),a?e.jsxs("div",{"aria-label":"附件选项",className:"make-ai-assistant__attachment-menu",role:"menu",children:[e.jsxs("button",{role:"menuitem",type:"button",onClick:()=>c.current?.click(),children:[e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("rect",{height:"15",rx:"2",width:"18",x:"3",y:"4.5"}),e.jsx("circle",{cx:"8.5",cy:"9",r:"1.5"}),e.jsx("path",{d:"m5.5 17 4.2-4.2 2.8 2.7 2.2-2.1 3.8 3.6"})]}),e.jsx("span",{children:"上传图片"})]}),e.jsxs("button",{role:"menuitem",type:"button",onClick:()=>d.current?.click(),children:[e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M7 3.5h7l4 4V20H7z"}),e.jsx("path",{d:"M14 3.5v4h4M10 12h5M10 15h5"})]}),e.jsx("span",{children:"上传文件"})]})]}):null,e.jsx("input",{accept:"image/*","aria-label":"上传图片",hidden:!0,multiple:!0,ref:c,type:"file",onChange:p=>g(p.currentTarget)}),e.jsx("input",{"aria-label":"上传文件",hidden:!0,multiple:!0,ref:d,type:"file",onChange:p=>g(p.currentTarget)})]})}function Ts({attachments:t}){return t.drafts.length?e.jsx("div",{className:"make-ai-assistant__attachment-drafts","aria-label":"待发送附件",children:e.jsx("ul",{children:t.drafts.map(s=>e.jsxs("li",{children:[e.jsxs("span",{children:[s.name," ·"," ",s.status==="ready"?"已上传":s.status==="completing"?"校验中":s.status==="paused"?"已暂停":s.status==="failed"?"上传失败":`${Math.round(s.progress*100)}%`]}),s.error?e.jsx("span",{role:"alert",children:s.error}):null,s.status==="failed"||s.status==="paused"?e.jsx("button",{type:"button",onClick:()=>t.retry(s.id),children:"重试上传"}):null,s.status==="uploading"?e.jsx("button",{type:"button",onClick:()=>t.pause(s.id),children:"暂停上传"}):null,e.jsx("button",{type:"button",onClick:()=>t.remove(s.id),children:"移除附件"})]},s.id))})}):null}const Ms=t=>`${t}-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,Rs="Make",Cs=["总结当前页面数据","找出需要关注的记录","列出我有权限查看的数据对象"],Ut=(t,s)=>s??`${t?.trim()||Rs} AI 助手`,Ss=t=>t??Cs,Es=/^只读分析\s*[·•]\s*/u,Ns=(t,s)=>t?.trim().replace(Es,"").trim()||`当前对象:${s??"未命名应用"}`,Ls=480,Ht=1024,$s=.72,Rt=16,pe=16,We=8,lt=(t,s,a)=>Math.min(Math.max(t,Math.min(s,a)),a),Ds=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0,Os=(t,s,a)=>{const o=Math.min(Ht,a*$s);return Math.max(t,Math.min(s??o,a))},Ct=(t,s,a)=>Math.min(Math.max(t,s),Math.max(s,a)),Fs=(t,s,a,o)=>{const n=Math.min(Math.max(s.width,1),Math.max(1,o-pe*2)),c=Math.min(Math.max(s.height,1),Math.max(1,a-pe*2)),d=t.left+t.width/2,g=t.top+t.height/2,f=[{left:t.right+We,placement:"right",top:g-c/2},{left:t.left-We-n,placement:"left",top:g-c/2},{left:d-n/2,placement:"bottom",top:t.bottom+We},{left:d-n/2,placement:"top",top:t.top-We-c}].find(({left:j,top:E})=>j>=pe&&E>=pe&&j+n<=o-pe&&E+c<=a-pe);return f||{left:Ct(d-n/2,pe,o-pe-n),placement:"bottom",top:Ct(t.bottom+We,pe,a-pe-c)}},Ps=t=>typeof t=="number"?Number.isFinite(t)?`${t}px`:void 0:t?.trim()||void 0;class Z extends Error{}const rt=(t,s)=>{if(!(typeof t!="object"||t===null))return t[s]},Bs=t=>{const s=rt(t,"status");return typeof s=="number"?s:rt(rt(t,"response"),"status")},zs=t=>{const s=rt(t,"code"),a=Bs(t),o=t instanceof Error?t.message:"",n=[s,o].filter(p=>typeof p=="string").join(" ").toLowerCase(),d=globalThis.navigator?.onLine===!1||/network|fetch|timeout|offline|connection|网络|连接|超时/.test(n),g=typeof a=="number"&&a>=500||/server|service|服务器|服务异常/.test(n);return d?{actionLabel:"重新连接",description:"请检查网络后再试。",kind:"network",label:"网络连接",title:"网络连接不可用"}:g?{actionLabel:"重新加载",description:"服务暂时未能响应,请稍后重试。",kind:"service",label:"服务异常",title:"服务暂时不可用"}:{actionLabel:"重新加载",description:"请稍后重试;若问题持续出现,请联系管理员。",kind:"unknown",label:"加载异常",title:"暂时无法加载对话"}},St=t=>{try{const s=t?.return?.();if(!s)return;Promise.resolve(s).catch(a=>{console.error("[make-ai-assistant] transport iterator close failed",{errorType:a instanceof Error?a.name:typeof a})})}catch(s){console.error("[make-ai-assistant] transport iterator close failed",{errorType:s instanceof Error?s.name:typeof s})}},Us=async t=>{if(globalThis.navigator?.clipboard?.writeText){await globalThis.navigator.clipboard.writeText(t);return}if(typeof document>"u"||!document.body)throw new Error("Clipboard API is unavailable");const s=document.createElement("textarea");s.value=t,s.setAttribute("readonly",""),s.style.position="fixed",s.style.inset="0 auto auto 0",s.style.opacity="0",document.body.append(s),s.select();const a=document.execCommand("copy");if(s.remove(),!a)throw new Error("Clipboard copy failed")},Kt=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M12 2.8c.5 4.4 2.8 6.8 7.2 7.2-4.4.5-6.8 2.8-7.2 7.2-.5-4.4-2.8-6.8-7.2-7.2 4.4-.5 6.8-2.8 7.2-7.2Z"}),e.jsx("path",{d:"M18.3 16.1c.2 1.8 1.2 2.8 3 3-1.8.2-2.8 1.2-3 3-.2-1.8-1.2-2.8-3-3 1.8-.2 2.8-1.2 3-3Z"})]}),Hs=()=>e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"m6 6 12 12M18 6 6 18"})}),Ks=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M8 8h10v12H8z"}),e.jsx("path",{d:"M6 16H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),Vs=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M20 11a8 8 0 0 0-14.7-4.4L4 8"}),e.jsx("path",{d:"M4 4v4h4"}),e.jsx("path",{d:"M4 13a8 8 0 0 0 14.7 4.4L20 16"}),e.jsx("path",{d:"M20 20v-4h-4"})]}),Ws=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("circle",{cx:"12",cy:"12",r:"8"}),e.jsx("path",{d:"M9.8 9.4a2.35 2.35 0 1 1 3.93 1.73c-.96.86-1.73 1.42-1.73 2.87"}),e.jsx("path",{d:"M12 17h.01"})]}),qs=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M12 4v11"}),e.jsx("path",{d:"m7 10 5 5 5-5"}),e.jsx("path",{d:"M5 20h14"})]}),Xs=()=>e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"M12 5v14M5 12h14"})}),Ys=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M10 6h9M10 12h9M10 18h9"}),e.jsx("path",{d:"M5 6h.01M5 12h.01M5 18h.01"})]}),Zs=()=>e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"m7 10 5 5 5-5"})}),Et=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"m4 4 17 8-17 8 3-8-3-8Z"}),e.jsx("path",{d:"M7 12h14"})]}),Vt=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M20 11a8 8 0 0 0-14.7-4.4L4 8"}),e.jsx("path",{d:"M4 4v4h4"}),e.jsx("path",{d:"M4 13a8 8 0 0 0 14.7 4.4L20 16"}),e.jsx("path",{d:"M20 20v-4h-4"})]}),Gs=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("circle",{cx:"12",cy:"12",r:"8"}),e.jsx("path",{d:"M12 8v4.5"}),e.jsx("path",{d:"M12 16h.01"})]}),it=({className:t=""})=>e.jsx("span",{className:`make-ai-assistant__avatar ${t}`.trim(),"aria-hidden":"true",children:e.jsx(Kt,{})}),Js=({src:t})=>t?e.jsx("span",{className:"make-ai-assistant__user-avatar","aria-hidden":"true",children:e.jsx("img",{alt:"",src:t})}):null,Qs=({userAvatarUrl:t,userName:s})=>{const a=s?.trim();return!a&&!t?null:e.jsxs("div",{className:"make-ai-assistant__message-identity",children:[a?e.jsx("span",{className:"make-ai-assistant__message-sender",children:a}):null,e.jsx(Js,{src:t})]})},dt=t=>{const s=t.trim();if(!(!s.startsWith("|")||!s.endsWith("|")))return s.slice(1,-1).split("|").map(a=>a.trim())},ea=t=>t.length>0&&t.every(s=>/^:?-{3,}:?$/.test(s)),ta=(t,s)=>{const a=dt(t[s]??""),o=dt(t[s+1]??"");if(!a||!o||a.length!==o.length||!ea(o))return;const n=[];let c=s+2;for(;c<t.length;){const d=dt(t[c]??"");if(!d||d.length!==a.length)break;n.push(d),c+=1}return{headers:a,lastIndex:c-1,rows:n}},sa=t=>{const s=[],a=[],o=[],n=[],c=t.replace(/\r\n?/g,`
2
2
  `).split(`
3
- `),c=()=>{const f=a.join(`
4
- `).trim();a.length=0,f&&s.push({type:"paragraph",text:f})},m=()=>{r.length&&s.push({type:"list",items:r.splice(0)})},x=()=>{const f=n.join(`
5
- `).trim();n.length=0,f&&s.push({type:"pre",text:f})};for(let f=0;f<i.length;f+=1){const T=i[f]??"",M=T.trim();if(!M){c(),m(),x();continue}const F=Is(i,f);if(F){c(),m(),x(),s.push({headers:F.headers,rows:F.rows,type:"table"}),f=F.lastIndex;continue}const E=/^(#{1,6})\s+(.+)$/.exec(M);if(E){c(),m(),x();const R=(E[2]??"").replace(/\s+#+\s*$/,"").trim();R&&s.push({type:"heading",level:E[1]?.length,text:R});continue}if(/^\s*\|.+\|\s*$/.test(T)){c(),m(),n.push(T.trim());continue}const I=/^\s*[-*]\s+(.+)$/.exec(T);if(I){c(),x(),r.push(I[1]?.trim()??"");continue}m(),x(),a.push(M)}return c(),m(),x(),s},_e=e=>{const s=[],a=/(\*\*[^*]+\*\*|`[^`]+`)/g;let r=0;for(const n of e.matchAll(a)){const i=n[0],c=n.index??0;c>r&&s.push(e.slice(r,c)),i.startsWith("**")?s.push(t.jsx("strong",{children:i.slice(2,-2)},`${c}-strong`)):s.push(t.jsx("code",{children:i.slice(1,-1)},`${c}-code`)),r=c+i.length}return r<e.length&&s.push(e.slice(r)),s},ws=({content:e})=>{const s=bs(e);return s.length?t.jsx("div",{className:"make-ai-assistant__bubble make-ai-assistant__assistant-text",children:s.map((a,r)=>{if(a.type==="heading"){const n=a.level<=2?"h3":"h4";return t.jsx(n,{className:`make-ai-assistant__markdown-heading make-ai-assistant__markdown-heading--${a.level}`,children:_e(a.text)},`${r}-heading`)}return a.type==="paragraph"?t.jsx("p",{children:_e(a.text)},`${r}-paragraph`):a.type==="pre"?t.jsx("pre",{children:t.jsx("code",{children:a.text})},`${r}-pre`):a.type==="table"?t.jsx("div",{"aria-label":"表格内容,可横向滚动",className:"make-ai-assistant__markdown-table-scroll",role:"region",tabIndex:0,children:t.jsxs("table",{className:"make-ai-assistant__markdown-table",children:[t.jsx("thead",{children:t.jsx("tr",{children:a.headers.map((n,i)=>t.jsx("th",{scope:"col",children:_e(n)},`${i}-${n}`))})}),t.jsx("tbody",{children:a.rows.map((n,i)=>t.jsx("tr",{children:n.map((c,m)=>t.jsx("td",{children:_e(c)},`${m}-${c}`))},`${i}-${n.join("|")}`))})]})},`${r}-table`):t.jsx("ul",{children:a.items.map((n,i)=>t.jsx("li",{children:_e(n)},`${i}-${n}`))},`${r}-list`)})}):null},wt=({assistantName:e})=>t.jsxs("div",{className:"make-ai-assistant__message-identity",children:[t.jsx(Me,{className:"make-ai-assistant__avatar--message"}),t.jsx("span",{className:"make-ai-assistant__message-sender",children:e})]}),Tt=e=>{for(let s=e.messages.length-1;s>=0;s-=1){const a=e.messages[s];if(a.role==="assistant"&&a.status==="streaming")return a.id}},Ts=e=>{for(let s=e.messages.length-1;s>=0;s-=1)if(e.messages[s].role==="user")return s;return-1},Mt=e=>{const s=Ts(e);if(!(s<0))for(let a=e.messages.length-1;a>s;a-=1){const r=e.messages[a];if(r.role==="assistant")return r.id}},Ms=e=>{if(e.status==="idle")for(let s=e.messages.length-1;s>=0;s-=1){const a=e.messages[s];if(a.role==="assistant"&&a.status==="complete")return a.id}},Ns=e=>{for(let s=e.messages.length-1;s>=0;s-=1){const a=e.messages[s];if(a.role==="user")return a}},Es=(e,s)=>{const a=e.messages.findIndex(r=>r.id===s&&r.role==="user");return{...e,error:void 0,progress:void 0,status:"streaming",messages:a<0?e.messages:e.messages.slice(0,a+1)}},Ss=e=>e.scrollHeight-e.scrollTop-e.clientHeight<=48,ht=(e="smooth")=>globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches?"auto":e,Le=(e,s)=>{typeof e.scrollTo=="function"?e.scrollTo({top:e.scrollHeight,behavior:s}):e.scrollTop=e.scrollHeight},Nt=({error:e,onRetry:s})=>t.jsxs("div",{className:"make-ai-assistant__message-status make-ai-assistant__message-status--error","data-error-presentation":"request-failed",role:"alert",children:[t.jsxs("div",{className:"make-ai-assistant__message-status-header",children:[t.jsx("span",{className:"make-ai-assistant__message-status-icon","aria-hidden":"true",children:t.jsx(js,{})}),t.jsx("strong",{children:"请求未完成"})]}),t.jsx("span",{className:"make-ai-assistant__message-status-message",children:e.message}),e.retryable&&s?t.jsxs("button",{className:"make-ai-assistant__retry",type:"button",onClick:s,children:[t.jsx(bt,{}),"重新发送"]}):null]}),Rs=({error:e,onRetry:s})=>{const a=ms(e);return t.jsxs("section",{"aria-live":"assertive",className:"make-ai-assistant__load-failure","data-load-failure-kind":a.kind,role:"alert",children:[t.jsx("span",{className:"make-ai-assistant__load-failure-icon","aria-hidden":"true",children:t.jsxs("svg",{viewBox:"0 0 24 24",children:[t.jsx("path",{d:"M5 12a7 7 0 0 1 13.4-2.8A4.5 4.5 0 0 1 18 18H7.5A4.5 4.5 0 0 1 5 12Z"}),t.jsx("path",{d:"m9.2 14.8 5.6-5.6M9.2 9.2l5.6 5.6"})]})}),t.jsxs("div",{className:"make-ai-assistant__load-failure-copy",children:[t.jsx("span",{className:"make-ai-assistant__load-failure-label",children:a.label}),t.jsx("h3",{children:a.title}),t.jsx("p",{children:a.description})]}),t.jsxs("button",{className:"make-ai-assistant__retry make-ai-assistant__retry--primary",type:"button",onClick:s,children:[t.jsx(bt,{}),a.actionLabel]})]})},Et=({active:e,steps:s})=>{if(!e||!s?.length)return null;const a=s[s.length-1]??"处理中";return t.jsxs("details",{className:"make-ai-assistant__process",open:!0,children:[t.jsxs("summary",{children:[t.jsxs("span",{className:"make-ai-assistant__progress",role:"status",children:[t.jsx("span",{"aria-hidden":"true"}),t.jsx("span",{children:a})]}),t.jsxs("span",{className:"make-ai-assistant__process-count",children:[s.length," 步"]})]}),t.jsx("ol",{children:s.map((r,n)=>t.jsxs("li",{"data-step-active":n===s.length-1?!0:void 0,children:[t.jsx("span",{"aria-hidden":"true"}),t.jsx("span",{children:r})]},`${n}-${r}`))})]})},Cs=({copyFeedback:e,onCopy:s,onRegenerate:a})=>!s&&!a?null:t.jsxs("div",{className:"make-ai-assistant__reply-actions","aria-label":"回复操作",children:[s?t.jsx("button",{"aria-label":"复制回答",className:"make-ai-assistant__reply-action make-ai-assistant__reply-copy","data-tooltip":"复制",type:"button",onClick:s,children:t.jsx(hs,{})}):null,a?t.jsx("button",{"aria-label":"重新生成",className:"make-ai-assistant__reply-action make-ai-assistant__reply-regenerate","data-tooltip":"重新生成",type:"button",onClick:a,children:t.jsx(fs,{})}):null,e?t.jsx("span",{className:"make-ai-assistant__reply-feedback","data-copy-status":e.status,role:"status",children:e.message}):null]}),ft=({assistantName:e,error:s,onRetry:a,progress:r})=>{const n=s?"error":"progress";return s?.message??r?.message?t.jsx("article",{"aria-label":`${e}的${n==="error"?"错误消息":"状态消息"}`,className:`make-ai-assistant__message make-ai-assistant__message--assistant make-ai-assistant__message--${n}`,"data-message-role":"assistant","data-message-state":n,children:t.jsxs("div",{className:"make-ai-assistant__message-turn",children:[t.jsx(wt,{assistantName:e}),t.jsx("div",{className:"make-ai-assistant__message-stack",children:s?t.jsx(Nt,{error:s,onRetry:a}):t.jsx(Et,{active:!0,steps:r?.steps})})]})}):null},$s=(e,s,a,r,n,i,c,m,x,f,T,M,F,E)=>{const I=Mt(e),R=Tt(e),C=Ms(e);let $;return e.messages.map(u=>{const A=u.role==="assistant",Z=$;A||($=u);const K=u.id===R,b=u.id===I?e.error:void 0,B=u.error??b,S=!A&&!!(x?.trim()||f),D=A?c:x?.trim()||"用户",v=A&&u.status==="complete"&&!B&&(u.content.trim()||u.id===C);return t.jsx("article",{"aria-label":`${D}的消息`,className:`make-ai-assistant__message make-ai-assistant__message--${u.role}`,"data-message-role":u.role,"data-message-state":B?"error":void 0,"data-message-status":u.status,"data-message-has-identity":A||S?!0:void 0,children:t.jsxs("div",{className:"make-ai-assistant__message-turn",children:[A?t.jsx(wt,{assistantName:c}):S?t.jsx(As,{userAvatarUrl:f,userName:x}):null,t.jsxs("div",{className:"make-ai-assistant__message-stack",children:[u.content?A?t.jsx(ws,{content:u.content}):t.jsx("div",{className:"make-ai-assistant__bubble",children:u.content}):u.status==="streaming"?t.jsxs("div",{className:"make-ai-assistant__typing","aria-label":`${c}正在思考`,children:[t.jsx("span",{}),t.jsx("span",{}),t.jsx("span",{})]}):null,A?t.jsx(Et,{active:K&&e.status==="streaming",steps:u.progressSteps}):null,B?t.jsx(Nt,{error:B,onRetry:b?m:void 0}):null,u.artifacts.map(j=>t.jsx(xt,{artifact:j,context:s,onAction:n,onActionError:i,registry:a,theme:r},j.id)),v?t.jsx(Cs,{copyFeedback:T?.messageId===u.id?{message:T.message,status:T.status}:void 0,onCopy:u.content.trim()?()=>F(u.id,u.content):void 0,onRegenerate:M&&u.id===C&&Z?()=>E({userMessage:Z,assistantMessage:u}):void 0}):null]})]})},u.id)})};function St({assistantName:e="AI 助手",brandName:s,context:a,onAction:r,onActionError:n,onClose:i,onNewConversation:c,headerHeight:m,privacyNotice:x,registry:f,subtitle:T,suggestions:M,title:F,theme:E,transport:I,userAvatarUrl:R,userName:C,visible:$}){const u=At(s,F),A=x?.trim(),Z=as(T,a.app.name),K=ls(m),b=Oe(E),B=b||K?{...b,...K?{"--make-ai-internal-header-height":K}:{}}:void 0,[S,D]=l.useState(""),[v,j]=l.useState(p.createAssistantConversationState),Q=l.useRef(v);Q.current=v;const[J,ee]=l.useState(void 0),[Ne,U]=l.useState(void 0),[Ee,de]=l.useState(0),[W,h]=l.useState(()=>I.loadConversation?"loading":"ready"),[w,L]=l.useState(void 0),[ve,z]=l.useState(!1),[te,Fe]=l.useState(!1),[me,De]=l.useState(void 0),se=l.useRef(void 0),ae=l.useRef(void 0),ne=l.useRef(0),Pe=l.useRef(null),ue=l.useRef(null),Ve=l.useRef(null),We=l.useRef(null),He=l.useRef(null),Ke=l.useRef(null),q=l.useRef(!0),Be=l.useRef(a.app.id),Ue=l.useRef($),ze=l.useId(),qe=l.useMemo(()=>f??yt(),[f]),Xe=l.useMemo(()=>ts(M),[M]),Ye=()=>{const o=We.current,_=He.current;if(!o||!_||typeof window>"u")return;const g=cs(o.getBoundingClientRect(),_.getBoundingClientRect(),window.innerHeight,window.innerWidth);De(y=>y?.left===g.left&&y.top===g.top&&y.placement===g.placement?y:g)},Ge=()=>Fe(!0),Ze=()=>Fe(!1),Rt=me?{left:`${me.left}px`,top:`${me.top}px`}:void 0;l.useLayoutEffect(()=>{if(!te||!A){De(void 0);return}Ye()},[te,A]),l.useEffect(()=>{if(!te||!A)return;const o=()=>Ye();return window.addEventListener("resize",o),window.addEventListener("scroll",o,!0),()=>{window.removeEventListener("resize",o),window.removeEventListener("scroll",o,!0)}},[te,A]);const je=o=>{const _=se.current,g=ae.current?.iterator;return!_&&!g?!1:(ne.current+=1,se.current=void 0,ae.current=void 0,console.info("[make-ai-assistant] local run cancellation requested",{reason:o}),_?.abort(),pt(g),!0)};l.useEffect(()=>()=>{je("unmount")},[]),l.useEffect(()=>{const o=I.loadConversation,_=Be.current!==a.app.id;if(Be.current=a.app.id,je("reinitialize"),_&&(D(""),q.current=!0),ee(void 0),U(void 0),z(!1),j(p.createAssistantConversationState()),!o){L(void 0),h("ready");return}const g=new AbortController;return L(void 0),h("loading"),console.info("[make-ai-assistant] conversation load start",{appId:a.app.id}),o.call(I,a,{signal:g.signal}).then(y=>{g.signal.aborted||(j(p.createAssistantConversationState(y)),h("ready"),console.info("[make-ai-assistant] conversation load success",{appId:a.app.id,messageCount:y.messages.length}))}).catch(y=>{g.signal.aborted||(console.error("[make-ai-assistant] conversation load failed",{appId:a.app.id,errorType:y instanceof Error?y.name:typeof y}),L(y),h("error"))}),()=>g.abort()},[a.app.id,Ee,I]),l.useEffect(()=>{const o=ue.current;if(!o||!q.current)return;z(!1);const _=requestAnimationFrame(()=>{if(!q.current)return;const g=v.status==="streaming"||globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches?"auto":"smooth";Le(o,g)});return()=>cancelAnimationFrame(_)},[v.messages,v.progress,v.status]),l.useEffect(()=>{const o=$&&!Ue.current;if(Ue.current=$,!o)return;const _=requestAnimationFrame(()=>{const g=ue.current;if(g&&q.current){z(!1);const pe=Q.current.status==="streaming"?"auto":ht();Le(g,pe)}else g&&z(Q.current.messages.length>0);const y=Ve.current;(y&&!y.disabled?y:Ke.current??Pe.current?.querySelector("button:not(:disabled)"))?.focus()});return()=>cancelAnimationFrame(_)},[$]);const Ct=()=>{const o=ue.current;if(!o)return;const _=Ss(o);q.current=_,z(!_&&Q.current.messages.length>0)},$t=()=>{const o=ue.current;if(!o)return;q.current=!0,z(!1);const _=ht();Le(o,_)},Qe=async(o,_)=>{const g=o.trim(),y=Q.current,H=_?.regenerateFrom,pe=I.regenerate;if(!g||W!=="ready"||y.status==="streaming"||se.current||H&&!pe)return;if(p.countCodePointsUpTo(g,p.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)>p.MAKE_AI_CONVERSATION_LIMITS.messageCharacters){ee(`输入内容过长,请控制在 ${p.MAKE_AI_CONVERSATION_LIMITS.messageCharacters} 个字符以内`);return}const ke={id:H?.userMessage.id??Qt("user"),content:g},Ie=H?Es(y,H.userMessage.id):p.appendUserMessage(y,ke),be=new AbortController,re=ne.current+1;ne.current=re,se.current=be,ee(void 0),U(void 0),z(!q.current&&y.messages.length>0),H||D(""),j(Ie);try{let X=!1,N,tt=0,st=0,at=0,Se=0,he=0;const fe=new Map,nt=new Set,rt=new Set([...Ie.messages.map(we=>we.id),ke.id]),ge=new Set,it=G.createArtifactCapabilities(qe),ot={signal:be.signal};let Re;if(H){if(!pe)throw new k("当前 AI 助手不支持重新生成");Re=pe({threadId:Ie.threadId,message:ke,assistantMessage:{id:H.assistantMessage.id,content:H.assistantMessage.content},context:a,capabilities:it},ot)}else Re=I.run({threadId:Ie.threadId,message:ke,context:a,capabilities:it},ot);const ct=Re[Symbol.asyncIterator]();for(ae.current={iterator:ct,requestVersion:re};;){const we=await ct.next();if(ne.current!==re||we.done)break;let d;try{d=p.parseAssistantEvent(we.value)}catch(O){throw new k(O instanceof Error?O.message:"Invalid assistant event")}if(d.type==="message.start"){if(N!==void 0&&N!==d.runId)throw new k("AI 助手响应 run id 不一致");if(N??=d.runId,st+=1,st>p.MAKE_AI_CONVERSATION_LIMITS.assistantMessagesPerRun)throw new k("AI 助手单次响应消息数量超过限制");if(rt.has(d.messageId))throw new k("AI 助手响应包含重复的 message id");rt.add(d.messageId),ge.add(d.messageId),fe.set(d.messageId,0)}if(d.type==="message.delta"){if(!ge.has(d.messageId))throw new k("AI 助手响应事件顺序无效");const O=fe.get(d.messageId)??0,ie=p.countCodePointsUpTo(d.delta,p.MAKE_AI_CONVERSATION_LIMITS.messageCharacters-he);if(he+ie>p.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)throw new k("AI 助手响应文本超过大小限制");he+=ie,fe.set(d.messageId,O+ie)}if(d.type==="message.replace"){if(!ge.has(d.messageId))throw new k("AI 助手响应事件顺序无效");const O=fe.get(d.messageId)??0,ie=p.countCodePointsUpTo(d.content,p.MAKE_AI_CONVERSATION_LIMITS.messageCharacters),lt=he-O+ie;if(lt>p.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)throw new k("AI 助手响应文本超过大小限制");he=lt,fe.set(d.messageId,ie)}if(d.type==="run.progress"){if(N!==void 0&&N!==d.runId)throw new k("AI 助手响应 run id 不一致");if(N??=d.runId,at+=1,at>p.MAKE_AI_CONVERSATION_LIMITS.progressStepsPerRun)throw new k("AI 助手处理过程数量超过限制");const O=p.countCodePointsUpTo(d.message,p.MAKE_AI_CONVERSATION_LIMITS.progressCharactersPerRun-Se);if(Se+O>p.MAKE_AI_CONVERSATION_LIMITS.progressCharactersPerRun)throw new k("AI 助手处理过程文本超过大小限制");Se+=O}if(d.type==="artifact"){if(!ge.has(d.messageId))throw new k("AI 助手响应事件顺序无效");if(tt+=1,tt>p.MAKE_AI_CONVERSATION_LIMITS.artifactsPerRun)throw new k("AI 助手单次响应 Artifact 数量超过限制");if(nt.has(d.artifact.id))throw new k("AI 助手响应包含重复的 Artifact id");nt.add(d.artifact.id)}if(d.type==="message.complete"&&!ge.delete(d.messageId))throw new k("AI 助手响应事件顺序无效");if(d.type==="run.complete"&&N!==void 0&&N!==d.runId)throw new k("AI 助手响应 run id 不一致");if(d.type==="run.cancelled"&&d.runId!==void 0&&N!==void 0&&N!==d.runId)throw new k("AI 助手响应 run id 不一致");if(j(O=>p.reduceAssistantEvent(O,d)),d.type==="error"||d.type==="run.cancelled"||d.type==="run.complete"){X=!0;break}}if(!X)throw new k("AI 助手流式响应在终止事件前结束")}catch(X){if(ne.current!==re)return;if(be.signal.aborted){j(N=>p.reduceAssistantEvent(N,{type:"run.cancelled"}));return}console.error("[make-ai-assistant] assistant run failed",{appId:a.app.id,errorType:X instanceof Error?X.name:typeof X}),j(N=>p.reduceAssistantEvent(N,{type:"error",code:"TRANSPORT_ERROR",message:X instanceof k?X.message:"连接失败,请重试",retryable:!0}))}finally{ne.current===re&&se.current===be&&(se.current=void 0),ae.current?.requestVersion===re&&(pt(ae.current.iterator),ae.current=void 0)}},ye=o=>Qe(o),Lt=o=>Qe(o.userMessage.content,{regenerateFrom:o}),Ot=async(o,_)=>{try{await us(_),U({messageId:o,message:"已复制",status:"success"})}catch(g){console.error("[make-ai-assistant] copy answer failed",{errorType:g instanceof Error?g.name:typeof g}),U({messageId:o,message:"复制失败",status:"error"})}},Ft=o=>{o.preventDefault(),ye(S)},Dt=o=>{o.key==="Enter"&&!o.shiftKey&&!o.nativeEvent.isComposing&&(o.preventDefault(),ye(S))},Pt=()=>{je("stop")&&j(o=>p.reduceAssistantEvent(o,{type:"run.cancelled"}))},Vt=()=>{je("new-conversation"),D(""),ee(void 0),U(void 0),z(!1),q.current=!0,j(p.createAssistantConversationState()),c?.()},Je=I.features?.remoteCancellation===!1?"停止接收":"停止生成",Wt=Tt(v),Ht=Mt(v),Ae=Ns(v),Kt=typeof I.regenerate=="function"&&I.features?.regeneration!==!1,et=()=>{Ae&&ye(Ae.content)};return t.jsxs("section",{className:"make-ai-assistant make-ai-assistant__panel",ref:Pe,style:B,children:[t.jsxs("header",{className:"make-ai-assistant__header",children:[t.jsx(Me,{}),t.jsxs("div",{className:"make-ai-assistant__header-content",children:[t.jsxs("div",{className:"make-ai-assistant__header-title-row",children:[t.jsx("h2",{className:"make-ai-assistant__header-title",title:u,children:u}),t.jsx("span",{className:"make-ai-assistant__read-only-tag",children:"只读"})]}),t.jsxs("div",{className:"make-ai-assistant__header-context",children:[t.jsx("p",{title:Z,children:Z}),A?t.jsxs(t.Fragment,{children:[t.jsx("span",{"aria-describedby":ze,"aria-label":`使用提示:${A}`,className:"make-ai-assistant__header-context-help","data-tooltip":A,ref:We,role:"note",tabIndex:0,onBlur:Ze,onFocus:Ge,onPointerEnter:Ge,onPointerLeave:Ze,children:t.jsx(gs,{})}),t.jsx("span",{"aria-hidden":!te,className:"make-ai-assistant__header-context-tooltip","data-placement":me?.placement,"data-positioned":me?!0:void 0,"data-visible":te||void 0,id:ze,ref:He,role:"tooltip",style:Rt,children:A})]}):null]})]}),t.jsxs("div",{className:"make-ai-assistant__header-actions",children:[I.features?.newConversation!==!1?t.jsx("button",{"aria-label":"新建对话",className:"make-ai-assistant__icon-button",type:"button",onClick:Vt,children:t.jsx(_s,{})}):null,i?t.jsx("button",{"aria-label":`关闭 ${u}`,className:"make-ai-assistant__icon-button",type:"button",onClick:i,children:t.jsx(ps,{})}):null]})]}),t.jsxs("div",{className:"make-ai-assistant__body","aria-live":"polite","aria-relevant":"additions text",ref:ue,role:"log",onScroll:Ct,children:[W==="loading"?t.jsxs("div",{className:"make-ai-assistant__empty",role:"status",children:[t.jsx(Me,{}),t.jsx("h3",{children:"正在恢复对话"}),t.jsx("p",{children:"正在读取当前 App 的历史消息…"})]}):W==="error"?t.jsx("div",{className:"make-ai-assistant__empty",children:t.jsx(Rs,{error:w,onRetry:()=>de(o=>o+1)})}):v.messages.length===0?t.jsxs("div",{className:"make-ai-assistant__empty",children:[t.jsx(Me,{}),t.jsx("h3",{children:"有什么可以帮你?"}),t.jsx("p",{children:"我会结合当前 App、页面位置和宿主允许的上下文回答,并把过程与结果分开展示。"})]}):$s(v,a,qe,E,r,n,e,Ae?et:void 0,C,R,Ne,Kt,(o,_)=>{Ot(o,_)},o=>{Lt(o)}),v.progress&&!Wt?t.jsx(ft,{assistantName:e,progress:v.progress}):null,v.error&&!Ht?t.jsx(ft,{assistantName:e,error:v.error,onRetry:Ae?et:void 0}):null]}),ve?t.jsx("button",{"aria-label":"回到最新消息",className:"make-ai-assistant__back-to-latest",type:"button",onClick:$t,children:t.jsx(xs,{})}):null,t.jsxs("footer",{className:"make-ai-assistant__composer-region",children:[W==="ready"&&Xe.length>0&&v.messages.length===0?t.jsx("div",{className:"make-ai-assistant__suggestions","aria-label":"推荐问题",children:Xe.map((o,_)=>t.jsx("button",{type:"button",onClick:()=>{ye(o)},children:o},`${_}-${o}`))}):null,t.jsxs("form",{className:"make-ai-assistant__composer",onSubmit:Ft,children:[t.jsx("textarea",{"aria-label":`向 ${e} 提问`,"aria-describedby":J?"make-ai-composer-error":void 0,"aria-invalid":J?!0:void 0,autoFocus:!0,disabled:W!=="ready"||v.status==="streaming",placeholder:`询问当前 ${a.app.name??"App"} 中的数据…`,ref:Ve,rows:2,value:S,onChange:o=>{D(o.currentTarget.value),ee(void 0)},onKeyDown:Dt}),v.status==="streaming"?t.jsx("button",{"aria-label":Je,className:"make-ai-assistant__send make-ai-assistant__send--stop","data-tooltip":Je,ref:Ke,type:"button",onClick:Pt,children:t.jsx("span",{"aria-hidden":"true"})}):t.jsx("button",{"aria-label":"发送",className:"make-ai-assistant__send",disabled:W!=="ready"||!S.trim(),type:"submit",children:t.jsx(vs,{})})]}),J?t.jsx("p",{id:"make-ai-composer-error",role:"alert",children:J}):null,t.jsx("p",{children:"AI 生成的结果可能存在偏差,重要数据请核对明细。"})]})]})}function Ls(e){return t.jsx(St,{...e,visible:!0})}function Os({defaultOpen:e=!1,hideLauncher:s=!1,launcher:a,launcherPosition:r="bottom-right",maxDrawerWidth:n,onOpenChange:i,open:c,...m}){const x=At(m.brandName,m.title),[f,T]=l.useState(e),[M,F]=l.useState(()=>e||c===!0),E=l.useRef(null),I=l.useRef(null),R=l.useRef(void 0),[C,$]=l.useState(),[u,A]=l.useState(ns),[Z,K]=l.useState(!1),b=c??f,B=Oe(m.theme),S=is(n),D=()=>os(u,S,typeof window>"u"?kt:window.innerWidth),v=D(),j=C===void 0?void 0:Ce(C,u,v),Q=j===void 0&&S===void 0?void 0:{...j===void 0?{}:{"--make-ai-internal-drawer-width":`${j}px`},...S===void 0?{}:{"--make-ai-internal-drawer-max-width":`max(var(--make-ai-internal-drawer-min-width), ${S}px)`}};l.useLayoutEffect(()=>{j!==void 0&&j!==C&&$(j)},[j,C]);const J=()=>{if(j!==void 0)return j;const h=I.current?.getBoundingClientRect().width;return h&&Number.isFinite(h)&&h>0?h:u},ee=h=>{if(h.button!==0)return;const w=J(),L=C===void 0?w:u;A(L),R.current={minimumWidth:L,pointerId:h.pointerId,startWidth:w,startX:h.clientX},K(!0),typeof h.currentTarget.setPointerCapture=="function"&&h.currentTarget.setPointerCapture(h.pointerId),h.preventDefault()},Ne=h=>{const w=R.current;if(!w||w.pointerId!==h.pointerId)return;const L=Ce(w.startWidth+w.startX-h.clientX,w.minimumWidth,D());$(L)},U=h=>{const w=R.current;!w||w.pointerId!==h.pointerId||(R.current=void 0,K(!1))},Ee=h=>{const w=h.key==="ArrowLeft"?mt:h.key==="ArrowRight"?-mt:void 0;if(w===void 0)return;h.preventDefault();const L=J(),ve=C===void 0?L:u;A(ve),$(Ce(L+w,ve,D()))},de=h=>{c===void 0&&T(h),i?.(h),h||requestAnimationFrame(()=>E.current?.focus())},W=()=>de(!b);return l.useEffect(()=>{b&&F(!0)},[b]),l.useEffect(()=>{if(!b)return;const h=w=>{w.key==="Escape"&&(de(!1),requestAnimationFrame(()=>E.current?.focus()))};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[i,b]),t.jsxs("div",{className:"make-ai-assistant","data-open":b||void 0,style:B,children:[!s&&(!b||a)?a?a({open:b,toggle:W}):t.jsxs("button",{"aria-label":b?`关闭 ${x}`:`打开 ${x}`,"aria-expanded":b,className:"make-ai-assistant__launcher","data-launcher-position":r,ref:E,type:"button",onClick:W,children:[t.jsx("span",{className:"make-ai-assistant__launcher-orbit","aria-hidden":"true"}),t.jsx(It,{})]}):null,M?t.jsxs("aside",{"aria-label":x,"aria-modal":"false",className:"make-ai-assistant__drawer","data-resizing":Z||void 0,hidden:!b,ref:I,role:"dialog",style:Q,children:[t.jsx("div",{"aria-label":"调整对话框宽度","aria-orientation":"vertical","aria-valuemax":v,"aria-valuemin":u,"aria-valuenow":j??u,className:"make-ai-assistant__drawer-resize-handle",role:"separator",tabIndex:0,onKeyDown:Ee,onPointerCancel:U,onPointerDown:ee,onPointerMove:Ne,onPointerUp:U}),t.jsx(St,{...m,onClose:()=>de(!1),visible:b})]}):null]})}exports.createArtifactCapabilities=G.createArtifactCapabilities;exports.createArtifactTemplateRegistry=G.createArtifactTemplateRegistry;exports.extendArtifactTemplateRegistry=G.extendArtifactTemplateRegistry;exports.resolveArtifactTemplate=G.resolveArtifactTemplate;exports.MAKE_AI_ARTIFACT_KINDS=p.MAKE_AI_ARTIFACT_KINDS;exports.MAKE_AI_ARTIFACT_LIMITS=p.MAKE_AI_ARTIFACT_LIMITS;exports.MAKE_AI_ARTIFACT_SCHEMA_VERSION=p.MAKE_AI_ARTIFACT_SCHEMA_VERSION;exports.MAKE_AI_CONVERSATION_LIMITS=p.MAKE_AI_CONVERSATION_LIMITS;exports.appendUserMessage=p.appendUserMessage;exports.createAssistantConversationState=p.createAssistantConversationState;exports.parseArtifact=p.parseArtifact;exports.parseAssistantEvent=p.parseAssistantEvent;exports.reduceAssistantEvent=p.reduceAssistantEvent;exports.validateArtifact=p.validateArtifact;exports.ArtifactRenderer=xt;exports.AssistantPanel=Ls;exports.MakeAiAssistant=Os;exports.createPlatformArtifactRegistry=yt;exports.formatArtifactValue=Y;exports.platformArtifactTemplates=jt;
3
+ `),d=()=>{const f=a.join(`
4
+ `).trim();a.length=0,f&&s.push({type:"paragraph",text:f})},g=()=>{o.length&&s.push({type:"list",items:o.splice(0)})},p=()=>{const f=n.join(`
5
+ `).trim();n.length=0,f&&s.push({type:"pre",text:f})};for(let f=0;f<c.length;f+=1){const j=c[f]??"",E=j.trim();if(!E){d(),g(),p();continue}const B=ta(c,f);if(B){d(),g(),p(),s.push({headers:B.headers,rows:B.rows,type:"table"}),f=B.lastIndex;continue}const H=/^(#{1,6})\s+(.+)$/.exec(E);if(H){d(),g(),p();const V=(H[2]??"").replace(/\s+#+\s*$/,"").trim();V&&s.push({type:"heading",level:H[1]?.length,text:V});continue}if(/^\s*\|.+\|\s*$/.test(j)){d(),g(),n.push(j.trim());continue}const y=/^\s*[-*]\s+(.+)$/.exec(j);if(y){d(),p(),o.push(y[1]?.trim()??"");continue}g(),p(),a.push(E)}return d(),g(),p(),s},qe=t=>{const s=[],a=/(\*\*[^*]+\*\*|`[^`]+`)/g;let o=0;for(const n of t.matchAll(a)){const c=n[0],d=n.index??0;d>o&&s.push(t.slice(o,d)),c.startsWith("**")?s.push(e.jsx("strong",{children:c.slice(2,-2)},`${d}-strong`)):s.push(e.jsx("code",{children:c.slice(1,-1)},`${d}-code`)),o=d+c.length}return o<t.length&&s.push(t.slice(o)),s},Nt=({content:t})=>{const s=sa(t);return s.length?e.jsx("div",{className:"make-ai-assistant__bubble make-ai-assistant__assistant-text",children:s.map((a,o)=>{if(a.type==="heading"){const n=a.level<=2?"h3":"h4";return e.jsx(n,{className:`make-ai-assistant__markdown-heading make-ai-assistant__markdown-heading--${a.level}`,children:qe(a.text)},`${o}-heading`)}return a.type==="paragraph"?e.jsx("p",{children:qe(a.text)},`${o}-paragraph`):a.type==="pre"?e.jsx("pre",{children:e.jsx("code",{children:a.text})},`${o}-pre`):a.type==="table"?e.jsx("div",{"aria-label":"表格内容,可横向滚动",className:"make-ai-assistant__markdown-table-scroll",role:"region",tabIndex:0,children:e.jsxs("table",{className:"make-ai-assistant__markdown-table",children:[e.jsx("thead",{children:e.jsx("tr",{children:a.headers.map((n,c)=>e.jsx("th",{scope:"col",children:qe(n)},`${c}-${n}`))})}),e.jsx("tbody",{children:a.rows.map((n,c)=>e.jsx("tr",{children:n.map((d,g)=>e.jsx("td",{children:qe(d)},`${g}-${d}`))},`${c}-${n.join("|")}`))})]})},`${o}-table`):e.jsx("ul",{children:a.items.map((n,c)=>e.jsx("li",{children:qe(n)},`${c}-${n}`))},`${o}-list`)})}):null},Wt=({assistantName:t})=>e.jsxs("div",{className:"make-ai-assistant__message-identity",children:[e.jsx(it,{className:"make-ai-assistant__avatar--message"}),e.jsx("span",{className:"make-ai-assistant__message-sender",children:t})]}),qt=t=>{for(let s=t.messages.length-1;s>=0;s-=1){const a=t.messages[s];if(a.role==="assistant"&&a.status==="streaming")return a.id}},aa=t=>{for(let s=t.messages.length-1;s>=0;s-=1)if(t.messages[s].role==="user")return s;return-1},Xt=t=>{const s=aa(t);if(!(s<0))for(let a=t.messages.length-1;a>s;a-=1){const o=t.messages[a];if(o.role==="assistant")return o.id}},na=t=>{if(t.status==="idle")for(let s=t.messages.length-1;s>=0;s-=1){const a=t.messages[s];if(a.role==="assistant"&&a.status==="complete")return a.id}},ra=t=>{for(let s=t.messages.length-1;s>=0;s-=1){const a=t.messages[s];if(a.role==="user")return a}},ia=(t,s)=>{const a=t.messages.findIndex(o=>o.id===s&&o.role==="user");return{...t,error:void 0,progress:void 0,status:"streaming",messages:a<0?t.messages:t.messages.slice(0,a+1)}},oa=t=>t.scrollHeight-t.scrollTop-t.clientHeight<=48,Lt=(t="smooth")=>globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches?"auto":t,ut=(t,s)=>{typeof t.scrollTo=="function"?t.scrollTo({top:t.scrollHeight,behavior:s}):t.scrollTop=t.scrollHeight},Yt=({error:t,onRetry:s})=>e.jsxs("div",{className:"make-ai-assistant__message-status make-ai-assistant__message-status--error","data-error-presentation":"request-failed",role:"alert",children:[e.jsxs("div",{className:"make-ai-assistant__message-status-header",children:[e.jsx("span",{className:"make-ai-assistant__message-status-icon","aria-hidden":"true",children:e.jsx(Gs,{})}),e.jsx("strong",{children:"请求未完成"})]}),e.jsx("span",{className:"make-ai-assistant__message-status-message",children:t.message}),t.retryable&&s?e.jsxs("button",{className:"make-ai-assistant__retry",type:"button",onClick:s,children:[e.jsx(Vt,{}),"重新发送"]}):null]}),ca=({error:t,onRetry:s})=>{const a=zs(t);return e.jsxs("section",{"aria-live":"assertive",className:"make-ai-assistant__load-failure","data-load-failure-kind":a.kind,role:"alert",children:[e.jsx("span",{className:"make-ai-assistant__load-failure-icon","aria-hidden":"true",children:e.jsxs("svg",{viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M5 12a7 7 0 0 1 13.4-2.8A4.5 4.5 0 0 1 18 18H7.5A4.5 4.5 0 0 1 5 12Z"}),e.jsx("path",{d:"m9.2 14.8 5.6-5.6M9.2 9.2l5.6 5.6"})]})}),e.jsxs("div",{className:"make-ai-assistant__load-failure-copy",children:[e.jsx("span",{className:"make-ai-assistant__load-failure-label",children:a.label}),e.jsx("h3",{children:a.title}),e.jsx("p",{children:a.description})]}),e.jsxs("button",{className:"make-ai-assistant__retry make-ai-assistant__retry--primary",type:"button",onClick:s,children:[e.jsx(Vt,{}),a.actionLabel]})]})},Zt=({active:t,steps:s})=>{if(!t||!s?.length)return null;const a=s[s.length-1]??"处理中";return e.jsxs("details",{className:"make-ai-assistant__process",open:!0,children:[e.jsxs("summary",{children:[e.jsxs("span",{className:"make-ai-assistant__progress",role:"status",children:[e.jsx("span",{"aria-hidden":"true"}),e.jsx("span",{children:a})]}),e.jsxs("span",{className:"make-ai-assistant__process-count",children:[s.length," 步"]})]}),e.jsx("ol",{children:s.map((o,n)=>e.jsxs("li",{"data-step-active":n===s.length-1?!0:void 0,children:[e.jsx("span",{"aria-hidden":"true"}),e.jsx("span",{children:o})]},`${n}-${o}`))})]})},la=({copyFeedback:t,onCopy:s,onRegenerate:a})=>!s&&!a?null:e.jsxs("div",{className:"make-ai-assistant__reply-actions","aria-label":"回复操作",children:[s?e.jsx("button",{"aria-label":"复制回答",className:"make-ai-assistant__reply-action make-ai-assistant__reply-copy","data-tooltip":"复制",type:"button",onClick:s,children:e.jsx(Ks,{})}):null,a?e.jsx("button",{"aria-label":"重新生成",className:"make-ai-assistant__reply-action make-ai-assistant__reply-regenerate","data-tooltip":"重新生成",type:"button",onClick:a,children:e.jsx(Vs,{})}):null,t?e.jsx("span",{className:"make-ai-assistant__reply-feedback","data-copy-status":t.status,role:"status",children:t.message}):null]}),$t=({assistantName:t,error:s,onRetry:a,progress:o})=>{const n=s?"error":"progress";return s?.message??o?.message?e.jsx("article",{"aria-label":`${t}的${n==="error"?"错误消息":"状态消息"}`,className:`make-ai-assistant__message make-ai-assistant__message--assistant make-ai-assistant__message--${n}`,"data-message-role":"assistant","data-message-state":n,children:e.jsxs("div",{className:"make-ai-assistant__message-turn",children:[e.jsx(Wt,{assistantName:t}),e.jsx("div",{className:"make-ai-assistant__message-stack",children:s?e.jsx(Yt,{error:s,onRetry:a}):e.jsx(Zt,{active:!0,steps:o?.steps})})]})}):null},da=(t,s,a,o,n,c,d,g,p,f,j,E,B,H,y,V)=>{const Q=Xt(t),W=qt(t),v=na(t);let u;return t.messages.map(l=>{if(l.intermediate)return e.jsxs("details",{className:"make-ai-assistant__process",children:[e.jsx("summary",{children:"处理过程"}),e.jsx(Nt,{content:l.content})]},l.id);const T=l.role==="assistant",N=u;T||(u=l);const ae=l.id===W,R=l.id===Q?t.error:void 0,G=l.error??R,K=!T&&!!(p?.trim()||f),L=T?d:p?.trim()||"用户",q=T&&l.status==="complete"&&!G&&(l.content.trim()||l.id===v);return e.jsx("article",{"aria-label":`${L}的消息`,className:`make-ai-assistant__message make-ai-assistant__message--${l.role}`,"data-message-role":l.role,"data-message-state":G?"error":void 0,"data-message-status":l.status,"data-message-has-identity":T||K?!0:void 0,children:e.jsxs("div",{className:"make-ai-assistant__message-turn",children:[T?e.jsx(Wt,{assistantName:d}):K?e.jsx(Qs,{userAvatarUrl:f,userName:p}):null,e.jsxs("div",{className:"make-ai-assistant__message-stack",children:[T&&l.responseId&&t.responses?.[l.responseId]?.status==="cancelled"?e.jsx("p",{className:"make-ai-assistant__response-status",role:"status",children:"已停止生成"}):null,l.content?T?e.jsx(Nt,{content:l.content}):e.jsx("div",{className:"make-ai-assistant__bubble",children:l.content}):l.status==="streaming"?e.jsxs("div",{className:"make-ai-assistant__typing","aria-label":`${d}正在思考`,children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}):null,T?e.jsx(Zt,{active:ae&&t.status==="streaming",steps:l.progressSteps}):null,G?e.jsx(Yt,{error:G,onRetry:R?g:void 0}):null,l.artifacts.map(ne=>e.jsx(Ot,{artifact:ne,context:s,onAction:n,onActionError:c,registry:a,theme:o},ne.id)),y&&V&&t.threadId?e.jsx(ks,{message:l,context:s,transport:V,chatId:t.threadId}):null,y&&V?.features?.feedback?e.jsx(js,{message:l,manager:y}):null,q?e.jsx(la,{copyFeedback:j?.messageId===l.id?{message:j.message,status:j.status}:void 0,onCopy:l.content.trim()?()=>B(l.id,l.content):void 0,onRegenerate:E&&l.id===v&&N?()=>H({userMessage:N,assistantMessage:l}):void 0}):null]})]})},`${t.threadId??"local"}:${l.id}`)})};function Gt({assistantName:t="AI 助手",brandName:s,context:a,onAction:o,onActionError:n,onClose:c,onNewConversation:d,headerHeight:g,privacyNotice:p,registry:f,subtitle:j,suggestions:E,title:B,theme:H,transport:y,userAvatarUrl:V,userName:Q,visible:W}){const v=gs(a,y),u=As(a,y,v),l=Ut(s,B),T=p?.trim(),N=Ns(j,a.app.name),ae=Ps(g),R=mt(H),G=R||ae?{...R,...ae?{"--make-ai-internal-header-height":ae}:{}}:void 0,[K,L]=r.useState(""),[q,ne]=r.useState(!1),[re,de]=r.useState(!1),ye=v.enabled?y.scopeKey?.(a)??a.app.id:"";r.useLayoutEffect(()=>{v.enabled&&L("")},[ye,v.enabled]);const[be,X]=r.useState(x.createAssistantConversationState),k=v.enabled?v.state:be,b=v.enabled?v.setState:X,P=r.useRef(k);P.current=k;const[Y,ee]=r.useState(void 0),[Se,C]=r.useState(void 0),[te,ie]=r.useState(0),[ue,je]=r.useState(()=>y.loadConversation?"loading":"ready"),J=v.enabled?v.loading&&!k.messages.length?"loading":"ready":ue,[ve,_e]=r.useState(void 0),[Xe,oe]=r.useState(!1),[me,Ye]=r.useState(!1),[ke,Ze]=r.useState(void 0),Ie=r.useRef(void 0),Ae=r.useRef(void 0),we=r.useRef(0),Ge=r.useRef(null),Ee=r.useRef(null),Je=r.useRef(null),Te=r.useRef(null),i=r.useRef(null),h=r.useRef(null),_=r.useRef(null),A=r.useRef(null),w=r.useRef(!0),S=r.useRef(a.app.id),I=r.useRef(W),z=r.useId(),F=r.useId(),O=r.useMemo(()=>f??zt(),[f]),he=r.useMemo(()=>Ss(E),[E]),Be=()=>{const m=h.current,$=_.current;if(!m||!$||typeof window>"u")return;const D=Fs(m.getBoundingClientRect(),$.getBoundingClientRect(),window.innerHeight,window.innerWidth);Ze(U=>U?.left===D.left&&U.top===D.top&&U.placement===D.placement?U:D)},ze=()=>Ye(!0),ce=()=>Ye(!1),Ne=ke?{left:`${ke.left}px`,top:`${ke.top}px`}:void 0;r.useLayoutEffect(()=>{if(!me||!T){Ze(void 0);return}Be()},[me,T]),r.useEffect(()=>{if(!me||!T)return;const m=()=>Be();return window.addEventListener("resize",m),window.addEventListener("scroll",m,!0),()=>{window.removeEventListener("resize",m),window.removeEventListener("scroll",m,!0)}},[me,T]);const ge=m=>{const $=Ie.current,D=Ae.current?.iterator;return!$&&!D?!1:(we.current+=1,Ie.current=void 0,Ae.current=void 0,console.info("[make-ai-assistant] local run cancellation requested",{reason:m}),$?.abort(),St(D),!0)};r.useEffect(()=>()=>{ge("unmount")},[]),r.useEffect(()=>{if(v.enabled)return;const m=y.loadConversation,$=S.current!==a.app.id;if(S.current=a.app.id,ge("reinitialize"),$&&(L(""),w.current=!0),ee(void 0),C(void 0),oe(!1),b(x.createAssistantConversationState()),!m){_e(void 0),je("ready");return}const D=new AbortController;return _e(void 0),je("loading"),console.info("[make-ai-assistant] conversation load start",{appId:a.app.id}),m.call(y,a,{signal:D.signal}).then(U=>{D.signal.aborted||(b(x.createAssistantConversationState(U)),je("ready"),console.info("[make-ai-assistant] conversation load success",{appId:a.app.id,messageCount:U.messages.length}))}).catch(U=>{D.signal.aborted||(console.error("[make-ai-assistant] conversation load failed",{appId:a.app.id,errorType:U instanceof Error?U.name:typeof U}),_e(U),je("error"))}),()=>D.abort()},[a.app.id,te,y,v.enabled]),r.useEffect(()=>{const m=Ee.current;if(!m||!w.current)return;oe(!1);const $=requestAnimationFrame(()=>{if(!w.current)return;const D=k.status==="streaming"||globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches?"auto":"smooth";ut(m,D)});return()=>cancelAnimationFrame($)},[k.messages,k.progress,k.status]),r.useEffect(()=>{W||(ne(!1),de(!1))},[W]),r.useEffect(()=>{const m=W&&!I.current;if(I.current=W,!m)return;const $=requestAnimationFrame(()=>{const D=Ee.current;if(D&&w.current){oe(!1);const Ue=P.current.status==="streaming"?"auto":Lt();ut(D,Ue)}else D&&oe(P.current.messages.length>0);const U=Je.current;(U&&!U.disabled?U:A.current??Ge.current?.querySelector("button:not(:disabled)"))?.focus()});return()=>cancelAnimationFrame($)},[W]);const Jt=()=>{const m=Ee.current;if(!m)return;const $=oa(m);w.current=$,oe(!$&&P.current.messages.length>0)},Qt=()=>{const m=Ee.current;if(!m)return;w.current=!0,oe(!1);const $=Lt();ut(m,$)},ft=async(m,$)=>{const D=m.trim(),U=P.current,xe=$?.regenerateFrom,Ue=y.regenerate;if(!D||J!=="ready"||U.status==="streaming"||Ie.current||xe&&!Ue)return;if(x.countCodePointsUpTo(D,x.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)>x.MAKE_AI_CONVERSATION_LIMITS.messageCharacters){ee(`输入内容过长,请控制在 ${x.MAKE_AI_CONVERSATION_LIMITS.messageCharacters} 个字符以内`);return}const tt={id:xe?.userMessage.id??Ms("user"),content:D},st=xe?ia(U,xe.userMessage.id):x.appendUserMessage(U,tt),at=new AbortController,Le=we.current+1;we.current=Le,Ie.current=at,ee(void 0),C(void 0),oe(!w.current&&U.messages.length>0),xe||L(""),b(st);try{let Me=!1,se,xt=0,yt=0,bt=0,ot=0,He=0;const Ke=new Map,jt=new Set,_t=new Set([...st.messages.map(nt=>nt.id),tt.id]),Ve=new Set,kt=Ce.createArtifactCapabilities(O),It={signal:at.signal};let ct;if(xe){if(!Ue)throw new Z("当前 AI 助手不支持重新生成");ct=Ue({threadId:st.threadId,message:tt,assistantMessage:{id:xe.assistantMessage.id,content:xe.assistantMessage.content},context:a,capabilities:kt},It)}else ct=y.run({threadId:st.threadId,message:tt,context:a,capabilities:kt},It);const At=ct[Symbol.asyncIterator]();for(Ae.current={iterator:At,requestVersion:Le};;){const nt=await At.next();if(we.current!==Le||nt.done)break;let M;try{M=x.parseAssistantEvent(nt.value)}catch(le){throw new Z(le instanceof Error?le.message:"Invalid assistant event")}if(M.type==="message.start"){if(se!==void 0&&se!==M.runId)throw new Z("AI 助手响应 run id 不一致");if(se??=M.runId,yt+=1,yt>x.MAKE_AI_CONVERSATION_LIMITS.assistantMessagesPerRun)throw new Z("AI 助手单次响应消息数量超过限制");if(_t.has(M.messageId))throw new Z("AI 助手响应包含重复的 message id");_t.add(M.messageId),Ve.add(M.messageId),Ke.set(M.messageId,0)}if(M.type==="message.delta"){if(!Ve.has(M.messageId))throw new Z("AI 助手响应事件顺序无效");const le=Ke.get(M.messageId)??0,$e=x.countCodePointsUpTo(M.delta,x.MAKE_AI_CONVERSATION_LIMITS.messageCharacters-He);if(He+$e>x.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)throw new Z("AI 助手响应文本超过大小限制");He+=$e,Ke.set(M.messageId,le+$e)}if(M.type==="message.replace"){if(!Ve.has(M.messageId))throw new Z("AI 助手响应事件顺序无效");const le=Ke.get(M.messageId)??0,$e=x.countCodePointsUpTo(M.content,x.MAKE_AI_CONVERSATION_LIMITS.messageCharacters),wt=He-le+$e;if(wt>x.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)throw new Z("AI 助手响应文本超过大小限制");He=wt,Ke.set(M.messageId,$e)}if(M.type==="run.progress"){if(se!==void 0&&se!==M.runId)throw new Z("AI 助手响应 run id 不一致");if(se??=M.runId,bt+=1,bt>x.MAKE_AI_CONVERSATION_LIMITS.progressStepsPerRun)throw new Z("AI 助手处理过程数量超过限制");const le=x.countCodePointsUpTo(M.message,x.MAKE_AI_CONVERSATION_LIMITS.progressCharactersPerRun-ot);if(ot+le>x.MAKE_AI_CONVERSATION_LIMITS.progressCharactersPerRun)throw new Z("AI 助手处理过程文本超过大小限制");ot+=le}if(M.type==="artifact"){if(!Ve.has(M.messageId))throw new Z("AI 助手响应事件顺序无效");if(xt+=1,xt>x.MAKE_AI_CONVERSATION_LIMITS.artifactsPerRun)throw new Z("AI 助手单次响应 Artifact 数量超过限制");if(jt.has(M.artifact.id))throw new Z("AI 助手响应包含重复的 Artifact id");jt.add(M.artifact.id)}if(M.type==="message.complete"&&!Ve.delete(M.messageId))throw new Z("AI 助手响应事件顺序无效");if(M.type==="run.complete"&&se!==void 0&&se!==M.runId)throw new Z("AI 助手响应 run id 不一致");if(M.type==="run.cancelled"&&M.runId!==void 0&&se!==void 0&&se!==M.runId)throw new Z("AI 助手响应 run id 不一致");if(b(le=>x.reduceAssistantEvent(le,M)),M.type==="error"||M.type==="run.cancelled"||M.type==="run.complete"){Me=!0;break}}if(!Me)throw new Z("AI 助手流式响应在终止事件前结束")}catch(Me){if(we.current!==Le)return;if(at.signal.aborted){b(se=>x.reduceAssistantEvent(se,{type:"run.cancelled"}));return}console.error("[make-ai-assistant] assistant run failed",{appId:a.app.id,errorType:Me instanceof Error?Me.name:typeof Me}),b(se=>x.reduceAssistantEvent(se,{type:"error",code:"TRANSPORT_ERROR",message:Me instanceof Z?Me.message:"连接失败,请重试",retryable:!0}))}finally{we.current===Le&&Ie.current===at&&(Ie.current=void 0),Ae.current?.requestVersion===Le&&(St(Ae.current.iterator),Ae.current=void 0)}},Qe=m=>{if(v.enabled){if(u.pending)return ee("请等待附件上传完成,或移除失败的附件"),Promise.resolve();if(u.parts.some(U=>!y.features?.modelInputKinds?.includes(U.kind)))return ee("当前模型尚未开放此类附件理解,已上传原件可保留或移除"),Promise.resolve();const $=m.trim(),D=u.parts.length?[...$?[{id:Oe(),kind:"text",text:$}]:[],...u.parts]:void 0;return L(""),u.clear(),v.send($,D)}return ft(m)},es=m=>ft(m.userMessage.content,{regenerateFrom:m}),ts=async(m,$)=>{try{await Us($),C({messageId:m,message:"已复制",status:"success"})}catch(D){console.error("[make-ai-assistant] copy answer failed",{errorType:D instanceof Error?D.name:typeof D}),C({messageId:m,message:"复制失败",status:"error"})}},ss=m=>{m.preventDefault(),Qe(K)},as=m=>{m.key==="Enter"&&!m.shiftKey&&!m.nativeEvent.isComposing&&(m.preventDefault(),Qe(K))},ns=()=>{if(v.enabled){v.stop();return}ge("stop")&&b(m=>x.reduceAssistantEvent(m,{type:"run.cancelled"}))},pt=()=>{if(de(!1),v.enabled){L(""),v.create(),d?.();return}ge("new-conversation"),L(""),ee(void 0),C(void 0),oe(!1),w.current=!0,b(x.createAssistantConversationState()),d?.()},vt=v.enabled&&v.cancelling.length?"停止中":y.features?.remoteCancellation===!1?"停止接收":"停止生成",rs=qt(k),is=Xt(k),et=ra(k),os=typeof y.regenerate=="function"&&y.features?.regeneration!==!1,gt=()=>{if(v.enabled){v.retry();return}et&&Qe(et.content)},cs=m=>{if(m.key==="Escape"&&!(!q&&!re)){if(m.preventDefault(),m.stopPropagation(),q){ne(!1),Te.current?.focus();return}de(!1),i.current?.focus()}};return e.jsxs("section",{className:`make-ai-assistant make-ai-assistant__panel${v.enabled?" make-ai-assistant__panel--managed":""}`,ref:Ge,style:G,onKeyDown:cs,onDragOver:m=>{u.enabled&&m.dataTransfer.types.includes("Files")&&m.preventDefault()},onDrop:m=>{u.enabled&&m.dataTransfer.files.length&&(m.preventDefault(),u.add(Array.from(m.dataTransfer.files)))},children:[e.jsxs("header",{className:"make-ai-assistant__header",children:[e.jsx("div",{className:"make-ai-assistant__header-leading",children:v.enabled?e.jsxs("button",{"aria-controls":F,"aria-expanded":re,"aria-haspopup":"dialog","aria-label":"任务列表",className:"make-ai-assistant__task-list-trigger",ref:i,type:"button",onClick:()=>de(m=>!m),children:[e.jsx(Ys,{}),e.jsx("span",{children:"任务列表"}),e.jsx(Zs,{})]}):null}),e.jsxs("div",{className:"make-ai-assistant__header-center",children:[e.jsx(it,{}),e.jsxs("div",{className:"make-ai-assistant__header-content",children:[e.jsxs("div",{className:"make-ai-assistant__header-title-row",children:[e.jsx("h2",{className:"make-ai-assistant__header-title",title:l,children:l}),v.enabled?e.jsx("span",{className:"make-ai-assistant__current-conversation",children:v.chat?.title||"新对话"}):null,e.jsx("span",{className:"make-ai-assistant__read-only-tag",children:"只读"})]}),e.jsxs("div",{className:"make-ai-assistant__header-context",children:[e.jsx("p",{title:N,children:N}),T?e.jsxs(e.Fragment,{children:[e.jsx("span",{"aria-describedby":z,"aria-label":`使用提示:${T}`,className:"make-ai-assistant__header-context-help","data-tooltip":T,ref:h,role:"note",tabIndex:0,onBlur:ce,onFocus:ze,onPointerEnter:ze,onPointerLeave:ce,children:e.jsx(Ws,{})}),e.jsx("span",{"aria-hidden":!me,className:"make-ai-assistant__header-context-tooltip","data-placement":ke?.placement,"data-positioned":ke?!0:void 0,"data-visible":me||void 0,id:z,ref:_,role:"tooltip",style:Ne,children:T})]}):null]})]})]}),e.jsxs("div",{className:"make-ai-assistant__header-actions",children:[y.features?.newConversation!==!1?e.jsx("button",{"aria-label":"新建对话",className:"make-ai-assistant__icon-button",type:"button",onClick:pt,children:e.jsx(Xs,{})}):null,c?e.jsx("button",{"aria-label":`关闭 ${l}`,className:"make-ai-assistant__icon-button",type:"button",onClick:c,children:e.jsx(Hs,{})}):null]})]}),v.enabled&&re?e.jsx(bs,{id:F,manager:v,triggerRef:i,onDismiss:()=>de(!1),onNewConversation:y.features?.newConversation!==!1?pt:void 0}):null,e.jsxs("div",{className:"make-ai-assistant__body","aria-live":"polite","aria-relevant":"additions text",ref:Ee,role:"log",onScroll:Jt,children:[J==="loading"?e.jsxs("div",{className:"make-ai-assistant__empty",role:"status",children:[e.jsx(it,{}),e.jsx("h3",{children:"正在恢复对话"}),e.jsx("p",{children:"正在读取当前 App 的历史消息…"})]}):J==="error"?e.jsx("div",{className:"make-ai-assistant__empty",children:e.jsx(ca,{error:ve,onRetry:()=>ie(m=>m+1)})}):k.messages.length===0?e.jsxs("div",{className:"make-ai-assistant__empty",children:[e.jsx(it,{}),e.jsx("h3",{children:"有什么可以帮你?"}),e.jsx("p",{children:"我会结合当前 App、页面位置和宿主允许的上下文回答,并把过程与结果分开展示。"})]}):da(k,a,O,H,o,n,t,et?gt:void 0,Q,V,Se,os,(m,$)=>{ts(m,$)},m=>{es(m)},v.enabled?v:void 0,y),k.progress&&!rs?e.jsx($t,{assistantName:t,progress:k.progress}):null,k.error&&!is?e.jsx($t,{assistantName:t,error:k.error,onRetry:et?gt:void 0}):null]}),Xe?e.jsx("button",{"aria-label":"回到最新消息",className:"make-ai-assistant__back-to-latest",type:"button",onClick:Qt,children:e.jsx(qs,{})}):null,e.jsxs("footer",{className:"make-ai-assistant__composer-region",children:[u.enabled?e.jsx(Ts,{attachments:u}):null,J==="ready"&&he.length>0&&k.messages.length===0?e.jsx("div",{className:"make-ai-assistant__suggestions","aria-label":"推荐问题",children:he.map((m,$)=>e.jsx("button",{type:"button",onClick:()=>{Qe(m)},children:m},`${$}-${m}`))}):null,e.jsxs("form",{className:"make-ai-assistant__composer",onSubmit:ss,children:[e.jsx("textarea",{"aria-label":`向 ${t} 提问`,"aria-describedby":Y?"make-ai-composer-error":void 0,"aria-invalid":Y?!0:void 0,autoFocus:!0,disabled:J!=="ready"||!v.enabled&&k.status==="streaming",placeholder:`询问当前 ${a.app.name??"App"} 中的数据…`,ref:Je,rows:2,value:K,onChange:m=>{L(m.currentTarget.value),ee(void 0)},onKeyDown:as,onPaste:m=>{u.enabled&&m.clipboardData.files.length&&(m.preventDefault(),u.add(Array.from(m.clipboardData.files)))}}),u.enabled?e.jsx(ws,{attachments:u,open:q,triggerRef:Te,onOpenChange:ne}):null,e.jsxs("div",{className:"make-ai-assistant__composer-actions",children:[k.status==="streaming"?e.jsx("button",{"aria-label":vt,className:"make-ai-assistant__send make-ai-assistant__send--stop","data-tooltip":vt,ref:A,disabled:v.enabled&&v.cancelling.includes(k.activeRunId??""),type:"button",onClick:ns,children:e.jsx("span",{"aria-hidden":"true"})}):e.jsx("button",{"aria-label":"发送",className:"make-ai-assistant__send",disabled:J!=="ready"||u.pending||!K.trim()&&!u.parts.length,type:"submit",children:e.jsx(Et,{})}),v.enabled&&k.status==="streaming"?e.jsx("button",{"aria-label":"发送",className:"make-ai-assistant__send",disabled:v.busy||u.pending||!K.trim()&&!u.parts.length,type:"submit",children:e.jsx(Et,{})}):null]})]}),Y?e.jsx("p",{id:"make-ai-composer-error",role:"alert",children:Y}):null,e.jsx("p",{children:"AI 生成的结果可能存在偏差,重要数据请核对明细。"})]})]})}function ua(t){return e.jsx(Gt,{...t,visible:!0})}function ma({defaultOpen:t=!1,hideLauncher:s=!1,launcher:a,launcherPosition:o="bottom-right",maxDrawerWidth:n,onOpenChange:c,open:d,...g}){const p=Ut(g.brandName,g.title),[f,j]=r.useState(t),[E,B]=r.useState(()=>t||d===!0),H=r.useRef(null),y=r.useRef(null),V=r.useRef(void 0),[Q,W]=r.useState(),[v,u]=r.useState(Ls),[l,T]=r.useState(!1),N=d??f,ae=mt(g.theme),R=Ds(n),G=()=>Os(v,R,typeof window>"u"?Ht:window.innerWidth),K=G(),L=Q===void 0?void 0:lt(Q,v,K),q=L===void 0&&R===void 0?void 0:{...L===void 0?{}:{"--make-ai-internal-drawer-width":`${L}px`},...R===void 0?{}:{"--make-ai-internal-drawer-max-width":`max(var(--make-ai-internal-drawer-min-width), ${R}px)`}};r.useLayoutEffect(()=>{L!==void 0&&L!==Q&&W(L)},[L,Q]);const ne=()=>{if(L!==void 0)return L;const b=y.current?.getBoundingClientRect().width;return b&&Number.isFinite(b)&&b>0?b:v},re=b=>{if(b.button!==0)return;const P=ne(),Y=Q===void 0?P:v;u(Y),V.current={minimumWidth:Y,pointerId:b.pointerId,startWidth:P,startX:b.clientX},T(!0),typeof b.currentTarget.setPointerCapture=="function"&&b.currentTarget.setPointerCapture(b.pointerId),b.preventDefault()},de=b=>{const P=V.current;if(!P||P.pointerId!==b.pointerId)return;const Y=lt(P.startWidth+P.startX-b.clientX,P.minimumWidth,G());W(Y)},ye=b=>{const P=V.current;!P||P.pointerId!==b.pointerId||(V.current=void 0,T(!1))},be=b=>{const P=b.key==="ArrowLeft"?Rt:b.key==="ArrowRight"?-Rt:void 0;if(P===void 0)return;b.preventDefault();const Y=ne(),ee=Q===void 0?Y:v;u(ee),W(lt(Y+P,ee,G()))},X=b=>{d===void 0&&j(b),c?.(b),b||requestAnimationFrame(()=>H.current?.focus())},k=()=>X(!N);return r.useEffect(()=>{N&&B(!0)},[N]),r.useEffect(()=>{if(!N)return;const b=P=>{P.key==="Escape"&&(X(!1),requestAnimationFrame(()=>H.current?.focus()))};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[c,N]),e.jsxs("div",{className:"make-ai-assistant","data-open":N||void 0,style:ae,children:[!s&&(!N||a)?a?a({open:N,toggle:k}):e.jsxs("button",{"aria-label":N?`关闭 ${p}`:`打开 ${p}`,"aria-expanded":N,className:"make-ai-assistant__launcher","data-launcher-position":o,ref:H,type:"button",onClick:k,children:[e.jsx("span",{className:"make-ai-assistant__launcher-orbit","aria-hidden":"true"}),e.jsx(Kt,{})]}):null,E?e.jsxs("aside",{"aria-label":p,"aria-modal":"false",className:"make-ai-assistant__drawer","data-resizing":l||void 0,hidden:!N,ref:y,role:"dialog",style:q,children:[e.jsx("div",{"aria-label":"调整对话框宽度","aria-orientation":"vertical","aria-valuemax":K,"aria-valuemin":v,"aria-valuenow":L??v,className:"make-ai-assistant__drawer-resize-handle",role:"separator",tabIndex:0,onKeyDown:be,onPointerCancel:ye,onPointerDown:re,onPointerMove:de,onPointerUp:ye}),e.jsx(Gt,{...g,onClose:()=>X(!1),visible:N})]}):null]})}exports.createArtifactCapabilities=Ce.createArtifactCapabilities;exports.createArtifactTemplateRegistry=Ce.createArtifactTemplateRegistry;exports.extendArtifactTemplateRegistry=Ce.extendArtifactTemplateRegistry;exports.resolveArtifactTemplate=Ce.resolveArtifactTemplate;exports.MAKE_AI_ARTIFACT_KINDS=x.MAKE_AI_ARTIFACT_KINDS;exports.MAKE_AI_ARTIFACT_LIMITS=x.MAKE_AI_ARTIFACT_LIMITS;exports.MAKE_AI_ARTIFACT_SCHEMA_VERSION=x.MAKE_AI_ARTIFACT_SCHEMA_VERSION;exports.MAKE_AI_CONVERSATION_LIMITS=x.MAKE_AI_CONVERSATION_LIMITS;exports.appendUserMessage=x.appendUserMessage;exports.createAssistantConversationState=x.createAssistantConversationState;exports.parseArtifact=x.parseArtifact;exports.parseAssistantEvent=x.parseAssistantEvent;exports.reduceAssistantEvent=x.reduceAssistantEvent;exports.validateArtifact=x.validateArtifact;exports.ArtifactRenderer=Ot;exports.AssistantPanel=ua;exports.MakeAiAssistant=ma;exports.createPlatformArtifactRegistry=zt;exports.formatArtifactValue=Re;exports.platformArtifactTemplates=Bt;