@qfei-design/make-ai-assistant 0.2.13 → 0.2.15

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 (41) hide show
  1. package/PUBLIC_API.md +18 -19
  2. package/README.md +18 -12
  3. package/capabilities.json +2 -1
  4. package/dist/client-protocol.d.ts +24 -0
  5. package/dist/client-types.d.ts +420 -0
  6. package/dist/client.cjs +2 -0
  7. package/dist/client.d.ts +18 -0
  8. package/dist/client.mjs +1154 -0
  9. package/dist/conversation-BpmWa2VL.cjs +1 -0
  10. package/dist/conversation-DuqMadaQ.js +888 -0
  11. package/dist/conversation-management-DZROhXyK.js +229 -0
  12. package/dist/conversation-management-f1y0yRvt.cjs +1 -0
  13. package/dist/core/conversation-management.d.ts +15 -5
  14. package/dist/core/conversation.d.ts +6 -5
  15. package/dist/index.cjs +1 -1
  16. package/dist/index.mjs +4 -4
  17. package/dist/make-app.cjs +1 -1
  18. package/dist/make-app.d.ts +8 -69
  19. package/dist/make-app.mjs +236 -703
  20. package/dist/make-console.cjs +1 -1
  21. package/dist/make-console.mjs +1 -1
  22. package/dist/react/icons.d.ts +19 -0
  23. package/dist/react/make-ai-assistant.d.ts +1 -2
  24. package/dist/react/use-attachments.d.ts +2 -1
  25. package/dist/react/use-conversation-manager.d.ts +1 -0
  26. package/dist/react.cjs +4 -4
  27. package/dist/react.mjs +1619 -1346
  28. package/dist/sse.cjs +1 -1
  29. package/dist/sse.mjs +1 -1
  30. package/dist/styles.css +288 -105
  31. package/docs/backend-contract.md +3 -7
  32. package/docs/make-app-integration.md +23 -68
  33. package/examples/make-app/main.tsx +1 -1
  34. package/examples/make-app/transport.ts +36 -146
  35. package/package.ai.json +10 -7
  36. package/package.json +9 -3
  37. package/recipes.json +4 -3
  38. package/dist/conversation-CZfbgCXd.js +0 -1111
  39. package/dist/conversation-Cvh-IVRV.cjs +0 -1
  40. package/dist/make-app/protocol.d.ts +0 -27
  41. package/dist/make-app/stream.d.ts +0 -20
@@ -1 +1 @@
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
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const N=require("./sse.cjs"),E=require("./conversation-BpmWa2VL.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-CZfbgCXd.js";
2
+ import { c as D, M as m } from "./conversation-DuqMadaQ.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,19 @@
1
+ import type { SVGProps } from "react";
2
+ type IconProps = Omit<SVGProps<SVGSVGElement>, "children">;
3
+ export declare const AddIcon: (props: IconProps) => import("react").JSX.Element;
4
+ export declare const CheckIcon: (props: IconProps) => import("react").JSX.Element;
5
+ export declare const CloseIcon: (props: IconProps) => import("react").JSX.Element;
6
+ export declare const DeleteIcon: (props: IconProps) => import("react").JSX.Element;
7
+ export declare const EditIcon: (props: IconProps) => import("react").JSX.Element;
8
+ export declare const LikeIcon: (props: IconProps) => import("react").JSX.Element;
9
+ export declare const UnlikeIcon: (props: IconProps) => import("react").JSX.Element;
10
+ export declare const PinIcon: (props: IconProps) => import("react").JSX.Element;
11
+ export declare const RefreshIcon: (props: IconProps) => import("react").JSX.Element;
12
+ export declare const WarningIcon: (props: IconProps) => import("react").JSX.Element;
13
+ export declare const ContractIcon: (props: IconProps) => import("react").JSX.Element;
14
+ export declare const CopyIcon: (props: IconProps) => import("react").JSX.Element;
15
+ export declare const DownIcon: (props: IconProps) => import("react").JSX.Element;
16
+ export declare const FullScreenIcon: (props: IconProps) => import("react").JSX.Element;
17
+ export declare const ListIcon: (props: IconProps) => import("react").JSX.Element;
18
+ export declare const UpIcon: (props: IconProps) => import("react").JSX.Element;
19
+ export {};
@@ -31,8 +31,7 @@ export interface MakeAiAssistantProps extends Omit<AssistantPanelProps, "onClose
31
31
  */
32
32
  launcherPosition?: MakeAiLauncherPosition;
33
33
  /**
34
- * Maximum desktop drawer width in pixels. Values below the drawer minimum use
35
- * the minimum instead. Defaults to `min(1024px, 72vw)`.
34
+ * Maximum desktop drawer width in pixels. Defaults to `min(1024px, 72vw)`.
36
35
  */
37
36
  maxDrawerWidth?: number;
38
37
  onOpenChange?: (open: boolean) => void;
@@ -29,6 +29,7 @@ export declare function AttachmentComposer({ attachments, onOpenChange, open, tr
29
29
  open: boolean;
30
30
  triggerRef: Ref<HTMLButtonElement>;
31
31
  }): import("react").JSX.Element;
32
- export declare function AttachmentDraftList({ attachments, }: {
32
+ export declare function AttachmentDraftList({ attachments, visible, }: {
33
33
  attachments: ReturnType<typeof useAttachments>;
34
+ visible: boolean;
34
35
  }): import("react").JSX.Element | null;
@@ -4,6 +4,7 @@ export declare const newRequestId: () => `${string}-${string}-${string}-${string
4
4
  export declare const operationError: (error: unknown) => string;
5
5
  export declare function useConversationManager(context: MakeAssistantHostContext, transport: AssistantTransport): {
6
6
  enabled: boolean;
7
+ canEdit: boolean;
7
8
  state: AssistantConversationState;
8
9
  setState: Dispatch<SetStateAction<AssistantConversationState>>;
9
10
  chats: AssistantChat[];
package/dist/react.cjs CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),c=require("react"),Ie=require("./index.cjs"),b=require("./conversation-Cvh-IVRV.cjs"),Xt=require("react-dom"),Ct=t=>t?.trim()||void 0,ge=(t,s)=>Ct(t)??s,dt=t=>{const s=Ct(t?.primary);if(s)return{"--make-ai-theme-primary":s,"--make-ai-theme-primary-hover":ge(t?.primaryHover,"color-mix(in srgb, var(--make-ai-theme-primary) 84%, #15233d)"),"--make-ai-theme-on-primary":ge(t?.onPrimary,"#fcfcff"),"--make-ai-theme-bg":ge(t?.background,"color-mix(in srgb, var(--make-ai-theme-primary) 2%, #fcfcff)"),"--make-ai-theme-surface":ge(t?.surface,"color-mix(in srgb, var(--make-ai-theme-primary) 4%, var(--make-ai-theme-bg))"),"--make-ai-theme-surface-strong":ge(t?.surfaceStrong,"color-mix(in srgb, var(--make-ai-theme-primary) 8%, var(--make-ai-theme-bg))"),"--make-ai-theme-text":ge(t?.text,"color-mix(in srgb, var(--make-ai-theme-primary) 12%, #252631)"),"--make-ai-theme-text-secondary":ge(t?.textSecondary,"color-mix(in srgb, var(--make-ai-theme-text) 74%, var(--make-ai-theme-primary))"),"--make-ai-theme-border":ge(t?.border,"color-mix(in srgb, var(--make-ai-theme-primary) 14%, var(--make-ai-theme-bg))"),"--make-ai-theme-overlay":ge(t?.overlay,"color-mix(in srgb, var(--make-ai-theme-text) 88%, var(--make-ai-theme-primary))"),"--make-ai-theme-on-overlay":ge(t?.onOverlay,"#fcfcff")}},_t=(t,s)=>!s||!c.isValidElement(t)||typeof t.type!="string"?t:c.cloneElement(t,{style:{...t.props.style,...s}});function Et({artifact:t,context:s,fallback:a,onAction:i,onActionError:o,registry:l,theme:d}){const h=dt(d),y=Ie.resolveArtifactTemplate(l,t,s);if(!y){const S=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 _t(S,h)}const p={context:s,onAction:i,onActionError:o,theme:d,themeStyle:h},C=y.template.render(t,s,p);return _t(C,h)}const ke=(t,s,a)=>{if(t==null||t==="")return"—";if(typeof t=="boolean")return t?"是":"否";if(typeof t!="number")return`${t}${s?.unit??""}`;const i=s?.precision,o={maximumFractionDigits:i??2,minimumFractionDigits:i};s?.style==="currency"&&s.currency?(o.style="currency",o.currency=s.currency):s?.style==="percent"&&(o.style="percent");try{const l=s?.style==="percent"?t/100:t;return`${new Intl.NumberFormat(a,o).format(l)}${s?.unit??""}`}catch{return`${t}${s?.unit??""}`}},Lt=t=>{let s=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(const i of t)s=Math.min(s,i),a=Math.max(a,i);return Number.isFinite(s)&&Number.isFinite(a)?{min:s,max:a}:{min:0,max:0}},$t=(t,s,a)=>{if(!a.onAction)return;const i=l=>{console.error("[make-ai-assistant] host action error handler failed",{actionId:t.id,artifactId:s.artifact.id,errorType:l instanceof Error?l.name:typeof l,intent:t.intent})},o=l=>{if(a.onActionError){try{Promise.resolve(a.onActionError(l,t,s)).catch(i)}catch(d){i(d)}return}console.error("[make-ai-assistant] host action failed",{actionId:t.id,artifactId:s.artifact.id,errorType:l instanceof Error?l.name:typeof l,intent:t.intent})};try{Promise.resolve(a.onAction(t,s)).catch(o)}catch(l){o(l)}},$e=(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:()=>$t(a,{artifact:t,context:s.context},s),children:[a.label,e.jsx("span",{"aria-hidden":"true",children:"→"})]},a.id))}):null,De=(t,s,a="",i)=>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:i,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]}),Gt=({artifact:t,renderContext:s})=>{const a=t.data.delta,i=a?ke(a.value,a.format==="percent"?{style:"percent"}:void 0,s.context.locale):void 0;return De(t,e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"make-ai-artifact__metric-value",children:ke(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:i}),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,$e(t,s)]}),"make-ai-artifact--metric",s.themeStyle)},Yt=({artifact:t,renderContext:s})=>De(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:ke(a.value,a.format,s.context.locale)}),a.hint?e.jsx("small",{children:a.hint}):null]},a.id))}),$e(t,s)]}),"make-ai-artifact--comparison",s.themeStyle),Jt=({artifact:t,renderContext:s})=>{const a=t.data.series.flatMap(d=>d.points.map(h=>h.y)),{max:i,min:o}=Lt(a),l=i-o||1;return De(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((h,y)=>{const p=18+(h.y-o)/l*70;return e.jsxs("div",{className:"make-ai-artifact__trend-point",children:[e.jsx("span",{"aria-label":`${h.x}: ${ke(h.y,d.format,s.context.locale)}`,className:"make-ai-artifact__trend-bar",role:"img",style:{height:`${p}%`},title:`${h.x}: ${ke(h.y,d.format,s.context.locale)}`}),e.jsx("small",{children:h.x})]},`${h.x}-${y}`)})})]},d.id))}),$e(t,s)]}),"make-ai-artifact--trend",s.themeStyle)},Qt=({artifact:t,renderContext:s})=>{const{max:a}=Lt(t.data.items.map(o=>Math.abs(o.value))),i=Math.max(a,1);return De(t,e.jsxs(e.Fragment,{children:[e.jsx("ol",{className:"make-ai-artifact__ranking",children:t.data.items.map((o,l)=>e.jsxs("li",{children:[e.jsx("span",{className:"make-ai-artifact__rank",children:l+1}),e.jsxs("span",{className:"make-ai-artifact__ranking-label",children:[e.jsx("span",{children:o.label}),o.description?e.jsx("small",{children:o.description}):null]}),e.jsx("span",{className:"make-ai-artifact__ranking-track","aria-hidden":"true",children:e.jsx("span",{style:{width:`${Math.abs(o.value)/i*100}%`}})}),e.jsx("strong",{children:ke(o.value,o.format,s.context.locale)})]},o.id))}),$e(t,s)]}),"make-ai-artifact--ranking",s.themeStyle)},es=(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}},ts=({artifact:t,renderContext:s})=>De(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 i=es(t,a),o=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(l=>e.jsxs("span",{children:[e.jsx("small",{children:l.label}),ke(a.values[l.key],l.format,s.context.locale)]},l.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:()=>$t(i,{artifact:t,context:s.context},s),children:o},a.id):e.jsx("div",{className:"make-ai-artifact__record",children:o},a.id)})}),t.data.total!==void 0?e.jsxs("p",{className:"make-ai-artifact__record-total",children:["共 ",t.data.total," 条"]}):null,$e(t,s)]}),"make-ai-artifact--record-list",s.themeStyle),ss=({artifact:t,renderContext:s})=>De(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})]}),$e(t,s)]}),"make-ai-artifact--notice",s.themeStyle),Ee=(t,s,a)=>({id:t,kinds:[s],priority:0,render:a}),as=[Ee("platform.metric.default","metric",(t,s,a)=>e.jsx(Gt,{artifact:t,renderContext:a})),Ee("platform.comparison.default","comparison",(t,s,a)=>e.jsx(Yt,{artifact:t,renderContext:a})),Ee("platform.trend.default","trend",(t,s,a)=>e.jsx(Jt,{artifact:t,renderContext:a})),Ee("platform.ranking.default","ranking",(t,s,a)=>e.jsx(Qt,{artifact:t,renderContext:a})),Ee("platform.record-list.default","record-list",(t,s,a)=>e.jsx(ts,{artifact:t,renderContext:a})),Ee("platform.notice.default","notice",(t,s,a)=>e.jsx(ss,{artifact:t,renderContext:a}))],Dt=Ie.createArtifactTemplateRegistry(as).templates,Ot=(t=Dt)=>Ie.createArtifactTemplateRegistry(t),Le=()=>globalThis.crypto.randomUUID(),ut=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 ns(t,s){const a=s.features?.conversationManagement===!0,i=a?s.scopeKey?.(t)??t.app.id:"",o=c.useRef(i);o.current=i;const l=c.useRef(i),[d,h]=c.useState(b.createAssistantConversationState),y=c.useRef(d),p=r=>{const u=typeof r=="function"?r(y.current):r;y.current=u,h(u)},[C,S]=c.useState([]),[R,V]=c.useState(),A=c.useRef(void 0),[D,g]=c.useState(""),[N,F]=c.useState(-1),[f,n]=c.useState(!1),[v,_]=c.useState(!1),[K,I]=c.useState(a),[X,G]=c.useState(!1),[U,J]=c.useState(),[me,re]=c.useState([]),[O,ae]=c.useState([]),ie=c.useRef(new Set),q=c.useRef(new Map),$=c.useRef(0),w=c.useRef(0),P=c.useRef(0),te=c.useRef(void 0),he=c.useRef(void 0),we=c.useRef(new Map),E=(r,u=i)=>w.current===r&&o.current===u,Q=()=>{const r=new AbortController;return ie.current.add(r),r},oe=r=>ie.current.delete(r),ce=r=>{A.current=r,V(r)},at=r=>{S(u=>u.map(x=>x.chatId===r.chatId?r:x))},fe=r=>{S(u=>u.filter(x=>x.chatId!==r))},xe=()=>{P.current+=1},pe=()=>{for(const r of q.current.values())r.abort();q.current.clear()},ee=r=>{r instanceof Error&&r.name==="AbortError"||(console.warn("[make-ai-assistant] conversation operation failed",{errorType:r instanceof Error?r.name:typeof r}),J(ut(r)))},_e=async r=>{if(!a||!s.listConversations)return;const u=w.current,x=++P.current,k=Q();try{const M=await s.listConversations(t,{cursor:r},{signal:k.signal});if(!E(u)||k.signal.aborted||x!==P.current)return;S(L=>[...new Map([...r?L:[],...M.chats].map(j=>[j.chatId,j])).values()]),g(M.nextCursor)}catch(M){E(u)&&!k.signal.aborted&&x===P.current&&ee(M)}finally{oe(k),E(u)&&x===P.current&&I(!1)}},ve=async(r,u,x)=>{const k=w.current,M=$.current;let L;try{for await(const j of r){if(!E(k)||u.signal.aborted||M!==$.current||A.current?.chatId!==x)return;const H=b.parseAssistantEvent(j);if(H.type==="response.accepted"||H.type==="response.state"){L=H.responseId;const B=q.current.get(L);if(B&&B!==u){H.type==="response.accepted"&&p(z=>b.reduceAssistantEvent(z,H)),u.abort();return}q.current.set(L,u)}p(B=>b.reduceAssistantEvent(B,H)),H.type==="response.terminal"&&(re(B=>B.filter(z=>z!==H.responseId)),_e())}}catch(j){E(k)&&!u.signal.aborted&&M===$.current&&(ee(j),L||p(H=>({...H,status:Object.values(H.responses??{}).some(B=>!b.isResponseTerminal(B.status))?"streaming":"error"})))}finally{L&&q.current.get(L)===u&&q.current.delete(L),oe(u)}},Oe=async(r,u,x,k)=>{if(!s.getResponse||!s.watchResponse)return;const M=new Set(r.filter(j=>j.role==="assistant"&&j.persistent).map(j=>j.responseId)),L=[...new Map(r.filter(j=>j.role==="user"&&j.responseId&&!M.has(j.responseId)).map(j=>[j.responseId,j.cursor??-1])).entries()].slice(-20);for(const[j,H]of L){if(!E(k)||x!==$.current)return;if(q.current.has(j))continue;const B=Q();try{const z=await s.getResponse(t,{chatId:u,responseId:j},{signal:B.signal});if(!E(k)||B.signal.aborted||x!==$.current||q.current.has(j))continue;p(ye=>b.reduceAssistantEvent(ye,b.isResponseTerminal(z.status)?{type:"response.snapshot",snapshot:z}:{type:"response.state",chatId:u,responseId:j,status:z.status})),z.status==="failed"||z.status==="cancelled"?p(ye=>b.reduceAssistantEvent(ye,{type:"response.terminal",chatId:u,responseId:j,status:z.status})):(q.current.set(j,B),ve(s.watchResponse(t,{chatId:u,responseId:j,historyCursor:H},{signal:B.signal}),B,u))}catch(z){E(k)&&!B.signal.aborted&&ee(z)}finally{q.current.get(j)!==B&&oe(B)}}},Fe=async r=>{const u=++$.current,x=w.current,k=Q();pe(),J(void 0),I(!0),re([]),he.current=void 0,ce(r),p({messages:[],status:"idle",threadId:r.chatId}),F(-1),n(!1),_(!1);try{const[M,L]=await Promise.all([s.getConversation(t,{chatId:r.chatId},{signal:k.signal}),s.loadConversation(t,{threadId:r.chatId,cursor:-1,signal:k.signal})]);if(!E(x)||k.signal.aborted||u!==$.current)return;if(M.chatId!==r.chatId||L.threadId!==r.chatId)throw new Error("Conversation mismatch");ce(M),p(b.createAssistantConversationState(L)),F(L.nextCursor??-1),n(L.hasMore??!1),Oe(L.messages,r.chatId,u,x)}catch(M){E(x)&&!k.signal.aborted&&u===$.current&&ee(M)}finally{oe(k),E(x)&&u===$.current&&I(!1)}},Ae=async()=>{if(A.current)return A.current;if(te.current??={requestId:Le()},te.current.promise)return te.current.promise;const r=w.current,u=$.current,x=Q(),k=te.current;return G(!0),k.promise=s.createConversation(t,{requestId:k.requestId},{signal:x.signal}).then(M=>{if(!E(r)||x.signal.aborted||u!==$.current)throw Object.assign(new Error("Stale create"),{name:"AbortError"});return te.current=void 0,ce(M),p({messages:[],status:"idle",threadId:M.chatId}),_e(),M}).finally(()=>{oe(x),k.promise=void 0,E(r)&&G(!1)}),k.promise},We=async()=>{if(!(X||te.current?.promise)){$.current+=1,pe(),ce(void 0),J(void 0),he.current=void 0,p(b.createAssistantConversationState()),n(!1),F(-1);try{await Ae()}catch(r){ee(r)}}},le=async r=>{const u=Q();he.current=r,J(void 0),y.current.messages.some(x=>x.id===r.message.id)||p(x=>b.appendUserMessage(x,r.message)),await ve(s.run(r,{signal:u.signal}),u,r.threadId)},Ve=async(r,u)=>{if(!(!r.trim()&&!u?.length))try{const x=await Ae(),k={id:Le(),content:r,...u?{parts:u}:{}};await le({threadId:x.chatId,message:k,context:t,capabilities:{artifactSchemaVersions:[],artifactKinds:[],templates:[]}})}catch(x){ee(x)}},qe=async()=>{const r=he.current;if(!r||r.threadId!==A.current?.chatId){A.current&&await Fe(A.current);return}const u=y.current.messages.find(x=>x.id===r.message.id);if(u?.responseId&&s.watchResponse){const x=u.responseId;if(q.current.has(x))return;const k=Q();q.current.set(x,k),J(void 0),await ve(s.watchResponse(t,{chatId:r.threadId,responseId:x,historyCursor:u.cursor},{signal:k.signal}),k,r.threadId)}else await le(r)},He=async(r=y.current.activeRunId)=>{const u=A.current;if(!u||!r||!s.cancelResponse||me.includes(r))return;const x=w.current,k=$.current,M=Q();re(L=>[...L,r]),J(void 0);try{const L=await s.cancelResponse(t,{chatId:u.chatId,responseId:r},{signal:M.signal});if(!E(x)||k!==$.current)return;if(b.isResponseTerminal(L.status))p(j=>b.reduceAssistantEvent(j,{type:"response.snapshot",snapshot:L})),re(j=>j.filter(H=>H!==r));else if(!q.current.has(r)&&s.watchResponse){const j=Q();q.current.set(r,j),ve(s.watchResponse(t,{chatId:u.chatId,responseId:r},{signal:j.signal}),j,u.chatId)}}catch(L){E(x)&&k===$.current&&(ee(L),re(j=>j.filter(H=>H!==r)))}finally{oe(M)}},Ze=async(r,u=A.current)=>{if(!u||X)return!1;const x=w.current,k=Q();G(!0),J(void 0);try{const M=await s.updateConversation(t,{chatId:u.chatId,expectedRevision:u.revision,...r},{signal:k.signal});return E(x)?(xe(),at(M),A.current?.chatId===M.chatId&&ce(M),!0):!1}catch(M){if(E(x)){ee(M);try{const L=await s.getConversation(t,{chatId:u.chatId},{signal:k.signal});E(x)&&A.current?.chatId===u.chatId&&ce(L)}catch{}_e()}return!1}finally{oe(k),E(x)&&G(!1)}},Xe=async(r=A.current)=>{if(!r||X)return!1;const u=w.current,x=Q();G(!0),J(void 0);try{return await s.deleteConversation(t,{chatId:r.chatId,expectedRevision:r.revision},{signal:x.signal}),E(u)?(xe(),fe(r.chatId),A.current?.chatId===r.chatId&&($.current+=1,pe(),ce(void 0),p(b.createAssistantConversationState())),!0):!1}catch(k){return E(u)&&ee(k),!1}finally{oe(x),E(u)&&G(!1)}},Ne=async(r,u,x="",k="")=>{const M=A.current;if(!M||!r.persistent||!s.setFeedback||O.includes(r.id))return;const L={chatId:M.chatId,messageId:r.id,rating:u,...x?{reason:x}:{},...k?{comment:k}:{}},j=we.current.get(r.id),{requestId:H,...B}=j??{requestId:""},z=j&&JSON.stringify(B)===JSON.stringify(L)?j:{...L,requestId:Le()};we.current.set(r.id,z);const ye=w.current,Re=$.current,Ge=Q();ae(de=>[...de,r.id]),J(void 0);try{const de=await s.setFeedback(t,z,{signal:Ge.signal});return!E(ye)||Re!==$.current||we.current.get(r.id)!==z?void 0:(p(Te=>({...Te,messages:Te.messages.map(m=>m.id===r.id&&de.revision>=(m.feedback?.revision??0)?{...m,feedback:de}:m)})),we.current.delete(r.id),!0)}catch(de){return E(ye)&&Re===$.current&&ee(de),!1}finally{oe(Ge),E(ye)&&ae(de=>de.filter(Te=>Te!==r.id))}},nt=async()=>{if(!A.current||!f||K)return;const r=w.current,u=$.current,x=A.current,k=Q();I(!0);try{const M=await s.loadConversation(t,{threadId:x.chatId,cursor:N,signal:k.signal});if(!E(r)||u!==$.current)return;const L=b.createAssistantConversationState(M),j=[...new Map([...y.current.messages,...L.messages].map(z=>[z.id,z])).values()];let H=0;const B=[];for(const z of j.slice(-200).reverse()){if(H+=[...z.content].length,H>1e6)break;B.unshift(z)}B.length<j.length&&_(!0),p(z=>({...z,messages:B})),F(M.nextCursor??N),n(M.hasMore??!1),Oe(M.messages,x.chatId,u,r)}catch(M){E(r)&&ee(M)}finally{oe(k),E(r)&&I(!1)}};c.useEffect(()=>(w.current+=1,l.current=i,te.current=void 0,he.current=void 0,we.current.clear(),ce(void 0),S([]),g(""),p(b.createAssistantConversationState()),J(void 0),I(a),G(!1),re([]),ae([]),a&&_e(),()=>{w.current+=1,$.current+=1;for(const r of ie.current)r.abort();ie.current.clear(),q.current.clear()}),[a,i,s]);const Me=l.current===i;return{enabled:a,state:Me?d:b.createAssistantConversationState(),setState:p,chats:Me?C:[],chat:Me?R:void 0,listCursor:D,historyMore:f,historyTruncated:v,loading:!Me||K,busy:X,error:Me?U:void 0,cancelling:me,feedbackBusy:O,refresh:_e,select:Fe,create:We,ensureChat:Ae,send:Ve,retry:qe,stop:He,update:Ze,remove:Xe,feedback:Ne,moreHistory:nt,setError:J}}const rs=()=>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"})]}),is=()=>e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"M12 5v14M5 12h14"})}),os=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"m4.5 16.8-.7 3.7 3.7-.7L18 9.3l-3-3L4.5 16.8Z"}),e.jsx("path",{d:"m13.8 7.5 3 3"})]}),cs=()=>e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"M5.5 7.5h13M9.5 7.5V5.7h5v1.8M8 10.5v6M12 10.5v6M16 10.5v6M7 7.5l.7 12h8.6l.7-12"})}),jt=()=>e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"m5 12.5 4.5 4.5L19 7.5"})}),kt=()=>e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"m6 6 12 12M18 6 6 18"})}),ls=({anchor:t,label:s,onDismiss:a})=>{const[i,o]=c.useState();if(c.useLayoutEffect(()=>{const d=()=>{if(!t.isConnected){a();return}const h=t.getBoundingClientRect(),y=h.top>=48?"above":"below";o({left:h.left+h.width/2,placement:y,top:y==="above"?h.top-8:h.bottom+8})};return d(),window.addEventListener("resize",d),document.addEventListener("scroll",d,!0),()=>{window.removeEventListener("resize",d),document.removeEventListener("scroll",d,!0)}},[t,a]),!i||typeof document>"u")return null;const l=t.closest(".make-ai-assistant")??document.body;return Xt.createPortal(e.jsx("span",{className:"make-ai-assistant__conversation-tooltip","data-placement":i.placement,role:"tooltip",style:{left:i.left,top:i.top},children:s}),l)},ds=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M7.5 10.5v9H4.8a1.8 1.8 0 0 1-1.8-1.8v-5.4a1.8 1.8 0 0 1 1.8-1.8h2.7Z"}),e.jsx("path",{d:"M7.5 19.5h8.1a2.4 2.4 0 0 0 2.3-1.8l1.4-5.4a1.5 1.5 0 0 0-1.5-1.8h-4.1l.7-3.4A2.4 2.4 0 0 0 12 4.2L7.5 10.5Z"})]}),us=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M7.5 13.5v-9H4.8A1.8 1.8 0 0 0 3 6.3v5.4a1.8 1.8 0 0 0 1.8 1.8h2.7Z"}),e.jsx("path",{d:"M7.5 4.5h8.1a2.4 2.4 0 0 1 2.3 1.8l1.4 5.4a1.5 1.5 0 0 1-1.5 1.8h-4.1l.7 3.4A2.4 2.4 0 0 1 12 19.8l-4.5-6.3Z"})]});function ms({id:t,manager:s,onDismiss:a,onNewConversation:i,triggerRef:o}){const[l,d]=c.useState(),[h,y]=c.useState(""),[p,C]=c.useState(),[S,R]=c.useState(),V=c.useRef(null),A=(n,v)=>{R(_=>_?.anchor===v&&_.label===n?_:{anchor:v,label:n})},D=n=>{R(v=>v?.anchor===n?void 0:v)},g=n=>({"data-tooltip":n,onBlur:v=>D(v.currentTarget),onFocus:v=>A(n,v.currentTarget),onPointerEnter:v=>A(n,v.currentTarget),onPointerLeave:v=>D(v.currentTarget)}),N=()=>{d(void 0),y("")},F=async n=>{const v=h.trim();v&&await s.update({title:v},n)&&N()},f=async n=>{await s.remove(n)&&C(void 0)};return c.useEffect(()=>{const n=v=>{const _=v.target;_ instanceof Node&&(V.current?.contains(_)||o.current?.contains(_)||a())};return document.addEventListener("pointerdown",n),()=>{document.removeEventListener("pointerdown",n)}},[a,o]),e.jsxs("div",{"aria-label":"任务列表",className:"make-ai-assistant__conversation-controls",id:t,ref:V,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(n=>{const v=l===n.chatId,_=p===n.chatId,K=n.title||"未命名对话";return e.jsxs("div",{className:"make-ai-assistant__conversation-row","data-editing":v||_||void 0,children:[_?e.jsxs("div",{"aria-label":"确认删除对话",className:"make-ai-assistant__conversation-delete-confirmation",role:"group",children:[e.jsxs("span",{children:["删除“",K,"”?"]}),e.jsx("button",{"aria-label":`确认删除:${K}`,className:"make-ai-assistant__conversation-row-action make-ai-assistant__conversation-row-action--danger",disabled:s.busy,type:"button",...g("确认删除"),onClick:()=>{f(n)},children:e.jsx(jt,{})}),e.jsx("button",{"aria-label":`取消删除:${K}`,className:"make-ai-assistant__conversation-row-action",disabled:s.busy,type:"button",...g("取消"),onClick:()=>C(void 0),children:e.jsx(kt,{})})]}):v?e.jsx("input",{"aria-label":"对话标题",autoFocus:!0,className:"make-ai-assistant__conversation-row-title-input",disabled:s.busy,maxLength:255,value:h,onChange:I=>y(I.currentTarget.value),onKeyDown:I=>{I.nativeEvent.isComposing||(I.key==="Escape"&&(I.preventDefault(),N()),I.key==="Enter"&&(I.preventDefault(),F(n)))}}):e.jsxs("button",{"aria-pressed":s.chat?.chatId===n.chatId,className:"make-ai-assistant__conversation-row-select",type:"button",onClick:()=>{a(),s.select(n)},children:[e.jsx(rs,{}),e.jsx("span",{children:K})]}),v?e.jsxs("div",{"aria-label":"修改标题操作",className:"make-ai-assistant__conversation-row-actions",role:"group",children:[e.jsx("button",{"aria-label":"确认修改标题",className:"make-ai-assistant__conversation-row-action",disabled:s.busy||!h.trim(),type:"button",...g("保存标题"),onClick:()=>{F(n)},children:e.jsx(jt,{})}),e.jsx("button",{"aria-label":"取消修改标题",className:"make-ai-assistant__conversation-row-action",disabled:s.busy,type:"button",...g("取消"),onClick:N,children:e.jsx(kt,{})})]}):_?null:e.jsxs("div",{className:"make-ai-assistant__conversation-row-actions",children:[e.jsx("button",{"aria-label":`${n.pinned?"取消置顶":"置顶"} ${K}`,className:"make-ai-assistant__conversation-row-pin",disabled:s.busy,type:"button",onClick:()=>{s.update({pinned:!n.pinned},n)},children:n.pinned?"★":"☆"}),e.jsx("button",{"aria-label":`修改标题:${K}`,className:"make-ai-assistant__conversation-row-action",disabled:s.busy,type:"button",...g("修改标题"),onClick:()=>{C(void 0),d(n.chatId),y(n.title)},children:e.jsx(os,{})}),e.jsx("button",{"aria-label":`删除:${K}`,className:"make-ai-assistant__conversation-row-action make-ai-assistant__conversation-row-action--danger",disabled:s.busy,type:"button",...g("删除"),onClick:()=>{N(),C(n.chatId)},children:e.jsx(cs,{})})]})]},n.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&&(s.historyMore||s.historyTruncated||s.state.historyTruncated)?e.jsxs("div",{className:"make-ai-assistant__conversation-history-actions",children:[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,i?e.jsxs("button",{className:"make-ai-assistant__conversation-new",type:"button",onClick:i,children:[e.jsx(is,{}),e.jsx("span",{children:"新建对话"})]}):null,S?e.jsx(ls,{anchor:S.anchor,label:S.label,onDismiss:()=>R(void 0)}):null]})}function hs({message:t,manager:s}){const[a,i]=c.useState(!1),[o,l]=c.useState(""),[d,h]=c.useState(""),y=s.feedbackBusy.includes(t.id);if(!t.persistent||t.role!=="assistant"||t.intermediate)return null;const p=t.feedback?.rating??"none";return e.jsxs("div",{"aria-label":"回答反馈",className:"make-ai-assistant__feedback",role:"group",children:[e.jsx("button",{type:"button","aria-label":"喜欢","aria-pressed":p==="like",className:"make-ai-assistant__reply-action make-ai-assistant__reply-feedback-action","data-tooltip":"喜欢",disabled:y,onClick:()=>{s.feedback(t,p==="like"?"none":"like")},children:e.jsx(ds,{})}),e.jsx("button",{type:"button","aria-label":"不喜欢","aria-pressed":p==="dislike",className:"make-ai-assistant__reply-action make-ai-assistant__reply-feedback-action","data-tooltip":"不喜欢",disabled:y,onClick:()=>{if(p==="dislike"){s.feedback(t,"none");return}l(t.feedback?.reason??""),h(t.feedback?.comment??""),i(!0)},children:e.jsx(us,{})}),p==="dislike"?e.jsx("button",{className:"make-ai-assistant__feedback-text-action",type:"button",disabled:y,onClick:()=>{l(t.feedback?.reason??""),h(t.feedback?.comment??""),i(!0)},children:"修改反馈"}):null,a?e.jsxs("form",{onSubmit:C=>{C.preventDefault(),s.feedback(t,"dislike",o,d).then(S=>{S&&i(!1)})},children:[e.jsx("input",{"aria-label":"反馈原因",maxLength:128,value:o,onChange:C=>l(C.currentTarget.value),placeholder:"原因(可选)"}),e.jsx("textarea",{"aria-label":"反馈说明",maxLength:4e3,value:d,onChange:C=>h(C.currentTarget.value),placeholder:"补充说明(可选)"}),e.jsx("button",{className:"make-ai-assistant__feedback-text-action",type:"submit",disabled:y,children:"提交反馈"}),e.jsx("button",{className:"make-ai-assistant__feedback-text-action",type:"button",onClick:()=>i(!1),children:"取消"})]}):null]})}const It=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 fs({part:t,context:s,transport:a,chatId:i}){const[o,l]=c.useState(),[d,h]=c.useState(),[y,p]=c.useState(!1),C=c.useRef([]),S=c.useRef(void 0);c.useEffect(()=>()=>{S.current?.abort(),C.current.forEach(V=>URL.revokeObjectURL(V))},[]);const R=async V=>{if(!a.readContent||y)return;const A=new AbortController;S.current=A,p(!0),h(void 0);try{const D=await a.readContent(s,{chatId:i,contentRef:t.media.contentRef},{signal:A.signal});if(A.signal.aborted)return;const g=new Blob([new Uint8Array(D).buffer],{type:V&&It.has(t.media.contentType)?t.media.contentType:"application/octet-stream"}),N=URL.createObjectURL(g);if(C.current.push(N),V)l(N);else{const F=document.createElement("a");F.href=N,F.download=t.name??"attachment",F.click()}}catch(D){A.signal.aborted||h(ut(D))}finally{A.signal.aborted||p(!1)}};return e.jsxs("div",{className:"make-ai-assistant__attachment",children:[e.jsxs("span",{children:[t.name??"附件"," · ",t.media.sizeBytes," 字节"]}),a.readContent?e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",disabled:y,onClick:()=>{R(!1)},children:"下载附件"}),It.has(t.media.contentType)?e.jsx("button",{type:"button",disabled:y,onClick:()=>{R(!0)},children:"预览附件"}):null]}):null,d?e.jsx("span",{role:"alert",children:d}):null,o&&t.kind==="image"?e.jsx("img",{src:o,alt:t.name??"附件图片"}):null,o&&t.kind==="audio"?e.jsx("audio",{src:o,controls:!0}):null,o&&t.kind==="video"?e.jsx("video",{src:o,controls:!0}):null]})}function ps({message:t,context:s,transport:a,chatId:i}){return e.jsx(e.Fragment,{children:t.parts?.map((o,l)=>o.kind==="text"?null:e.jsx(fs,{part:o,context:s,transport:a,chatId:i},o.id??`${t.id}:${l}`))})}const Ft=t=>t.type.split(";")[0].trim().toLowerCase()||"application/octet-stream",vs=t=>t.startsWith("image/")&&t!=="image/svg+xml"?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"file",gs=t=>{const s=Ft(t);if(!(!s.startsWith("image/")||s==="image/svg+xml"||typeof URL>"u"||typeof URL.createObjectURL!="function"))return URL.createObjectURL(t)},wt=t=>{t&&typeof URL<"u"&&typeof URL.revokeObjectURL=="function"&&URL.revokeObjectURL(t)},xs=(t,s)=>new Promise((a,i)=>{const o=new FileReader,l=()=>s.removeEventListener("abort",d),d=()=>{o.abort(),l(),i(Object.assign(new Error("Read aborted"),{name:"AbortError"}))};if(s.aborted){d();return}s.addEventListener("abort",d,{once:!0}),o.onload=()=>{l(),a(new Uint8Array(o.result))},o.onerror=()=>{l(),i(new Error("无法读取文件"))},o.readAsArrayBuffer(t)});function ys(t,s,a){const[i,o]=c.useState([]),l=c.useRef(new Map),d=c.useRef(Promise.resolve()),h=s.scopeKey?.(t)??t.app.id,y=c.useRef(h);y.current=h;const p=c.useRef(void 0),C=a.enabled&&s.features?.attachments===!0,S=(f,n)=>{!l.current.has(f.draft.id)||f.scope!==y.current||(f.draft={...f.draft,...n},o([...l.current.values()].map(v=>v.draft)))},R=()=>{for(const f of l.current.values())f.controller.abort(),wt(f.draft.previewUrl);l.current.clear(),o([]),p.current=void 0,d.current=Promise.resolve()};c.useEffect(()=>(R(),R),[h,s]),c.useEffect(()=>{p.current&&a.chat?.chatId!==p.current&&R()},[a.chat?.chatId]);const V=async f=>{const n=f.controller.signal,v=()=>{if(n.aborted||f.scope!==y.current||!l.current.has(f.draft.id))throw Object.assign(new Error("Upload aborted"),{name:"AbortError"})};try{if(v(),f.file.size>64<<20)throw new Error("文件不能超过 64 MiB");const _=await a.ensureChat();v(),p.current=_.chatId;const K=Ft(f.file);S(f,{status:"uploading",error:void 0});let I=f.draft.upload?await s.getUpload(t,{chatId:_.chatId,uploadId:f.draft.upload.id},{signal:n}):await s.startUpload(t,{chatId:_.chatId,fileId:f.draft.fileId,name:f.file.name,contentType:K,sizeBytes:f.file.size},{signal:n});if(v(),S(f,{upload:I}),I.name!==f.file.name||I.contentType!==K||I.sizeBytes!==f.file.size)throw new Error("上传文件身份不一致");if(I.status!=="ready"){I=await s.getUpload(t,{chatId:_.chatId,uploadId:I.id},{signal:n}),v();const X=new Set(I.completedParts),G=Math.ceil(f.file.size/I.partSize);for(let U=0;U<G;U+=1){if(v(),!X.has(U)){const J=await xs(f.file.slice(U*I.partSize,Math.min(f.file.size,(U+1)*I.partSize)),n);v(),await s.uploadPart(t,{chatId:_.chatId,uploadId:I.id,part:U,bytes:J},{signal:n}),v(),X.add(U)}S(f,{progress:X.size/Math.max(G,1)})}S(f,{status:"completing"}),I=await s.completeUpload(t,{chatId:_.chatId,uploadId:I.id},{signal:n}),v()}if(I.status!=="ready"||!I.content)throw new Error("上传尚未完成");S(f,{status:"ready",progress:1,upload:I})}catch(_){S(f,{status:n.aborted?"paused":"failed",error:n.aborted?void 0:ut(_)})}},A=f=>{if(C){if(f.length+l.current.size>32){a.setError("每条消息最多包含 32 个附件或文本片段");return}for(const n of f){const v={id:Le(),fileId:Le(),name:n.name,size:n.size,status:"queued",progress:0,previewUrl:gs(n)},_={draft:v,file:n,controller:new AbortController,scope:h};l.current.set(v.id,_),d.current=d.current.then(()=>V(_))}o([...l.current.values()].map(n=>n.draft))}},D=f=>{const n=l.current.get(f);!n||!["paused","failed"].includes(n.draft.status)||(n.controller=new AbortController,S(n,{status:"queued"}),d.current=d.current.then(()=>V(n)))},g=f=>{const n=l.current.get(f);n?.controller.abort(),wt(n?.draft.previewUrl),l.current.delete(f),o([...l.current.values()].map(v=>v.draft))},N=f=>l.current.get(f)?.controller.abort(),F=i.flatMap(f=>{const n=f.upload;if(f.status!=="ready"||!n?.content)return[];const v=vs(n.contentType);return[{id:f.id,kind:v,name:n.name,media:{contentRef:n.content.contentRef,contentType:n.contentType,sizeBytes:n.content.sizeBytes,digestSha256:n.content.digestSha256}}]});return{enabled:C,drafts:i,parts:F,pending:i.some(f=>f.status!=="ready"),add:A,retry:D,remove:g,pause:N,clear:R}}function bs({attachments:t,onOpenChange:s,open:a,triggerRef:i}){const o=c.useRef(null),l=c.useRef(null);c.useEffect(()=>{if(!a)return;const h=y=>{const p=y.target;p instanceof Node&&!o.current?.contains(p)&&s(!1)};return document.addEventListener("pointerdown",h),()=>{document.removeEventListener("pointerdown",h)}},[s,a]);const d=h=>{t.add(Array.from(h.files??[])),h.value="",s(!1)};return e.jsxs("div",{className:"make-ai-assistant__attachment-composer",ref:o,children:[e.jsx("button",{"aria-expanded":a,"aria-haspopup":"menu","aria-label":"添加附件",className:"make-ai-assistant__attachment-trigger",ref:i,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.jsx("div",{"aria-label":"附件选项",className:"make-ai-assistant__attachment-menu",role:"menu",children:e.jsxs("button",{role:"menuitem",type:"button",onClick:()=>l.current?.click(),children:[e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M12 15V4M7.5 8.5 12 4l4.5 4.5"}),e.jsx("path",{d:"M5 14v5h14v-5"})]}),e.jsx("span",{children:"上传文件或图片"})]})}):null,e.jsx("input",{"aria-label":"上传文件或图片",hidden:!0,multiple:!0,ref:l,type:"file",onChange:h=>d(h.currentTarget)})]})}function _s({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",{"data-status":s.status,children:[s.previewUrl?e.jsx("img",{alt:"",className:"make-ai-assistant__attachment-draft-preview",src:s.previewUrl}):e.jsx("span",{"aria-hidden":"true",className:"make-ai-assistant__attachment-draft-file",children:e.jsxs("svg",{viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M6 3h8l4 4v14H6z"}),e.jsx("path",{d:"M14 3v5h5M9 13h6M9 16h6"})]})}),e.jsxs("span",{className:"make-ai-assistant__attachment-draft-details",children:[e.jsx("span",{className:"make-ai-assistant__attachment-draft-name",title:s.name,children:s.name}),e.jsx("span",{className:"make-ai-assistant__attachment-draft-status",children: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",{"aria-label":`移除附件 ${s.name}`,className:"make-ai-assistant__attachment-draft-remove",type:"button",onClick:()=>t.remove(s.id),children:e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"m7 7 10 10M17 7 7 17"})})})]},s.id))})}):null}const js=t=>`${t}-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,ks="Make",Is=["总结当前页面数据","找出需要关注的记录","列出我有权限查看的数据对象"],Ut=(t,s)=>s??`${t?.trim()||ks} AI 助手`,ws=t=>t??Is,As=480,Pt=1024,Ms=.72,At=16,ot=(t,s,a)=>Math.min(Math.max(t,Math.min(s,a)),a),Rs=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0,Ns=(t,s,a)=>{const i=Math.min(Pt,a*Ms);return Math.max(t,Math.min(s??i,a))},Ts=t=>typeof t=="number"?Number.isFinite(t)?`${t}px`:void 0:t?.trim()||void 0;class Y extends Error{}const tt=(t,s)=>{if(!(typeof t!="object"||t===null))return t[s]},Ss=t=>{const s=tt(t,"status");return typeof s=="number"?s:tt(tt(t,"response"),"status")},Cs=t=>{const s=tt(t,"code"),a=Ss(t),i=t instanceof Error?t.message:"",o=[s,i].filter(y=>typeof y=="string").join(" ").toLowerCase(),d=globalThis.navigator?.onLine===!1||/network|fetch|timeout|offline|connection|网络|连接|超时/.test(o),h=typeof a=="number"&&a>=500||/server|service|服务器|服务异常/.test(o);return d?{actionLabel:"重新连接",description:"请检查网络后再试。",kind:"network",label:"网络连接",title:"网络连接不可用"}:h?{actionLabel:"重新加载",description:"服务暂时未能响应,请稍后重试。",kind:"service",label:"服务异常",title:"服务暂时不可用"}:{actionLabel:"重新加载",description:"请稍后重试;若问题持续出现,请联系管理员。",kind:"unknown",label:"加载异常",title:"暂时无法加载对话"}},Mt=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})}},Es=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")},Bt=()=>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"})]}),Ls=()=>e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"m6 6 12 12M18 6 6 18"})}),$s=()=>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"})]}),Ds=()=>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"})]}),Os=()=>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"})]}),Fs=()=>e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"M12 5v14M5 12h14"})}),Us=()=>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"})]}),Ps=()=>e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"m7 10 5 5 5-5"})}),Rt=()=>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"})]}),zt=()=>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"})]}),Bs=()=>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"})]}),st=({className:t=""})=>e.jsx("span",{className:`make-ai-assistant__avatar ${t}`.trim(),"aria-hidden":"true",children:e.jsx(Bt,{})}),zs=({src:t})=>t?e.jsx("span",{className:"make-ai-assistant__user-avatar","aria-hidden":"true",children:e.jsx("img",{alt:"",src:t})}):null,Ks=({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(zs,{src:t})]})},ct=t=>{const s=t.trim();if(!(!s.startsWith("|")||!s.endsWith("|")))return s.slice(1,-1).split("|").map(a=>a.trim())},Ws=t=>t.length>0&&t.every(s=>/^:?-{3,}:?$/.test(s)),Vs=(t,s)=>{const a=ct(t[s]??""),i=ct(t[s+1]??"");if(!a||!i||a.length!==i.length||!Ws(i))return;const o=[];let l=s+2;for(;l<t.length;){const d=ct(t[l]??"");if(!d||d.length!==a.length)break;o.push(d),l+=1}return{headers:a,lastIndex:l-1,rows:o}},qs=t=>{const s=[],a=[],i=[],o=[],l=t.replace(/\r\n?/g,`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),c=require("react"),ke=require("./index.cjs"),j=require("./conversation-BpmWa2VL.cjs"),ut=require("./conversation-management-f1y0yRvt.cjs"),Ft=require("react-dom"),Pt=t=>t?.trim()||void 0,fe=(t,s)=>Pt(t)??s,pt=t=>{const s=Pt(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")}},Nt=(t,s)=>!s||!c.isValidElement(t)||typeof t.type!="string"?t:c.cloneElement(t,{style:{...t.props.style,...s}});function Ut({artifact:t,context:s,fallback:a,onAction:o,onActionError:i,registry:l,theme:u}){const p=pt(u),d=ke.resolveArtifactTemplate(l,t,s);if(!d){const R=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 Nt(R,p)}const v={context:s,onAction:o,onActionError:i,theme:u,themeStyle:p},S=d.template.render(t,s,v);return Nt(S,p)}const xe=(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,i={maximumFractionDigits:o??2,minimumFractionDigits:o};s?.style==="currency"&&s.currency?(i.style="currency",i.currency=s.currency):s?.style==="percent"&&(i.style="percent");try{const l=s?.style==="percent"?t/100:t;return`${new Intl.NumberFormat(a,i).format(l)}${s?.unit??""}`}catch{return`${t}${s?.unit??""}`}},Dt=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}},Kt=(t,s,a)=>{if(!a.onAction)return;const o=l=>{console.error("[make-ai-assistant] host action error handler failed",{actionId:t.id,artifactId:s.artifact.id,errorType:l instanceof Error?l.name:typeof l,intent:t.intent})},i=l=>{if(a.onActionError){try{Promise.resolve(a.onActionError(l,t,s)).catch(o)}catch(u){o(u)}return}console.error("[make-ai-assistant] host action failed",{actionId:t.id,artifactId:s.artifact.id,errorType:l instanceof Error?l.name:typeof l,intent:t.intent})};try{Promise.resolve(a.onAction(t,s)).catch(i)}catch(l){i(l)}},Oe=(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:()=>Kt(a,{artifact:t,context:s.context},s),children:[a.label,e.jsx("span",{"aria-hidden":"true",children:"→"})]},a.id))}):null,Fe=(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]}),es=({artifact:t,renderContext:s})=>{const a=t.data.delta,o=a?xe(a.value,a.format==="percent"?{style:"percent"}:void 0,s.context.locale):void 0;return Fe(t,e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"make-ai-artifact__metric-value",children:xe(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,Oe(t,s)]}),"make-ai-artifact--metric",s.themeStyle)},ts=({artifact:t,renderContext:s})=>Fe(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:xe(a.value,a.format,s.context.locale)}),a.hint?e.jsx("small",{children:a.hint}):null]},a.id))}),Oe(t,s)]}),"make-ai-artifact--comparison",s.themeStyle),ss=({artifact:t,renderContext:s})=>{const a=t.data.series.flatMap(u=>u.points.map(p=>p.y)),{max:o,min:i}=Dt(a),l=o-i||1;return Fe(t,e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"make-ai-artifact__trend",children:t.data.series.map(u=>e.jsxs("div",{className:"make-ai-artifact__trend-series",children:[e.jsx("div",{className:"make-ai-artifact__trend-label",children:u.label}),e.jsx("div",{className:"make-ai-artifact__trend-bars",children:u.points.map((p,d)=>{const v=18+(p.y-i)/l*70;return e.jsxs("div",{className:"make-ai-artifact__trend-point",children:[e.jsx("span",{"aria-label":`${p.x}: ${xe(p.y,u.format,s.context.locale)}`,className:"make-ai-artifact__trend-bar",role:"img",style:{height:`${v}%`},title:`${p.x}: ${xe(p.y,u.format,s.context.locale)}`}),e.jsx("small",{children:p.x})]},`${p.x}-${d}`)})})]},u.id))}),Oe(t,s)]}),"make-ai-artifact--trend",s.themeStyle)},as=({artifact:t,renderContext:s})=>{const{max:a}=Dt(t.data.items.map(i=>Math.abs(i.value))),o=Math.max(a,1);return Fe(t,e.jsxs(e.Fragment,{children:[e.jsx("ol",{className:"make-ai-artifact__ranking",children:t.data.items.map((i,l)=>e.jsxs("li",{children:[e.jsx("span",{className:"make-ai-artifact__rank",children:l+1}),e.jsxs("span",{className:"make-ai-artifact__ranking-label",children:[e.jsx("span",{children:i.label}),i.description?e.jsx("small",{children:i.description}):null]}),e.jsx("span",{className:"make-ai-artifact__ranking-track","aria-hidden":"true",children:e.jsx("span",{style:{width:`${Math.abs(i.value)/o*100}%`}})}),e.jsx("strong",{children:xe(i.value,i.format,s.context.locale)})]},i.id))}),Oe(t,s)]}),"make-ai-artifact--ranking",s.themeStyle)},ns=(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}},rs=({artifact:t,renderContext:s})=>Fe(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=ns(t,a),i=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(l=>e.jsxs("span",{children:[e.jsx("small",{children:l.label}),xe(a.values[l.key],l.format,s.context.locale)]},l.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:()=>Kt(o,{artifact:t,context:s.context},s),children:i},a.id):e.jsx("div",{className:"make-ai-artifact__record",children:i},a.id)})}),t.data.total!==void 0?e.jsxs("p",{className:"make-ai-artifact__record-total",children:["共 ",t.data.total," 条"]}):null,Oe(t,s)]}),"make-ai-artifact--record-list",s.themeStyle),is=({artifact:t,renderContext:s})=>Fe(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})]}),Oe(t,s)]}),"make-ai-artifact--notice",s.themeStyle),Le=(t,s,a)=>({id:t,kinds:[s],priority:0,render:a}),os=[Le("platform.metric.default","metric",(t,s,a)=>e.jsx(es,{artifact:t,renderContext:a})),Le("platform.comparison.default","comparison",(t,s,a)=>e.jsx(ts,{artifact:t,renderContext:a})),Le("platform.trend.default","trend",(t,s,a)=>e.jsx(ss,{artifact:t,renderContext:a})),Le("platform.ranking.default","ranking",(t,s,a)=>e.jsx(as,{artifact:t,renderContext:a})),Le("platform.record-list.default","record-list",(t,s,a)=>e.jsx(rs,{artifact:t,renderContext:a})),Le("platform.notice.default","notice",(t,s,a)=>e.jsx(is,{artifact:t,renderContext:a}))],Ht=ke.createArtifactTemplateRegistry(os).templates,Bt=(t=Ht)=>ke.createArtifactTemplateRegistry(t),se=({children:t,...s})=>e.jsx("svg",{"aria-hidden":"true",fill:"none",focusable:"false",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8",viewBox:"0 0 24 24",...s,children:t}),vt=t=>e.jsx(se,{...t,children:e.jsx("path",{d:"M12 5v14M5 12h14"})}),cs=t=>e.jsx(se,{...t,children:e.jsx("path",{d:"m5 12 4.5 4.5L19 7"})}),ct=t=>e.jsx(se,{...t,children:e.jsx("path",{d:"m6 6 12 12M18 6 6 18"})}),Mt=t=>e.jsx(se,{...t,children:e.jsx("path",{d:"M4 7h16M9 7V5h6v2M7 7l1 13h8l1-13M10 11v5M14 11v5"})}),ls=t=>e.jsxs(se,{...t,children:[e.jsx("path",{d:"m4 20 4.2-1 10.7-10.7a2.1 2.1 0 0 0-3-3L5.2 16 4 20Z"}),e.jsx("path",{d:"m13.8 7.3 3 3"})]}),ds=t=>e.jsx(se,{...t,children:e.jsx("path",{d:"M7 10v10H4V10h3ZM7 20h9.4a2 2 0 0 0 2-1.6l1.1-5A2 2 0 0 0 17.6 11H14l.5-3.2A2.5 2.5 0 0 0 12 5l-5 5v10Z"})}),us=t=>e.jsx(se,{...t,children:e.jsx("path",{d:"M7 4v10H4V4h3ZM7 4h9.4a2 2 0 0 1 2 1.6l1.1 5a2 2 0 0 1-1.9 2.4H14l.5 3.2A2.5 2.5 0 0 1 12 19l-5-5V4Z"})}),ms=t=>e.jsx(se,{...t,children:e.jsx("path",{d:"M9 4h6l-1 6 3 3v2H7v-2l3-3-1-6ZM12 15v5"})}),hs=t=>e.jsx(se,{...t,children:e.jsx("path",{d:"M20 11a8 8 0 1 0 1.3 4.4M20 5v6h-6"})}),fs=t=>e.jsxs(se,{...t,children:[e.jsx("path",{d:"M12 4 3.5 19h17L12 4Z"}),e.jsx("path",{d:"M12 9v4M12 16h.01"})]}),ps=t=>e.jsx(se,{...t,children:e.jsx("path",{d:"M9 4H4v5M4 4l6 6M15 4h5v5M20 4l-6 6M9 20H4v-5M4 20l6-6M15 20h5v-5M20 20l-6-6"})}),vs=t=>e.jsxs(se,{...t,children:[e.jsx("rect",{height:"12",rx:"2",width:"12",x:"8",y:"8"}),e.jsx("path",{d:"M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"})]}),gs=t=>e.jsx(se,{...t,children:e.jsx("path",{d:"m6 9 6 6 6-6"})}),_s=t=>e.jsx(se,{...t,children:e.jsx("path",{d:"M9 4H4v5M15 4h5v5M9 20H4v-5M15 20h5v-5"})}),bs=t=>e.jsx(se,{...t,children:e.jsx("path",{d:"M9 6h11M9 12h11M9 18h11M4 6h.01M4 12h.01M4 18h.01"})}),ys=t=>e.jsx(se,{...t,children:e.jsx("path",{d:"m6 15 6-6 6 6"})}),$e=()=>globalThis.crypto.randomUUID(),Ct=1e3,mt=(t,s)=>t?.chatId===s.chatId&&t.revision>s.revision?t:s,gt=t=>{const s=t,a=s?.status??s?.response?.status;return a===410||s?.code==="AI_UPLOAD_EXPIRED"?"上传已过期,请移除后重新选择文件":a===409?"数据已变化或对话仍在运行,请刷新后重试":a===401||s?.code==="AI_AUTH_REQUIRED"||s?.code==="AI_AUTH_EXPIRED"?"登录已失效,请重新登录":a===403?"当前账号无权访问该对话":a===404?"对话或回答已不可见,请刷新列表":s?.message?.startsWith("输入内容过长")?s.message:"操作未完成,请重试或刷新对话"};function xs(t,s){const a=s.features?.conversationManagement===!0,o=a?s.scopeKey?.(t)??t.app.id:"",i=c.useRef(o);i.current=o;const l=c.useRef(o),[u,p]=c.useState(j.createAssistantConversationState),d=c.useRef(u),v=r=>{const m=typeof r=="function"?r(d.current):r;d.current=m,p(m)},[S,R]=c.useState([]),[O,F]=c.useState(),b=c.useRef(void 0),[B,L]=c.useState(""),[D,k]=c.useState(void 0),[f,n]=c.useState(!1),[_,A]=c.useState(!1),[G,I]=c.useState(a),[z,J]=c.useState(!1),[ae,Z]=c.useState(),[ce,me]=c.useState([]),[je,Pe]=c.useState([]),P=c.useRef(new Set),H=c.useRef(new Map),$=c.useRef(0),X=c.useRef(0),re=c.useRef(0),pe=c.useRef(void 0),le=c.useRef(void 0),Ie=c.useRef(new Map),T=(r,m=o)=>X.current===r&&i.current===m,ee=()=>{const r=new AbortController;return P.current.add(r),r},Y=r=>P.current.delete(r),Q=r=>{const m=r?mt(b.current,r):void 0;b.current=m,F(m)},Ue=r=>{R(m=>m.map(g=>g.chatId===r.chatId?mt(g,r):g))},De=r=>{R(m=>m.filter(g=>g.chatId!==r))},Ge=()=>{re.current+=1},ie=()=>{for(const r of H.current.values())r.abort();H.current.clear()},q=r=>{r instanceof Error&&r.name==="AbortError"||(console.warn("[make-ai-assistant] conversation operation failed",{errorType:r instanceof Error?r.name:typeof r}),Z(gt(r)))},oe=async r=>{if(!a||!s.listConversations)return;const m=X.current,g=++re.current,y=ee();try{const w=await s.listConversations(t,{cursor:r},{signal:y.signal});if(!T(m)||y.signal.aborted||g!==re.current)return;R(C=>{const x=new Map(C.map(N=>[N.chatId,N])),M=w.chats.map(N=>mt(x.get(N.chatId),N));return[...new Map([...r?C:[],...M].map(N=>[N.chatId,N])).values()]}),L(w.nextCursor)}catch(w){T(m)&&!y.signal.aborted&&g===re.current&&q(w)}finally{Y(y),T(m)&&g===re.current&&I(!1)}},_e=async r=>{if(!s.getConversation)return;const m=X.current,g=ee();try{const y=await s.getConversation(t,{chatId:r},{signal:g.signal});if(!T(m)||g.signal.aborted||y.chatId!==r)return;Ue(y),b.current?.chatId===r&&Q(y)}catch(y){T(m)&&!g.signal.aborted&&q(y)}finally{Y(g)}},we=async(r,m,g)=>{const y=X.current,w=$.current;let C;try{for await(const x of r){if(!T(y)||m.signal.aborted||w!==$.current||b.current?.chatId!==g)return;const M=j.parseAssistantEvent(x);if(M.type==="response.accepted"||M.type==="response.state"){C=M.responseId;const N=H.current.get(C);if(N&&N!==m){M.type==="response.accepted"&&v(U=>j.reduceAssistantEvent(U,M)),m.abort();return}H.current.set(C,m)}v(N=>j.reduceAssistantEvent(N,M)),M.type==="response.accepted"&&_e(g),M.type==="response.terminal"&&(me(N=>N.filter(U=>U!==M.responseId)),oe())}}catch(x){T(y)&&!m.signal.aborted&&w===$.current&&(q(x),C||v(M=>({...M,status:Object.values(M.responses??{}).some(N=>!ut.isResponseTerminal(N))?"streaming":"error"})))}finally{C&&H.current.get(C)===m&&H.current.delete(C),Y(m)}},be=async(r,m,g,y)=>{if(!s.getResponse||!s.watchResponse)return;const w=new Set(r.filter(x=>x.role==="assistant"&&x.persistent).map(x=>x.responseId)),C=[...new Map(r.filter(x=>x.role==="user"&&x.responseId&&!w.has(x.responseId)).map(x=>[x.responseId,x.cursor])).entries()].slice(-20);for(const[x,M]of C){if(!T(y)||g!==$.current)return;if(H.current.has(x))continue;const N=ee();try{const U=await s.getResponse(t,{chatId:m,responseId:x},{signal:N.signal});if(!T(y)||N.signal.aborted||g!==$.current||H.current.has(x))continue;v(ve=>j.reduceAssistantEvent(ve,ut.isResponseTerminal(U)?{type:"response.snapshot",snapshot:U}:{type:"response.state",chatId:m,responseId:x,status:U.status})),U.status==="failed"||U.status==="cancelled"?v(ve=>j.reduceAssistantEvent(ve,{type:"response.terminal",chatId:m,responseId:x,status:U.status})):(H.current.set(x,N),we(s.watchResponse(t,{chatId:m,responseId:x,historyCursor:M},{signal:N.signal}),N,m))}catch(U){T(y)&&!N.signal.aborted&&q(U)}finally{H.current.get(x)!==N&&Y(N)}}},Me=async r=>{const m=++$.current,g=X.current,y=ee();ie(),Z(void 0),I(!0),me([]),le.current=void 0,Q(r),v({messages:[],status:"idle",threadId:r.chatId}),k(void 0),n(!1),A(!1);try{const[w,C]=await Promise.all([s.getConversation(t,{chatId:r.chatId},{signal:y.signal}),s.loadConversation(t,{threadId:r.chatId,cursor:void 0,signal:y.signal})]);if(!T(g)||y.signal.aborted||m!==$.current)return;if(w.chatId!==r.chatId||C.threadId!==r.chatId)throw new Error("Conversation mismatch");Q(w),v(j.createAssistantConversationState(C)),k(C.nextCursor??-1),n(C.hasMore??!1),be(C.messages,r.chatId,m,g)}catch(w){T(g)&&!y.signal.aborted&&m===$.current&&q(w)}finally{Y(y),T(g)&&m===$.current&&I(!1)}},Ce=async()=>{if(b.current)return b.current;if(pe.current??={requestId:$e()},pe.current.promise)return pe.current.promise;const r=X.current,m=$.current,g=ee(),y=pe.current;return J(!0),y.promise=s.createConversation(t,{requestId:y.requestId},{signal:g.signal}).then(w=>{if(!T(r)||g.signal.aborted||m!==$.current)throw Object.assign(new Error("Stale create"),{name:"AbortError"});return pe.current=void 0,Q(w),v({messages:[],status:"idle",threadId:w.chatId}),oe(),w}).finally(()=>{Y(g),y.promise=void 0,T(r)&&J(!1)}),y.promise},Ke=async()=>{if(!(z||pe.current?.promise)){$.current+=1,ie(),Q(void 0),Z(void 0),le.current=void 0,v(j.createAssistantConversationState()),n(!1),k(void 0);try{await Ce()}catch(r){q(r)}}},He=async r=>{const m=ee();le.current=r,Z(void 0),d.current.messages.some(g=>g.id===r.message.id)||v(g=>j.appendUserMessage(g,r.message)),await we(s.run(r,{signal:m.signal}),m,r.threadId)},he=async(r,m)=>{if(!(!r.trim()&&!m?.length))try{const g=await Ce(),y={id:$e(),content:r,...m?{parts:m}:{}};await He({threadId:g.chatId,message:y,context:t,capabilities:{artifactSchemaVersions:[],artifactKinds:[],templates:[]}})}catch(g){q(g)}},Xe=async()=>{const r=le.current;if(!r||r.threadId!==b.current?.chatId){b.current&&await Me(b.current);return}const m=d.current.messages.find(g=>g.id===r.message.id);if(m?.responseId&&s.watchResponse){const g=m.responseId;if(H.current.has(g))return;const y=ee();H.current.set(g,y),Z(void 0),await we(s.watchResponse(t,{chatId:r.threadId,responseId:g,historyCursor:m.cursor},{signal:y.signal}),y,r.threadId)}else await He(r)},Je=async(r=d.current.activeRunId)=>{const m=b.current;if(!m||!r||!s.cancelResponse||ce.includes(r))return;const g=X.current,y=$.current,w=ee();me(C=>[...C,r]),Z(void 0);try{const C=await s.cancelResponse(t,{chatId:m.chatId,responseId:r},{signal:w.signal});if(!T(g)||y!==$.current)return;if(ut.isResponseTerminal(C))v(x=>j.reduceAssistantEvent(x,{type:"response.snapshot",snapshot:C})),me(x=>x.filter(M=>M!==r));else if(!H.current.has(r)&&s.watchResponse){const x=ee();H.current.set(r,x),we(s.watchResponse(t,{chatId:m.chatId,responseId:r},{signal:x.signal}),x,m.chatId)}}catch(C){T(g)&&y===$.current&&(q(C),me(x=>x.filter(M=>M!==r)))}finally{Y(w)}},Ye=async(r,m=b.current)=>{if(!m||z)return!1;const g=X.current,y=ee();J(!0),Z(void 0);try{const w=await s.updateConversation(t,{chatId:m.chatId,expectedRevision:m.revision,...r},{signal:y.signal});return T(g)?(Ge(),Ue(w),b.current?.chatId===w.chatId&&Q(w),!0):!1}catch(w){if(T(g)){q(w);try{const C=await s.getConversation(t,{chatId:m.chatId},{signal:y.signal});T(g)&&b.current?.chatId===m.chatId&&Q(C)}catch{}oe()}return!1}finally{Y(y),T(g)&&J(!1)}},Qe=async(r=b.current)=>{if(!r||z)return!1;const m=X.current,g=ee();J(!0),Z(void 0);try{return await s.deleteConversation(t,{chatId:r.chatId,expectedRevision:r.revision},{signal:g.signal}),T(m)?(Ge(),De(r.chatId),b.current?.chatId===r.chatId&&($.current+=1,ie(),Q(void 0),v(j.createAssistantConversationState())),!0):!1}catch(y){return T(m)&&q(y),!1}finally{Y(g),T(m)&&J(!1)}},et=async(r,m,g="",y="")=>{const w=b.current;if(!w||!r.persistent||!s.setFeedback||je.includes(r.id))return;const C={chatId:w.chatId,messageId:r.id,rating:m,...g?{reason:g}:{},...y?{comment:y}:{}},x=Ie.current.get(r.id),{requestId:M,...N}=x??{requestId:""},U=x&&JSON.stringify(N)===JSON.stringify(C)?x:{...C,requestId:$e()};Ie.current.set(r.id,U);const ve=X.current,Ne=$.current,tt=ee();Pe(de=>[...de,r.id]),Z(void 0);try{const de=await s.setFeedback(t,U,{signal:tt.signal});return!T(ve)||Ne!==$.current||Ie.current.get(r.id)!==U?void 0:(v(Se=>({...Se,messages:Se.messages.map(h=>h.id===r.id&&de.revision>=(h.feedback?.revision??0)?{...h,feedback:de}:h)})),Ie.current.delete(r.id),!0)}catch(de){return T(ve)&&Ne===$.current&&q(de),!1}finally{Y(tt),T(ve)&&Pe(de=>de.filter(Se=>Se!==r.id))}},Ee=async()=>{if(!b.current||!f||G)return;const r=X.current,m=$.current,g=b.current,y=ee();I(!0);try{const w=await s.loadConversation(t,{threadId:g.chatId,cursor:D,signal:y.signal});if(!T(r)||m!==$.current)return;const C=j.createAssistantConversationState(w),x=[...new Map([...d.current.messages,...C.messages].map(U=>[U.id,U])).values()];let M=0;const N=[];for(const U of x.slice(-200).reverse()){if(M+=[...U.content].length,M>1e6)break;N.unshift(U)}N.length<x.length&&A(!0),v(U=>({...U,messages:N})),k(w.nextCursor??D),n(w.hasMore??!1),be(w.messages,g.chatId,m,r)}catch(w){T(r)&&q(w)}finally{Y(y),T(r)&&I(!1)}},Be=[...new Set([...S.filter(r=>r.titlePending).map(r=>r.chatId),...O?.titlePending?[O.chatId]:[]])].sort().join("\0");c.useEffect(()=>{if(!a||!s.getConversation||!Be)return;const r=X.current,m=ee(),g=Be.split("\0"),y=new Set;let w;console.debug("[make-ai-assistant] watching pending conversation titles",{count:g.length});const C=async()=>{await Promise.all(g.map(async x=>{if(!y.has(x))try{const M=await s.getConversation(t,{chatId:x},{signal:m.signal});if(!T(r)||m.signal.aborted||M.chatId!==x)return;Ue(M),b.current?.chatId===x&&Q(M)}catch(M){if(!T(r)||m.signal.aborted)return;console.warn("[make-ai-assistant] title metadata refresh failed",{errorType:M instanceof Error?M.name:typeof M});const N=M?.status;N===401?(m.abort(),q(M)):(N===403||N===404)&&(y.add(x),b.current?.chatId===x&&q(M))}})),T(r)&&!m.signal.aborted&&g.some(x=>!y.has(x))&&(w=setTimeout(()=>{C()},Ct))};return w=setTimeout(()=>{C()},Ct),()=>{clearTimeout(w),m.abort(),Y(m)}},[a,o,s,Be]),c.useEffect(()=>(X.current+=1,l.current=o,pe.current=void 0,le.current=void 0,Ie.current.clear(),Q(void 0),R([]),L(""),v(j.createAssistantConversationState()),Z(void 0),I(a),J(!1),me([]),Pe([]),a&&oe(),()=>{X.current+=1,$.current+=1;for(const r of P.current)r.abort();P.current.clear(),H.current.clear()}),[a,o,s]);const Ae=l.current===o;return{enabled:a,canEdit:s.features?.conversationEditing!==!1,state:Ae?u:j.createAssistantConversationState(),setState:v,chats:Ae?S:[],chat:Ae?O:void 0,listCursor:B,historyMore:f,historyTruncated:_,loading:!Ae||G,busy:z,error:Ae?ae:void 0,cancelling:ce,feedbackBusy:je,refresh:oe,select:Me,create:Ke,ensureChat:Ce,send:he,retry:Xe,stop:Je,update:Ye,remove:Qe,feedback:et,moreHistory:Ee,setError:Z}}const ks=()=>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"})]}),js=({anchor:t,label:s,onDismiss:a})=>{const[o,i]=c.useState();if(c.useLayoutEffect(()=>{const u=()=>{if(!t.isConnected){a();return}const p=t.getBoundingClientRect(),d=p.top>=48?"above":"below";i({left:p.left+p.width/2,placement:d,top:d==="above"?p.top-8:p.bottom+8})};return u(),window.addEventListener("resize",u),document.addEventListener("scroll",u,!0),()=>{window.removeEventListener("resize",u),document.removeEventListener("scroll",u,!0)}},[t,a]),!o||typeof document>"u")return null;const l=t.closest(".make-ai-assistant")??document.body;return Ft.createPortal(e.jsx("span",{className:"make-ai-assistant__conversation-tooltip","data-placement":o.placement,role:"tooltip",style:{left:o.left,top:o.top},children:s}),l)};function Is({id:t,manager:s,onDismiss:a,onNewConversation:o,triggerRef:i}){const[l,u]=c.useState(),[p,d]=c.useState(""),[v,S]=c.useState(),[R,O]=c.useState(),F=c.useRef(null),b=(n,_)=>{O(A=>A?.anchor===_&&A.label===n?A:{anchor:_,label:n})},B=n=>{O(_=>_?.anchor===n?void 0:_)},L=n=>({"data-tooltip":n,onBlur:_=>B(_.currentTarget),onFocus:_=>b(n,_.currentTarget),onPointerEnter:_=>b(n,_.currentTarget),onPointerLeave:_=>B(_.currentTarget)}),D=()=>{u(void 0),d("")},k=async n=>{const _=p.trim();_&&await s.update({title:_},n)&&D()},f=async n=>{await s.remove(n)&&S(void 0)};return c.useEffect(()=>{const n=_=>{const A=_.target;A instanceof Node&&(F.current?.contains(A)||i.current?.contains(A)||a())};return document.addEventListener("pointerdown",n),()=>{document.removeEventListener("pointerdown",n)}},[a,i]),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",...L("刷新"),onClick:()=>{s.refresh()},children:e.jsx(hs,{"aria-hidden":"true",className:"make-ai-assistant__conversation-refresh-icon"})})]}),e.jsxs("nav",{"aria-label":"对话列表",className:"make-ai-assistant__conversation-list",children:[s.chats.map(n=>{const _=l===n.chatId,A=v===n.chatId,G=n.title||"未命名对话";return e.jsxs("div",{className:"make-ai-assistant__conversation-row","data-active":s.chat?.chatId===n.chatId||void 0,"data-editing":_||A||void 0,children:[A?e.jsxs("div",{"aria-label":"确认删除对话",className:"make-ai-assistant__conversation-delete-confirmation",role:"group",children:[e.jsx(fs,{"aria-hidden":"true",className:"make-ai-assistant__conversation-delete-confirmation-icon"}),e.jsxs("span",{className:"make-ai-assistant__conversation-delete-confirmation-message",children:["确认删除“",G,"”?"]}),e.jsx("button",{"aria-label":`确认删除:${G}`,className:"make-ai-assistant__conversation-row-action make-ai-assistant__conversation-row-action--danger make-ai-assistant__conversation-delete-confirmation-confirm",disabled:s.busy||!s.canEdit,type:"button",...L("确认删除"),onClick:()=>{f(n)},children:e.jsx(Mt,{"aria-hidden":"true",className:"make-ai-assistant__conversation-row-action-icon"})}),e.jsx("button",{"aria-label":`取消删除:${G}`,className:"make-ai-assistant__conversation-row-action make-ai-assistant__conversation-delete-confirmation-cancel",disabled:s.busy,type:"button",...L("取消"),onClick:()=>S(void 0),children:e.jsx(ct,{"aria-hidden":"true",className:"make-ai-assistant__conversation-row-action-icon"})})]}):_?e.jsx("input",{"aria-label":"对话标题",autoFocus:!0,className:"make-ai-assistant__conversation-row-title-input",disabled:s.busy,maxLength:255,value:p,onChange:I=>d(I.currentTarget.value),onKeyDown:I=>{I.nativeEvent.isComposing||(I.key==="Escape"&&(I.preventDefault(),D()),I.key==="Enter"&&(I.preventDefault(),k(n)))}}):e.jsxs("button",{"aria-pressed":s.chat?.chatId===n.chatId,className:"make-ai-assistant__conversation-row-select",type:"button",onClick:()=>{a(),s.select(n)},children:[e.jsx(ks,{}),e.jsx("span",{children:G})]}),_?e.jsxs("div",{"aria-label":"修改标题操作",className:"make-ai-assistant__conversation-row-actions",role:"group",children:[e.jsx("button",{"aria-label":"确认修改标题",className:"make-ai-assistant__conversation-row-action",disabled:s.busy||!p.trim(),type:"button",...L("保存标题"),onClick:()=>{k(n)},children:e.jsx(cs,{"aria-hidden":"true",className:"make-ai-assistant__conversation-row-action-icon"})}),e.jsx("button",{"aria-label":"取消修改标题",className:"make-ai-assistant__conversation-row-action",disabled:s.busy,type:"button",...L("取消"),onClick:D,children:e.jsx(ct,{"aria-hidden":"true",className:"make-ai-assistant__conversation-row-action-icon"})})]}):A?null:e.jsxs("div",{className:"make-ai-assistant__conversation-row-actions",children:[e.jsx("button",{"aria-label":`${n.pinned?"取消置顶":"置顶"} ${G}`,"aria-pressed":n.pinned,className:"make-ai-assistant__conversation-row-action make-ai-assistant__conversation-row-pin",disabled:s.busy||!s.canEdit,type:"button",...L(n.pinned?"取消置顶":"置顶"),onClick:()=>{s.update({pinned:!n.pinned},n)},children:e.jsx(ms,{"aria-hidden":"true",className:"make-ai-assistant__conversation-row-action-icon"})}),e.jsx("button",{"aria-label":`修改标题:${G}`,className:"make-ai-assistant__conversation-row-action",disabled:s.busy||!s.canEdit,type:"button",...L("修改标题"),onClick:()=>{S(void 0),u(n.chatId),d(n.title)},children:e.jsx(ls,{"aria-hidden":"true",className:"make-ai-assistant__conversation-row-action-icon"})}),e.jsx("button",{"aria-label":`删除:${G}`,className:"make-ai-assistant__conversation-row-action make-ai-assistant__conversation-row-action--danger",disabled:s.busy,type:"button",...L("删除"),onClick:()=>{D(),S(n.chatId)},children:e.jsx(Mt,{"aria-hidden":"true",className:"make-ai-assistant__conversation-row-action-icon"})})]})]},n.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&&(s.historyMore||s.historyTruncated||s.state.historyTruncated)?e.jsxs("div",{className:"make-ai-assistant__conversation-history-actions",children:[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(vt,{"aria-hidden":"true",className:"make-ai-assistant__conversation-new-icon"}),e.jsx("span",{children:"新建对话"})]}):null,R?e.jsx(js,{anchor:R.anchor,label:R.label,onDismiss:()=>O(void 0)}):null]})}function ws({message:t,manager:s}){const[a,o]=c.useState(!1),[i,l]=c.useState(""),[u,p]=c.useState(""),d=s.feedbackBusy.includes(t.id);if(!t.persistent||t.role!=="assistant"||t.intermediate)return null;const v=t.feedback?.rating??"none";return e.jsxs("div",{"aria-label":"回答反馈",className:"make-ai-assistant__feedback",role:"group",children:[e.jsx("button",{type:"button","aria-label":"喜欢","aria-pressed":v==="like",className:"make-ai-assistant__reply-action make-ai-assistant__reply-feedback-action","data-tooltip":"喜欢",disabled:d,onClick:()=>{s.feedback(t,v==="like"?"none":"like")},children:e.jsx(ds,{"aria-hidden":"true",className:"make-ai-assistant__reply-feedback-icon"})}),e.jsx("button",{type:"button","aria-label":"不喜欢","aria-pressed":v==="dislike",className:"make-ai-assistant__reply-action make-ai-assistant__reply-feedback-action","data-tooltip":"不喜欢",disabled:d,onClick:()=>{if(v==="dislike"){s.feedback(t,"none");return}l(t.feedback?.reason??""),p(t.feedback?.comment??""),o(!0)},children:e.jsx(us,{"aria-hidden":"true",className:"make-ai-assistant__reply-feedback-icon"})}),v==="dislike"?e.jsx("button",{className:"make-ai-assistant__feedback-text-action",type:"button",disabled:d,onClick:()=>{l(t.feedback?.reason??""),p(t.feedback?.comment??""),o(!0)},children:"修改反馈"}):null,a?e.jsxs("form",{onSubmit:S=>{S.preventDefault(),s.feedback(t,"dislike",i,u).then(R=>{R&&o(!1)})},children:[e.jsx("input",{"aria-label":"反馈原因",maxLength:128,value:i,onChange:S=>l(S.currentTarget.value),placeholder:"原因(可选)"}),e.jsx("textarea",{"aria-label":"反馈说明",maxLength:4e3,value:u,onChange:S=>p(S.currentTarget.value),placeholder:"补充说明(可选)"}),e.jsx("button",{className:"make-ai-assistant__feedback-text-action",type:"submit",disabled:d,children:"提交反馈"}),e.jsx("button",{className:"make-ai-assistant__feedback-text-action",type:"button",onClick:()=>o(!1),children:"取消"})]}):null]})}const Et=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 As({part:t,context:s,transport:a,chatId:o}){const[i,l]=c.useState(),[u,p]=c.useState(),[d,v]=c.useState(!1),S=c.useRef([]),R=c.useRef(void 0);c.useEffect(()=>()=>{R.current?.abort(),S.current.forEach(F=>URL.revokeObjectURL(F))},[]);const O=async F=>{if(!a.readContent||d)return;const b=new AbortController;R.current=b,v(!0),p(void 0);try{const B=await a.readContent(s,{chatId:o,contentRef:t.media.contentRef},{signal:b.signal});if(b.signal.aborted)return;const L=new Blob([new Uint8Array(B).buffer],{type:F&&Et.has(t.media.contentType)?t.media.contentType:"application/octet-stream"}),D=URL.createObjectURL(L);if(S.current.push(D),F)l(D);else{const k=document.createElement("a");k.href=D,k.download=t.name??"attachment",k.click()}}catch(B){b.signal.aborted||p(gt(B))}finally{b.signal.aborted||v(!1)}};return e.jsxs("div",{className:"make-ai-assistant__attachment",children:[e.jsxs("span",{children:[t.name??"附件"," · ",t.media.sizeBytes," 字节"]}),a.readContent?e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",disabled:d,onClick:()=>{O(!1)},children:"下载附件"}),Et.has(t.media.contentType)?e.jsx("button",{type:"button",disabled:d,onClick:()=>{O(!0)},children:"预览附件"}):null]}):null,u?e.jsx("span",{role:"alert",children:u}):null,i&&t.kind==="image"?e.jsx("img",{src:i,alt:t.name??"附件图片"}):null,i&&t.kind==="audio"?e.jsx("audio",{src:i,controls:!0}):null,i&&t.kind==="video"?e.jsx("video",{src:i,controls:!0}):null]})}function Ns({message:t,context:s,transport:a,chatId:o}){return e.jsx(e.Fragment,{children:t.parts?.map((i,l)=>i.kind==="text"?null:i.kind==="unknown"?e.jsx("span",{className:"make-ai-assistant__attachment",children:i.textFallback??"此内容类型暂不支持展示"},i.id??`${t.id}:${l}`):e.jsx(As,{part:i,context:s,transport:a,chatId:o},i.id??`${t.id}:${l}`))})}const Vt=t=>t.type.split(";")[0].trim().toLowerCase()||"application/octet-stream",Ms=t=>t.startsWith("image/")&&t!=="image/svg+xml"?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"file",Cs=t=>{const s=Vt(t);if(!(!s.startsWith("image/")||s==="image/svg+xml"||typeof URL>"u"||typeof URL.createObjectURL!="function"))return URL.createObjectURL(t)},St=t=>{t&&typeof URL<"u"&&typeof URL.revokeObjectURL=="function"&&URL.revokeObjectURL(t)},Es=(t,s)=>new Promise((a,o)=>{const i=new FileReader,l=()=>s.removeEventListener("abort",u),u=()=>{i.abort(),l(),o(Object.assign(new Error("Read aborted"),{name:"AbortError"}))};if(s.aborted){u();return}s.addEventListener("abort",u,{once:!0}),i.onload=()=>{l(),a(new Uint8Array(i.result))},i.onerror=()=>{l(),o(new Error("无法读取文件"))},i.readAsArrayBuffer(t)});function Ss(t,s,a){const[o,i]=c.useState([]),l=c.useRef(new Map),u=c.useRef(Promise.resolve()),p=s.scopeKey?.(t)??t.app.id,d=c.useRef(p);d.current=p;const v=c.useRef(void 0),S=a.enabled&&s.features?.attachments===!0,R=(f,n)=>{!l.current.has(f.draft.id)||f.scope!==d.current||(f.draft={...f.draft,...n},i([...l.current.values()].map(_=>_.draft)))},O=()=>{for(const f of l.current.values())f.controller.abort(),St(f.draft.previewUrl);l.current.clear(),i([]),v.current=void 0,u.current=Promise.resolve()};c.useEffect(()=>(O(),O),[p,s]),c.useEffect(()=>{v.current&&a.chat?.chatId!==v.current&&O()},[a.chat?.chatId]);const F=async f=>{const n=f.controller.signal,_=()=>{if(n.aborted||f.scope!==d.current||!l.current.has(f.draft.id))throw Object.assign(new Error("Upload aborted"),{name:"AbortError"})};try{if(_(),f.file.size>64<<20)throw new Error("文件不能超过 64 MiB");const A=await a.ensureChat();_(),v.current=A.chatId;const G=Vt(f.file);R(f,{status:"uploading",error:void 0});let I=f.draft.upload?await s.getUpload(t,{chatId:A.chatId,uploadId:f.draft.upload.id},{signal:n}):await s.startUpload(t,{chatId:A.chatId,fileId:f.draft.fileId,name:f.file.name,contentType:G,sizeBytes:f.file.size},{signal:n});if(_(),R(f,{upload:I}),I.name!==f.file.name||I.contentType!==G||I.sizeBytes!==f.file.size)throw new Error("上传文件身份不一致");if(I.status!=="ready"){if(I=await s.getUpload(t,{chatId:A.chatId,uploadId:I.id},{signal:n}),_(),I.status!=="uploading"||!Number.isSafeInteger(I.partSize)||I.partSize<=0||I.partSize>1<<20)throw new Error("当前上传状态无法继续,请重新选择文件");const z=new Set(I.completedParts),J=Math.ceil(f.file.size/I.partSize);for(let ae=0;ae<J;ae+=1){if(_(),!z.has(ae)){const Z=await Es(f.file.slice(ae*I.partSize,Math.min(f.file.size,(ae+1)*I.partSize)),n);_(),await s.uploadPart(t,{chatId:A.chatId,uploadId:I.id,part:ae,bytes:Z},{signal:n}),_(),z.add(ae)}R(f,{progress:z.size/Math.max(J,1)})}R(f,{status:"completing"}),I=await s.completeUpload(t,{chatId:A.chatId,uploadId:I.id},{signal:n}),_()}if(I.status!=="ready"||!I.content)throw new Error("上传尚未完成");R(f,{status:"ready",progress:1,upload:I})}catch(A){R(f,{status:n.aborted?"paused":"failed",error:n.aborted?void 0:gt(A)})}},b=f=>{if(S){if(f.length+l.current.size>32){a.setError("每条消息最多包含 32 个附件或文本片段");return}for(const n of f){const _={id:$e(),fileId:$e(),name:n.name,size:n.size,status:"queued",progress:0,previewUrl:Cs(n)},A={draft:_,file:n,controller:new AbortController,scope:p};l.current.set(_.id,A),u.current=u.current.then(()=>F(A))}i([...l.current.values()].map(n=>n.draft))}},B=f=>{const n=l.current.get(f);!n||!["paused","failed"].includes(n.draft.status)||(n.controller=new AbortController,R(n,{status:"queued"}),u.current=u.current.then(()=>F(n)))},L=f=>{const n=l.current.get(f);n?.controller.abort(),St(n?.draft.previewUrl),l.current.delete(f),i([...l.current.values()].map(_=>_.draft))},D=f=>l.current.get(f)?.controller.abort(),k=o.flatMap(f=>{const n=f.upload;if(f.status!=="ready"||!n?.content)return[];const _=Ms(n.contentType);return[{id:f.id,kind:_,name:n.name,media:{contentRef:n.content.contentRef,contentType:n.contentType,sizeBytes:n.content.sizeBytes,digestSha256:n.content.digestSha256}}]});return{enabled:S,drafts:o,parts:k,pending:o.some(f=>f.status!=="ready"),add:b,retry:B,remove:L,pause:D,clear:O}}function Ts({attachments:t,onOpenChange:s,open:a,triggerRef:o}){const i=c.useRef(null),l=c.useRef(null);c.useEffect(()=>{if(!a)return;const p=d=>{const v=d.target;v instanceof Node&&!i.current?.contains(v)&&s(!1)};return document.addEventListener("pointerdown",p),()=>{document.removeEventListener("pointerdown",p)}},[s,a]);const u=p=>{t.add(Array.from(p.files??[])),p.value="",s(!1)};return e.jsxs("div",{className:"make-ai-assistant__attachment-composer",ref:i,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(vt,{"aria-hidden":"true",className:"make-ai-assistant__attachment-trigger-icon"})}),a?e.jsx("div",{"aria-label":"附件选项",className:"make-ai-assistant__attachment-menu",role:"menu",children:e.jsxs("button",{role:"menuitem",type:"button",onClick:()=>l.current?.click(),children:[e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M12 15V4M7.5 8.5 12 4l4.5 4.5"}),e.jsx("path",{d:"M5 14v5h14v-5"})]}),e.jsx("span",{children:"上传文件或图片"})]})}):null,e.jsx("input",{"aria-label":"上传文件或图片",hidden:!0,multiple:!0,ref:l,type:"file",onChange:p=>u(p.currentTarget)})]})}function Rs({attachments:t,visible:s}){const[a,o]=c.useState(),i=c.useRef(null),l=c.useRef(null),u=c.useCallback(()=>{o(void 0),l.current?.focus()},[]);if(c.useEffect(()=>{if(!a)return;const d=v=>{v.key==="Escape"&&(v.preventDefault(),v.stopImmediatePropagation(),u())};return document.addEventListener("keydown",d,!0),()=>document.removeEventListener("keydown",d,!0)},[u,a]),c.useEffect(()=>{s||o(void 0)},[s]),!t.drafts.length)return null;const p=typeof document>"u"?void 0:i.current?.closest(".make-ai-assistant")??document.body;return e.jsxs("div",{"aria-label":"待发送附件",className:"make-ai-assistant__attachment-drafts",ref:i,children:[e.jsx("ul",{children:t.drafts.map(d=>e.jsxs("li",{"data-status":d.status,children:[d.previewUrl?e.jsx("button",{"aria-label":`预览附件 ${d.name}`,className:"make-ai-assistant__attachment-draft-preview-button",type:"button",onClick:v=>{l.current=v.currentTarget,o(d)},children:e.jsx("img",{alt:"",className:"make-ai-assistant__attachment-draft-preview",src:d.previewUrl})}):e.jsx("span",{"aria-hidden":"true",className:"make-ai-assistant__attachment-draft-file",children:e.jsxs("svg",{viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M6 3h8l4 4v14H6z"}),e.jsx("path",{d:"M14 3v5h5M9 13h6M9 16h6"})]})}),e.jsxs("span",{className:"make-ai-assistant__attachment-draft-details",children:[e.jsx("span",{className:"make-ai-assistant__attachment-draft-name",title:d.name,children:d.name}),e.jsx("span",{className:"make-ai-assistant__attachment-draft-status",children:d.status==="ready"?"已上传":d.status==="completing"?"校验中":d.status==="paused"?"已暂停":d.status==="failed"?"上传失败":`${Math.round(d.progress*100)}%`})]}),d.error?e.jsx("span",{role:"alert",children:d.error}):null,d.status==="failed"||d.status==="paused"?e.jsx("button",{type:"button",onClick:()=>t.retry(d.id),children:"重试上传"}):null,d.status==="uploading"?e.jsx("button",{type:"button",onClick:()=>t.pause(d.id),children:"暂停上传"}):null,e.jsx("button",{"aria-label":`移除附件 ${d.name}`,className:"make-ai-assistant__attachment-draft-remove",type:"button",onClick:()=>{a?.id===d.id&&u(),t.remove(d.id)},children:e.jsx(ct,{"aria-hidden":"true",className:"make-ai-assistant__attachment-draft-remove-icon"})})]},d.id))}),a?.previewUrl&&p?Ft.createPortal(e.jsx("div",{className:"make-ai-assistant__attachment-preview-backdrop",onPointerDown:d=>{d.target===d.currentTarget&&u()},children:e.jsxs("div",{"aria-label":`预览附件 ${a.name}`,"aria-modal":"true",className:"make-ai-assistant__attachment-preview-dialog",role:"dialog",onKeyDown:d=>{d.key==="Tab"&&d.preventDefault()},children:[e.jsx("button",{"aria-label":`关闭图片预览 ${a.name}`,autoFocus:!0,className:"make-ai-assistant__attachment-preview-close",type:"button",onClick:u,children:e.jsx(ct,{"aria-hidden":"true",className:"make-ai-assistant__attachment-preview-close-icon"})}),e.jsx("img",{alt:a.name,src:a.previewUrl})]})}),p):null]})}const Ls=t=>`${t}-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,$s="Make",Os=["总结当前页面数据","找出需要关注的记录","列出我有权限查看的数据对象"],Fs=72,Ps=192,zt=(t,s)=>s??`${t?.trim()||$s} AI 助手`,Us=t=>t??Os,Ds=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0,Ks=t=>typeof t=="number"?Number.isFinite(t)?`${t}px`:void 0:t?.trim()||void 0;class W extends Error{}const it=(t,s)=>{if(!(typeof t!="object"||t===null))return t[s]},Hs=t=>{const s=it(t,"status");return typeof s=="number"?s:it(it(t,"response"),"status")},Bs=t=>{const s=it(t,"code"),a=Hs(t),o=t instanceof Error?t.message:"",i=[s,o].filter(d=>typeof d=="string").join(" ").toLowerCase(),u=globalThis.navigator?.onLine===!1||/network|fetch|timeout|offline|connection|网络|连接|超时/.test(i),p=typeof a=="number"&&a>=500||/server|service|服务器|服务异常/.test(i);return u?{actionLabel:"重新连接",description:"请检查网络后再试。",kind:"network",label:"网络连接",title:"网络连接不可用"}:p?{actionLabel:"重新加载",description:"服务暂时未能响应,请稍后重试。",kind:"service",label:"服务异常",title:"服务暂时不可用"}:{actionLabel:"重新加载",description:"请稍后重试;若问题持续出现,请联系管理员。",kind:"unknown",label:"加载异常",title:"暂时无法加载对话"}},Tt=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})}},Vs=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")},qt=()=>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"})]}),zs=()=>e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"m6 6 12 12M18 6 6 18"})}),qs=()=>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"})]}),Zs=()=>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"})]}),Rt=()=>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"})]}),Zt=()=>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:"M12 8v4.5"}),e.jsx("path",{d:"M12 16h.01"})]}),ot=({className:t=""})=>e.jsx("span",{className:`make-ai-assistant__avatar ${t}`.trim(),"aria-hidden":"true",children:e.jsx(qt,{})}),Gs=({src:t})=>t?e.jsx("span",{className:"make-ai-assistant__user-avatar","aria-hidden":"true",children:e.jsx("img",{alt:"",src:t})}):null,Xs=({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(Gs,{src:t})]})},ht=t=>{const s=t.trim();if(!(!s.startsWith("|")||!s.endsWith("|")))return s.slice(1,-1).split("|").map(a=>a.trim())},Js=t=>t.length>0&&t.every(s=>/^:?-{3,}:?$/.test(s)),Ys=(t,s)=>{const a=ht(t[s]??""),o=ht(t[s+1]??"");if(!a||!o||a.length!==o.length||!Js(o))return;const i=[];let l=s+2;for(;l<t.length;){const u=ht(t[l]??"");if(!u||u.length!==a.length)break;i.push(u),l+=1}return{headers:a,lastIndex:l-1,rows:i}},Qs=t=>{const s=[],a=[],o=[],i=[],l=t.replace(/\r\n?/g,`
2
2
  `).split(`
3
- `),d=()=>{const p=a.join(`
4
- `).trim();a.length=0,p&&s.push({type:"paragraph",text:p})},h=()=>{i.length&&s.push({type:"list",items:i.splice(0)})},y=()=>{const p=o.join(`
5
- `).trim();o.length=0,p&&s.push({type:"pre",text:p})};for(let p=0;p<l.length;p+=1){const C=l[p]??"",S=C.trim();if(!S){d(),h(),y();continue}const R=Vs(l,p);if(R){d(),h(),y(),s.push({headers:R.headers,rows:R.rows,type:"table"}),p=R.lastIndex;continue}const V=/^(#{1,6})\s+(.+)$/.exec(S);if(V){d(),h(),y();const D=(V[2]??"").replace(/\s+#+\s*$/,"").trim();D&&s.push({type:"heading",level:V[1]?.length,text:D});continue}if(/^\s*\|.+\|\s*$/.test(C)){d(),h(),o.push(C.trim());continue}const A=/^\s*[-*]\s+(.+)$/.exec(C);if(A){d(),y(),i.push(A[1]?.trim()??"");continue}h(),y(),a.push(S)}return d(),h(),y(),s},Ke=t=>{const s=[],a=/(\*\*[^*]+\*\*|`[^`]+`)/g;let i=0;for(const o of t.matchAll(a)){const l=o[0],d=o.index??0;d>i&&s.push(t.slice(i,d)),l.startsWith("**")?s.push(e.jsx("strong",{children:l.slice(2,-2)},`${d}-strong`)):s.push(e.jsx("code",{children:l.slice(1,-1)},`${d}-code`)),i=d+l.length}return i<t.length&&s.push(t.slice(i)),s},Nt=({content:t})=>{const s=qs(t);return s.length?e.jsx("div",{className:"make-ai-assistant__bubble make-ai-assistant__assistant-text",children:s.map((a,i)=>{if(a.type==="heading"){const o=a.level<=2?"h3":"h4";return e.jsx(o,{className:`make-ai-assistant__markdown-heading make-ai-assistant__markdown-heading--${a.level}`,children:Ke(a.text)},`${i}-heading`)}return a.type==="paragraph"?e.jsx("p",{children:Ke(a.text)},`${i}-paragraph`):a.type==="pre"?e.jsx("pre",{children:e.jsx("code",{children:a.text})},`${i}-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((o,l)=>e.jsx("th",{scope:"col",children:Ke(o)},`${l}-${o}`))})}),e.jsx("tbody",{children:a.rows.map((o,l)=>e.jsx("tr",{children:o.map((d,h)=>e.jsx("td",{children:Ke(d)},`${h}-${d}`))},`${l}-${o.join("|")}`))})]})},`${i}-table`):e.jsx("ul",{children:a.items.map((o,l)=>e.jsx("li",{children:Ke(o)},`${l}-${o}`))},`${i}-list`)})}):null},Kt=({assistantName:t})=>e.jsxs("div",{className:"make-ai-assistant__message-identity",children:[e.jsx(st,{className:"make-ai-assistant__avatar--message"}),e.jsx("span",{className:"make-ai-assistant__message-sender",children:t})]}),Wt=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}},Hs=t=>{for(let s=t.messages.length-1;s>=0;s-=1)if(t.messages[s].role==="user")return s;return-1},Vt=t=>{const s=Hs(t);if(!(s<0))for(let a=t.messages.length-1;a>s;a-=1){const i=t.messages[a];if(i.role==="assistant")return i.id}},Zs=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}},Xs=t=>{for(let s=t.messages.length-1;s>=0;s-=1){const a=t.messages[s];if(a.role==="user")return a}},Gs=(t,s)=>{const a=t.messages.findIndex(i=>i.id===s&&i.role==="user");return{...t,error:void 0,progress:void 0,status:"streaming",messages:a<0?t.messages:t.messages.slice(0,a+1)}},Ys=t=>t.scrollHeight-t.scrollTop-t.clientHeight<=48,Tt=(t="smooth")=>globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches?"auto":t,lt=(t,s)=>{typeof t.scrollTo=="function"?t.scrollTo({top:t.scrollHeight,behavior:s}):t.scrollTop=t.scrollHeight},qt=({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(Bs,{})}),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(zt,{}),"重新发送"]}):null]}),Js=({error:t,onRetry:s})=>{const a=Cs(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(zt,{}),a.actionLabel]})]})},Ht=({active:t,steps:s})=>{const[a,i]=c.useState(!1);if(!t||!s?.length)return null;const o=s[s.length-1]??"处理中";return e.jsxs("details",{className:"make-ai-assistant__process",open:a,onToggle:l=>i(l.currentTarget.open),children:[e.jsxs("summary",{"aria-label":`查看处理过程,共 ${s.length} 步`,children:[e.jsxs("span",{className:"make-ai-assistant__process-summary",children:[e.jsx("span",{className:"make-ai-assistant__process-indicator","aria-hidden":"true"}),e.jsxs("span",{className:"make-ai-assistant__process-copy",children:[e.jsx("span",{className:"make-ai-assistant__process-title",children:"处理过程"}),e.jsx("span",{className:"make-ai-assistant__progress make-ai-assistant__process-latest",role:"status",children:o})]})]}),e.jsxs("span",{className:"make-ai-assistant__process-count",children:[s.length," 步"]})]}),e.jsx("ol",{children:s.map((l,d)=>e.jsxs("li",{"data-step-active":d===s.length-1?!0:void 0,children:[e.jsx("span",{"aria-hidden":"true"}),e.jsx("span",{children:l})]},`${d}-${l}`))})]})},Qs=({copyFeedback:t,feedback:s,onCopy:a,onRegenerate:i})=>!s&&!a&&!i?null:e.jsxs("div",{className:"make-ai-assistant__reply-actions","aria-label":"回复操作",children:[a?e.jsx("button",{"aria-label":"复制回答",className:"make-ai-assistant__reply-action make-ai-assistant__reply-copy","data-tooltip":"复制",type:"button",onClick:a,children:e.jsx($s,{})}):null,s,i?e.jsx("button",{"aria-label":"重新生成",className:"make-ai-assistant__reply-action make-ai-assistant__reply-regenerate","data-tooltip":"重新生成",type:"button",onClick:i,children:e.jsx(Ds,{})}):null,t?e.jsx("span",{className:"make-ai-assistant__reply-feedback","data-copy-status":t.status,role:"status",children:t.message}):null]}),St=({assistantName:t,error:s,onRetry:a,progress:i})=>{const o=s?"error":"progress";return s?.message??i?.message?e.jsx("article",{"aria-label":`${t}的${o==="error"?"错误消息":"状态消息"}`,className:`make-ai-assistant__message make-ai-assistant__message--assistant make-ai-assistant__message--${o}`,"data-message-role":"assistant","data-message-state":o,children:e.jsxs("div",{className:"make-ai-assistant__message-turn",children:[e.jsx(Kt,{assistantName:t}),e.jsx("div",{className:"make-ai-assistant__message-stack",children:s?e.jsx(qt,{error:s,onRetry:a}):e.jsx(Ht,{active:!0,steps:i?.steps})})]})}):null},ea=(t,s,a,i,o,l,d,h,y,p,C,S,R,V,A,D)=>{const g=Vt(t),N=Wt(t),F=Zs(t);let f;return t.messages.map(n=>{if(n.intermediate)return e.jsxs("details",{className:"make-ai-assistant__process",children:[e.jsx("summary",{children:"处理过程"}),e.jsx(Nt,{content:n.content})]},n.id);const v=n.role==="assistant",_=f;v||(f=n);const K=n.id===N,I=n.id===g?t.error:void 0,X=n.error??I,G=!v&&!!(y?.trim()||p),U=v?d:y?.trim()||"用户",J=v&&n.status==="complete"&&!X&&(n.content.trim()||n.id===F),me=!!(A&&D?.features?.feedback&&v&&n.persistent),re=J||me;return e.jsx("article",{"aria-label":`${U}的消息`,className:`make-ai-assistant__message make-ai-assistant__message--${n.role}`,"data-message-role":n.role,"data-message-state":X?"error":void 0,"data-message-status":n.status,"data-message-has-identity":v||G?!0:void 0,children:e.jsxs("div",{className:"make-ai-assistant__message-turn",children:[v?e.jsx(Kt,{assistantName:d}):G?e.jsx(Ks,{userAvatarUrl:p,userName:y}):null,e.jsxs("div",{className:"make-ai-assistant__message-stack",children:[v&&n.responseId&&t.responses?.[n.responseId]?.status==="cancelled"?e.jsx("p",{className:"make-ai-assistant__response-status",role:"status",children:"已停止生成"}):null,n.content?v?e.jsx(Nt,{content:n.content}):e.jsx("div",{className:"make-ai-assistant__bubble",children:n.content}):n.status==="streaming"?e.jsxs("div",{className:"make-ai-assistant__typing","aria-label":`${d}正在思考`,children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}):null,v?e.jsx(Ht,{active:K&&t.status==="streaming",steps:n.progressSteps}):null,X?e.jsx(qt,{error:X,onRetry:I?h:void 0}):null,n.artifacts.map(O=>e.jsx(Et,{artifact:O,context:s,onAction:o,onActionError:l,registry:a,theme:i},O.id)),A&&D&&t.threadId?e.jsx(ps,{message:n,context:s,transport:D,chatId:t.threadId}):null,re?e.jsx(Qs,{copyFeedback:C?.messageId===n.id?{message:C.message,status:C.status}:void 0,onCopy:n.content.trim()?()=>R(n.id,n.content):void 0,feedback:A&&me?e.jsx(hs,{message:n,manager:A}):void 0,onRegenerate:S&&n.id===F&&_?()=>V({userMessage:_,assistantMessage:n}):void 0}):null]})]})},`${t.threadId??"local"}:${n.id}`)})};function Zt({assistantName:t="AI 助手",brandName:s,context:a,onAction:i,onActionError:o,onClose:l,onNewConversation:d,headerHeight:h,registry:y,suggestions:p,title:C,theme:S,transport:R,userAvatarUrl:V,userName:A,visible:D}){const g=ns(a,R),N=ys(a,R,g),F=Ut(s,C),f=Ts(h),n=dt(S),v=n||f?{...n,...f?{"--make-ai-internal-header-height":f}:{}}:void 0,[_,K]=c.useState(""),[I,X]=c.useState(!1),[G,U]=c.useState(!1),J=g.enabled?R.scopeKey?.(a)??a.app.id:"";c.useLayoutEffect(()=>{g.enabled&&K("")},[J,g.enabled]);const[me,re]=c.useState(b.createAssistantConversationState),O=g.enabled?g.state:me,ae=g.enabled?g.setState:re,ie=c.useRef(O);ie.current=O;const[q,$]=c.useState(void 0),[w,P]=c.useState(void 0),[te,he]=c.useState(0),[we,E]=c.useState(()=>R.loadConversation?"loading":"ready"),Q=g.enabled?g.loading&&!O.messages.length?"loading":"ready":we,[oe,ce]=c.useState(void 0),[at,fe]=c.useState(!1),xe=c.useRef(void 0),pe=c.useRef(void 0),ee=c.useRef(0),_e=c.useRef(null),ve=c.useRef(null),Oe=c.useRef(null),Fe=c.useRef(null),Ae=c.useRef(null),We=c.useRef(null),le=c.useRef(!0),Ve=c.useRef(a.app.id),qe=c.useRef(D),He=c.useId(),Ze=c.useMemo(()=>y??Ot(),[y]),Xe=c.useMemo(()=>ws(p),[p]),Ne=m=>{const W=xe.current,Z=pe.current?.iterator;return!W&&!Z?!1:(ee.current+=1,xe.current=void 0,pe.current=void 0,console.info("[make-ai-assistant] local run cancellation requested",{reason:m}),W?.abort(),Mt(Z),!0)};c.useEffect(()=>()=>{Ne("unmount")},[]),c.useEffect(()=>{if(g.enabled)return;const m=R.loadConversation,W=Ve.current!==a.app.id;if(Ve.current=a.app.id,Ne("reinitialize"),W&&(K(""),le.current=!0),$(void 0),P(void 0),fe(!1),ae(b.createAssistantConversationState()),!m){ce(void 0),E("ready");return}const Z=new AbortController;return ce(void 0),E("loading"),console.info("[make-ai-assistant] conversation load start",{appId:a.app.id}),m.call(R,a,{signal:Z.signal}).then(se=>{Z.signal.aborted||(ae(b.createAssistantConversationState(se)),E("ready"),console.info("[make-ai-assistant] conversation load success",{appId:a.app.id,messageCount:se.messages.length}))}).catch(se=>{Z.signal.aborted||(console.error("[make-ai-assistant] conversation load failed",{appId:a.app.id,errorType:se instanceof Error?se.name:typeof se}),ce(se),E("error"))}),()=>Z.abort()},[a.app.id,te,R,g.enabled]),c.useEffect(()=>{const m=ve.current;if(!m||!le.current)return;fe(!1);const W=requestAnimationFrame(()=>{if(!le.current)return;const Z=O.status==="streaming"||globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches?"auto":"smooth";lt(m,Z)});return()=>cancelAnimationFrame(W)},[O.messages,O.progress,O.status]),c.useEffect(()=>{D||(X(!1),U(!1))},[D]),c.useEffect(()=>{const m=D&&!qe.current;if(qe.current=D,!m)return;const W=requestAnimationFrame(()=>{const Z=ve.current;if(Z&&le.current){fe(!1);const Ue=ie.current.status==="streaming"?"auto":Tt();lt(Z,Ue)}else Z&&fe(ie.current.messages.length>0);const se=Oe.current;(se&&!se.disabled?se:We.current??_e.current?.querySelector("button:not(:disabled)"))?.focus()});return()=>cancelAnimationFrame(W)},[D]);const nt=()=>{const m=ve.current;if(!m)return;const W=Ys(m);le.current=W,fe(!W&&ie.current.messages.length>0)},Me=()=>{const m=ve.current;if(!m)return;le.current=!0,fe(!1);const W=Tt();lt(m,W)},r=async(m,W)=>{const Z=m.trim(),se=ie.current,be=W?.regenerateFrom,Ue=R.regenerate;if(!Z||Q!=="ready"||se.status==="streaming"||xe.current||be&&!Ue)return;if(b.countCodePointsUpTo(Z,b.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)>b.MAKE_AI_CONVERSATION_LIMITS.messageCharacters){$(`输入内容过长,请控制在 ${b.MAKE_AI_CONVERSATION_LIMITS.messageCharacters} 个字符以内`);return}const Ye={id:be?.userMessage.id??js("user"),content:Z},Je=be?Gs(se,be.userMessage.id):b.appendUserMessage(se,Ye),Qe=new AbortController,Se=ee.current+1;ee.current=Se,xe.current=Qe,$(void 0),P(void 0),fe(!le.current&&se.messages.length>0),be||K(""),ae(Je);try{let je=!1,ne,mt=0,ht=0,ft=0,rt=0,Pe=0;const Be=new Map,pt=new Set,vt=new Set([...Je.messages.map(et=>et.id),Ye.id]),ze=new Set,gt=Ie.createArtifactCapabilities(Ze),xt={signal:Qe.signal};let it;if(be){if(!Ue)throw new Y("当前 AI 助手不支持重新生成");it=Ue({threadId:Je.threadId,message:Ye,assistantMessage:{id:be.assistantMessage.id,content:be.assistantMessage.content},context:a,capabilities:gt},xt)}else it=R.run({threadId:Je.threadId,message:Ye,context:a,capabilities:gt},xt);const yt=it[Symbol.asyncIterator]();for(pe.current={iterator:yt,requestVersion:Se};;){const et=await yt.next();if(ee.current!==Se||et.done)break;let T;try{T=b.parseAssistantEvent(et.value)}catch(ue){throw new Y(ue instanceof Error?ue.message:"Invalid assistant event")}if(T.type==="message.start"){if(ne!==void 0&&ne!==T.runId)throw new Y("AI 助手响应 run id 不一致");if(ne??=T.runId,ht+=1,ht>b.MAKE_AI_CONVERSATION_LIMITS.assistantMessagesPerRun)throw new Y("AI 助手单次响应消息数量超过限制");if(vt.has(T.messageId))throw new Y("AI 助手响应包含重复的 message id");vt.add(T.messageId),ze.add(T.messageId),Be.set(T.messageId,0)}if(T.type==="message.delta"){if(!ze.has(T.messageId))throw new Y("AI 助手响应事件顺序无效");const ue=Be.get(T.messageId)??0,Ce=b.countCodePointsUpTo(T.delta,b.MAKE_AI_CONVERSATION_LIMITS.messageCharacters-Pe);if(Pe+Ce>b.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)throw new Y("AI 助手响应文本超过大小限制");Pe+=Ce,Be.set(T.messageId,ue+Ce)}if(T.type==="message.replace"){if(!ze.has(T.messageId))throw new Y("AI 助手响应事件顺序无效");const ue=Be.get(T.messageId)??0,Ce=b.countCodePointsUpTo(T.content,b.MAKE_AI_CONVERSATION_LIMITS.messageCharacters),bt=Pe-ue+Ce;if(bt>b.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)throw new Y("AI 助手响应文本超过大小限制");Pe=bt,Be.set(T.messageId,Ce)}if(T.type==="run.progress"){if(ne!==void 0&&ne!==T.runId)throw new Y("AI 助手响应 run id 不一致");if(ne??=T.runId,ft+=1,ft>b.MAKE_AI_CONVERSATION_LIMITS.progressStepsPerRun)throw new Y("AI 助手处理过程数量超过限制");const ue=b.countCodePointsUpTo(T.message,b.MAKE_AI_CONVERSATION_LIMITS.progressCharactersPerRun-rt);if(rt+ue>b.MAKE_AI_CONVERSATION_LIMITS.progressCharactersPerRun)throw new Y("AI 助手处理过程文本超过大小限制");rt+=ue}if(T.type==="artifact"){if(!ze.has(T.messageId))throw new Y("AI 助手响应事件顺序无效");if(mt+=1,mt>b.MAKE_AI_CONVERSATION_LIMITS.artifactsPerRun)throw new Y("AI 助手单次响应 Artifact 数量超过限制");if(pt.has(T.artifact.id))throw new Y("AI 助手响应包含重复的 Artifact id");pt.add(T.artifact.id)}if(T.type==="message.complete"&&!ze.delete(T.messageId))throw new Y("AI 助手响应事件顺序无效");if(T.type==="run.complete"&&ne!==void 0&&ne!==T.runId)throw new Y("AI 助手响应 run id 不一致");if(T.type==="run.cancelled"&&T.runId!==void 0&&ne!==void 0&&ne!==T.runId)throw new Y("AI 助手响应 run id 不一致");if(ae(ue=>b.reduceAssistantEvent(ue,T)),T.type==="error"||T.type==="run.cancelled"||T.type==="run.complete"){je=!0;break}}if(!je)throw new Y("AI 助手流式响应在终止事件前结束")}catch(je){if(ee.current!==Se)return;if(Qe.signal.aborted){ae(ne=>b.reduceAssistantEvent(ne,{type:"run.cancelled"}));return}console.error("[make-ai-assistant] assistant run failed",{appId:a.app.id,errorType:je instanceof Error?je.name:typeof je}),ae(ne=>b.reduceAssistantEvent(ne,{type:"error",code:"TRANSPORT_ERROR",message:je instanceof Y?je.message:"连接失败,请重试",retryable:!0}))}finally{ee.current===Se&&xe.current===Qe&&(xe.current=void 0),pe.current?.requestVersion===Se&&(Mt(pe.current.iterator),pe.current=void 0)}},u=m=>{if(g.enabled){if(N.pending)return $("请等待附件上传完成,或移除失败的附件"),Promise.resolve();const W=m.trim(),Z=N.parts.length?[...W?[{id:Le(),kind:"text",text:W}]:[],...N.parts]:void 0;return K(""),N.clear(),g.send(W,Z)}return r(m)},x=m=>r(m.userMessage.content,{regenerateFrom:m}),k=async(m,W)=>{try{await Es(W),P({messageId:m,message:"已复制",status:"success"})}catch(Z){console.error("[make-ai-assistant] copy answer failed",{errorType:Z instanceof Error?Z.name:typeof Z}),P({messageId:m,message:"复制失败",status:"error"})}},M=m=>{m.preventDefault(),u(_)},L=m=>{m.key==="Enter"&&!m.shiftKey&&!m.nativeEvent.isComposing&&(m.preventDefault(),u(_))},j=()=>{if(g.enabled){g.stop();return}Ne("stop")&&ae(m=>b.reduceAssistantEvent(m,{type:"run.cancelled"}))},H=()=>{if(U(!1),g.enabled){K(""),g.create(),d?.();return}Ne("new-conversation"),K(""),$(void 0),P(void 0),fe(!1),le.current=!0,ae(b.createAssistantConversationState()),d?.()},B=g.enabled&&g.cancelling.length?"停止中":R.features?.remoteCancellation===!1?"停止接收":"停止生成",z=Wt(O),ye=Vt(O),Re=Xs(O),Ge=typeof R.regenerate=="function"&&R.features?.regeneration!==!1,de=()=>{if(g.enabled){g.retry();return}Re&&u(Re.content)},Te=m=>{if(m.key==="Escape"&&!(!I&&!G)){if(m.preventDefault(),m.stopPropagation(),I){X(!1),Fe.current?.focus();return}U(!1),Ae.current?.focus()}};return e.jsxs("section",{className:`make-ai-assistant make-ai-assistant__panel${g.enabled?" make-ai-assistant__panel--managed":""}`,ref:_e,style:v,onKeyDown:Te,onDragOver:m=>{N.enabled&&m.dataTransfer.types.includes("Files")&&m.preventDefault()},onDrop:m=>{N.enabled&&m.dataTransfer.files.length&&(m.preventDefault(),N.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:g.enabled?e.jsxs("button",{"aria-controls":He,"aria-expanded":G,"aria-haspopup":"dialog","aria-label":"任务列表",className:"make-ai-assistant__task-list-trigger",ref:Ae,type:"button",onClick:()=>U(m=>!m),children:[e.jsx(Us,{}),e.jsx("span",{children:"任务列表"}),e.jsx(Ps,{})]}):null}),e.jsxs("div",{className:"make-ai-assistant__header-center",children:[e.jsx(st,{}),e.jsx("h2",{className:"make-ai-assistant__header-title",title:F,children:F})]}),e.jsxs("div",{className:"make-ai-assistant__header-actions",children:[R.features?.newConversation!==!1?e.jsx("button",{"aria-label":"新建对话",className:"make-ai-assistant__icon-button",type:"button",onClick:H,children:e.jsx(Fs,{})}):null,l?e.jsx("button",{"aria-label":`关闭 ${F}`,className:"make-ai-assistant__icon-button",type:"button",onClick:l,children:e.jsx(Ls,{})}):null]})]}),g.enabled&&G?e.jsx(ms,{id:He,manager:g,triggerRef:Ae,onDismiss:()=>U(!1),onNewConversation:R.features?.newConversation!==!1?H:void 0}):null,e.jsxs("div",{className:"make-ai-assistant__body","aria-live":"polite","aria-relevant":"additions text",ref:ve,role:"log",onScroll:nt,children:[Q==="loading"?e.jsxs("div",{className:"make-ai-assistant__empty",role:"status",children:[e.jsx(st,{}),e.jsx("h3",{children:"正在恢复对话"}),e.jsx("p",{children:"正在读取当前 App 的历史消息…"})]}):Q==="error"?e.jsx("div",{className:"make-ai-assistant__empty",children:e.jsx(Js,{error:oe,onRetry:()=>he(m=>m+1)})}):O.messages.length===0?e.jsxs("div",{className:"make-ai-assistant__empty",children:[e.jsx(st,{}),e.jsx("h3",{children:"有什么可以帮你?"}),e.jsx("p",{children:"我会结合当前 App、页面位置和宿主允许的上下文回答,并把过程与结果分开展示。"})]}):ea(O,a,Ze,S,i,o,t,Re?de:void 0,A,V,w,Ge,(m,W)=>{k(m,W)},m=>{x(m)},g.enabled?g:void 0,R),O.progress&&!z?e.jsx(St,{assistantName:t,progress:O.progress}):null,O.error&&!ye?e.jsx(St,{assistantName:t,error:O.error,onRetry:Re?de:void 0}):null]}),at?e.jsx("button",{"aria-label":"回到最新消息",className:"make-ai-assistant__back-to-latest",type:"button",onClick:Me,children:e.jsx(Os,{})}):null,e.jsxs("footer",{className:"make-ai-assistant__composer-region",children:[N.enabled?e.jsx(_s,{attachments:N}):null,Q==="ready"&&Xe.length>0&&O.messages.length===0?e.jsx("div",{className:"make-ai-assistant__suggestions","aria-label":"推荐问题",children:Xe.map((m,W)=>e.jsx("button",{type:"button",onClick:()=>{u(m)},children:m},`${W}-${m}`))}):null,e.jsxs("form",{className:"make-ai-assistant__composer",onSubmit:M,children:[e.jsx("textarea",{"aria-label":`向 ${t} 提问`,"aria-describedby":q?"make-ai-composer-error":void 0,"aria-invalid":q?!0:void 0,autoFocus:!0,disabled:Q!=="ready"||!g.enabled&&O.status==="streaming",placeholder:`询问当前 ${a.app.name??"App"} 中的数据…`,ref:Oe,rows:2,value:_,onChange:m=>{K(m.currentTarget.value),$(void 0)},onKeyDown:L,onPaste:m=>{N.enabled&&m.clipboardData.files.length&&(m.preventDefault(),N.add(Array.from(m.clipboardData.files)))}}),N.enabled?e.jsx(bs,{attachments:N,open:I,triggerRef:Fe,onOpenChange:X}):null,e.jsxs("div",{className:"make-ai-assistant__composer-actions",children:[O.status==="streaming"?e.jsx("button",{"aria-label":B,className:"make-ai-assistant__send make-ai-assistant__send--stop","data-tooltip":B,ref:We,disabled:g.enabled&&g.cancelling.includes(O.activeRunId??""),type:"button",onClick:j,children:e.jsx("span",{"aria-hidden":"true"})}):e.jsx("button",{"aria-label":"发送",className:"make-ai-assistant__send",disabled:Q!=="ready"||N.pending||!_.trim()&&!N.parts.length,type:"submit",children:e.jsx(Rt,{})}),g.enabled&&O.status==="streaming"?e.jsx("button",{"aria-label":"发送",className:"make-ai-assistant__send",disabled:g.busy||N.pending||!_.trim()&&!N.parts.length,type:"submit",children:e.jsx(Rt,{})}):null]})]}),q?e.jsx("p",{id:"make-ai-composer-error",role:"alert",children:q}):null,e.jsx("p",{children:"AI 生成的结果可能存在偏差,重要数据请核对明细。"})]})]})}function ta(t){return e.jsx(Zt,{...t,visible:!0})}function sa({defaultOpen:t=!1,hideLauncher:s=!1,launcher:a,launcherPosition:i="bottom-right",maxDrawerWidth:o,onOpenChange:l,open:d,...h}){const y=Ut(h.brandName,h.title),[p,C]=c.useState(t),[S,R]=c.useState(()=>t||d===!0),V=c.useRef(null),A=c.useRef(null),D=c.useRef(void 0),[g,N]=c.useState(),[F,f]=c.useState(As),[n,v]=c.useState(!1),_=d??p,K=dt(h.theme),I=Rs(o),X=()=>Ns(F,I,typeof window>"u"?Pt:window.innerWidth),G=X(),U=g===void 0?void 0:ot(g,F,G),J=U===void 0&&I===void 0?void 0:{...U===void 0?{}:{"--make-ai-internal-drawer-width":`${U}px`},...I===void 0?{}:{"--make-ai-internal-drawer-max-width":`max(var(--make-ai-internal-drawer-min-width), ${I}px)`}};c.useLayoutEffect(()=>{U!==void 0&&U!==g&&N(U)},[U,g]);const me=()=>{if(U!==void 0)return U;const w=A.current?.getBoundingClientRect().width;return w&&Number.isFinite(w)&&w>0?w:F},re=w=>{if(w.button!==0)return;const P=me(),te=g===void 0?P:F;f(te),D.current={minimumWidth:te,pointerId:w.pointerId,startWidth:P,startX:w.clientX},v(!0),typeof w.currentTarget.setPointerCapture=="function"&&w.currentTarget.setPointerCapture(w.pointerId),w.preventDefault()},O=w=>{const P=D.current;if(!P||P.pointerId!==w.pointerId)return;const te=ot(P.startWidth+P.startX-w.clientX,P.minimumWidth,X());N(te)},ae=w=>{const P=D.current;!P||P.pointerId!==w.pointerId||(D.current=void 0,v(!1))},ie=w=>{const P=w.key==="ArrowLeft"?At:w.key==="ArrowRight"?-At:void 0;if(P===void 0)return;w.preventDefault();const te=me(),he=g===void 0?te:F;f(he),N(ot(te+P,he,X()))},q=w=>{d===void 0&&C(w),l?.(w),w||requestAnimationFrame(()=>V.current?.focus())},$=()=>q(!_);return c.useEffect(()=>{_&&R(!0)},[_]),c.useEffect(()=>{if(!_)return;const w=P=>{P.key==="Escape"&&(q(!1),requestAnimationFrame(()=>V.current?.focus()))};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[l,_]),e.jsxs("div",{className:"make-ai-assistant","data-open":_||void 0,style:K,children:[!s&&(!_||a)?a?a({open:_,toggle:$}):e.jsxs("button",{"aria-label":_?`关闭 ${y}`:`打开 ${y}`,"aria-expanded":_,className:"make-ai-assistant__launcher","data-launcher-position":i,ref:V,type:"button",onClick:$,children:[e.jsx("span",{className:"make-ai-assistant__launcher-orbit","aria-hidden":"true"}),e.jsx(Bt,{})]}):null,S?e.jsxs("aside",{"aria-label":y,"aria-modal":"false",className:"make-ai-assistant__drawer","data-resizing":n||void 0,hidden:!_,ref:A,role:"dialog",style:J,children:[e.jsx("div",{"aria-label":"调整对话框宽度","aria-orientation":"vertical","aria-valuemax":G,"aria-valuemin":F,"aria-valuenow":U??F,className:"make-ai-assistant__drawer-resize-handle",role:"separator",tabIndex:0,onKeyDown:ie,onPointerCancel:ae,onPointerDown:re,onPointerMove:O,onPointerUp:ae}),e.jsx(Zt,{...h,onClose:()=>q(!1),visible:_})]}):null]})}exports.createArtifactCapabilities=Ie.createArtifactCapabilities;exports.createArtifactTemplateRegistry=Ie.createArtifactTemplateRegistry;exports.extendArtifactTemplateRegistry=Ie.extendArtifactTemplateRegistry;exports.resolveArtifactTemplate=Ie.resolveArtifactTemplate;exports.MAKE_AI_ARTIFACT_KINDS=b.MAKE_AI_ARTIFACT_KINDS;exports.MAKE_AI_ARTIFACT_LIMITS=b.MAKE_AI_ARTIFACT_LIMITS;exports.MAKE_AI_ARTIFACT_SCHEMA_VERSION=b.MAKE_AI_ARTIFACT_SCHEMA_VERSION;exports.MAKE_AI_CONVERSATION_LIMITS=b.MAKE_AI_CONVERSATION_LIMITS;exports.appendUserMessage=b.appendUserMessage;exports.createAssistantConversationState=b.createAssistantConversationState;exports.parseArtifact=b.parseArtifact;exports.parseAssistantEvent=b.parseAssistantEvent;exports.reduceAssistantEvent=b.reduceAssistantEvent;exports.validateArtifact=b.validateArtifact;exports.ArtifactRenderer=Et;exports.AssistantPanel=ta;exports.MakeAiAssistant=sa;exports.createPlatformArtifactRegistry=Ot;exports.formatArtifactValue=ke;exports.platformArtifactTemplates=Dt;
3
+ `),u=()=>{const v=a.join(`
4
+ `).trim();a.length=0,v&&s.push({type:"paragraph",text:v})},p=()=>{o.length&&s.push({type:"list",items:o.splice(0)})},d=()=>{const v=i.join(`
5
+ `).trim();i.length=0,v&&s.push({type:"pre",text:v})};for(let v=0;v<l.length;v+=1){const S=l[v]??"",R=S.trim();if(!R){u(),p(),d();continue}const O=Ys(l,v);if(O){u(),p(),d(),s.push({headers:O.headers,rows:O.rows,type:"table"}),v=O.lastIndex;continue}const F=/^(#{1,6})\s+(.+)$/.exec(R);if(F){u(),p(),d();const B=(F[2]??"").replace(/\s+#+\s*$/,"").trim();B&&s.push({type:"heading",level:F[1]?.length,text:B});continue}if(/^\s*\|.+\|\s*$/.test(S)){u(),p(),i.push(S.trim());continue}const b=/^\s*[-*]\s+(.+)$/.exec(S);if(b){u(),d(),o.push(b[1]?.trim()??"");continue}p(),d(),a.push(R)}return u(),p(),d(),s},We=t=>{const s=[],a=/(\*\*[^*]+\*\*|`[^`]+`)/g;let o=0;for(const i of t.matchAll(a)){const l=i[0],u=i.index??0;u>o&&s.push(t.slice(o,u)),l.startsWith("**")?s.push(e.jsx("strong",{children:l.slice(2,-2)},`${u}-strong`)):s.push(e.jsx("code",{children:l.slice(1,-1)},`${u}-code`)),o=u+l.length}return o<t.length&&s.push(t.slice(o)),s},Lt=({content:t})=>{const s=Qs(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 i=a.level<=2?"h3":"h4";return e.jsx(i,{className:`make-ai-assistant__markdown-heading make-ai-assistant__markdown-heading--${a.level}`,children:We(a.text)},`${o}-heading`)}return a.type==="paragraph"?e.jsx("p",{children:We(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((i,l)=>e.jsx("th",{scope:"col",children:We(i)},`${l}-${i}`))})}),e.jsx("tbody",{children:a.rows.map((i,l)=>e.jsx("tr",{children:i.map((u,p)=>e.jsx("td",{children:We(u)},`${p}-${u}`))},`${l}-${i.join("|")}`))})]})},`${o}-table`):e.jsx("ul",{children:a.items.map((i,l)=>e.jsx("li",{children:We(i)},`${l}-${i}`))},`${o}-list`)})}):null},Wt=({assistantName:t})=>e.jsxs("div",{className:"make-ai-assistant__message-identity",children:[e.jsx(ot,{className:"make-ai-assistant__avatar--message"}),e.jsx("span",{className:"make-ai-assistant__message-sender",children:t})]}),Gt=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}},ea=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=ea(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}},ta=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}},sa=t=>{for(let s=t.messages.length-1;s>=0;s-=1){const a=t.messages[s];if(a.role==="user")return a}},aa=(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)}},na=t=>t.scrollHeight-t.scrollTop-t.clientHeight<=48,$t=(t="smooth")=>globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches?"auto":t,ft=(t,s)=>{typeof t.scrollTo=="function"?t.scrollTo({top:t.scrollHeight,behavior:s}):t.scrollTop=t.scrollHeight},Jt=({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(Ws,{})}),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(Zt,{}),"重新发送"]}):null]}),ra=({error:t,onRetry:s})=>{const a=Bs(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(Zt,{}),a.actionLabel]})]})},Yt=({active:t,steps:s})=>{const[a,o]=c.useState(!1);if(!t||!s?.length)return null;const i=s[s.length-1]??"处理中";return e.jsxs("details",{className:"make-ai-assistant__process",open:a,onToggle:l=>o(l.currentTarget.open),children:[e.jsxs("summary",{"aria-label":`查看处理过程,共 ${s.length} 步`,children:[e.jsxs("span",{className:"make-ai-assistant__process-summary",children:[e.jsx("span",{className:"make-ai-assistant__process-indicator","aria-hidden":"true"}),e.jsxs("span",{className:"make-ai-assistant__process-copy",children:[e.jsx("span",{className:"make-ai-assistant__process-title",children:"处理过程"}),e.jsx("span",{className:"make-ai-assistant__progress make-ai-assistant__process-latest",role:"status",children:i})]})]}),e.jsxs("span",{className:"make-ai-assistant__process-count",children:[s.length," 步"]})]}),e.jsx("ol",{children:s.map((l,u)=>e.jsxs("li",{"data-step-active":u===s.length-1?!0:void 0,children:[e.jsx("span",{"aria-hidden":"true"}),e.jsx("span",{children:l})]},`${u}-${l}`))})]})},ia=({copyFeedback:t,feedback:s,onCopy:a,onRegenerate:o})=>!s&&!a&&!o?null:e.jsxs("div",{className:"make-ai-assistant__reply-actions","aria-label":"回复操作",children:[a?e.jsx("button",{"aria-label":"复制回答",className:"make-ai-assistant__reply-action make-ai-assistant__reply-copy","data-tooltip":"复制",type:"button",onClick:a,children:e.jsx(vs,{"aria-hidden":"true",className:"make-ai-assistant__reply-copy-icon"})}):null,s,o?e.jsx("button",{"aria-label":"重新生成",className:"make-ai-assistant__reply-action make-ai-assistant__reply-regenerate","data-tooltip":"重新生成",type:"button",onClick:o,children:e.jsx(qs,{})}):null,t?e.jsx("span",{className:"make-ai-assistant__reply-feedback","data-copy-status":t.status,role:"status",children:t.message}):null]}),Ot=({assistantName:t,error:s,onRetry:a,progress:o})=>{const i=s?"error":"progress";return s?.message??o?.message?e.jsx("article",{"aria-label":`${t}的${i==="error"?"错误消息":"状态消息"}`,className:`make-ai-assistant__message make-ai-assistant__message--assistant make-ai-assistant__message--${i}`,"data-message-role":"assistant","data-message-state":i,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(Jt,{error:s,onRetry:a}):e.jsx(Yt,{active:!0,steps:o?.steps})})]})}):null},oa=(t,s,a,o,i,l,u,p,d,v,S,R,O,F,b,B)=>{const L=Xt(t),D=Gt(t),k=ta(t);let f;return t.messages.map(n=>{if(n.intermediate)return e.jsxs("details",{className:"make-ai-assistant__process",children:[e.jsx("summary",{children:"处理过程"}),e.jsx(Lt,{content:n.content})]},n.id);const _=n.role==="assistant",A=f;_||(f=n);const G=n.id===D,I=n.id===L?t.error:void 0,z=n.error??I,J=!_&&!!(d?.trim()||v),ae=_?u:d?.trim()||"用户",Z=_&&n.status==="complete"&&!z&&(n.content.trim()||n.id===k),ce=!!(b&&B?.features?.feedback&&_&&n.persistent),me=Z||ce;return e.jsx("article",{"aria-label":`${ae}的消息`,className:`make-ai-assistant__message make-ai-assistant__message--${n.role}`,"data-message-role":n.role,"data-message-state":z?"error":void 0,"data-message-status":n.status,"data-message-has-identity":_||J?!0:void 0,children:e.jsxs("div",{className:"make-ai-assistant__message-turn",children:[_?e.jsx(Wt,{assistantName:u}):J?e.jsx(Xs,{userAvatarUrl:v,userName:d}):null,e.jsxs("div",{className:"make-ai-assistant__message-stack",children:[_&&n.responseId&&t.responses?.[n.responseId]?.status==="cancelled"?e.jsx("p",{className:"make-ai-assistant__response-status",role:"status",children:"已停止生成"}):null,n.content?_?e.jsx(Lt,{content:n.content}):e.jsx("div",{className:"make-ai-assistant__bubble",children:n.content}):n.status==="streaming"?e.jsxs("div",{className:"make-ai-assistant__typing","aria-label":`${u}正在思考`,children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}):null,_?e.jsx(Yt,{active:G&&t.status==="streaming",steps:n.progressSteps}):null,z?e.jsx(Jt,{error:z,onRetry:I?p:void 0}):null,n.artifacts.map(je=>e.jsx(Ut,{artifact:je,context:s,onAction:i,onActionError:l,registry:a,theme:o},je.id)),b&&B&&t.threadId?e.jsx(Ns,{message:n,context:s,transport:B,chatId:t.threadId}):null,me?e.jsx(ia,{copyFeedback:S?.messageId===n.id?{message:S.message,status:S.status}:void 0,onCopy:n.content.trim()?()=>O(n.id,n.content):void 0,feedback:b&&ce?e.jsx(ws,{message:n,manager:b}):void 0,onRegenerate:R&&n.id===k&&A?()=>F({userMessage:A,assistantMessage:n}):void 0}):null]})]})},`${t.threadId??"local"}:${n.id}`)})};function Qt({assistantName:t="AI 助手",brandName:s,context:a,onAction:o,onActionError:i,onClose:l,onNewConversation:u,onToggleFullscreen:p,headerHeight:d,isFullscreen:v=!1,registry:S,suggestions:R,title:O,theme:F,transport:b,userAvatarUrl:B,userName:L,visible:D}){const k=xs(a,b),f=Ss(a,b,k),n=zt(s,O),_=Ks(d),A=pt(F),G=A||_?{...A,..._?{"--make-ai-internal-header-height":_}:{}}:void 0,[I,z]=c.useState(""),[J,ae]=c.useState(!1),[Z,ce]=c.useState(!1),me=k.enabled?b.scopeKey?.(a)??a.app.id:"";c.useLayoutEffect(()=>{k.enabled&&z("")},[me,k.enabled]);const[je,Pe]=c.useState(j.createAssistantConversationState),P=k.enabled?k.state:je,H=k.enabled?k.setState:Pe,$=c.useRef(P);$.current=P;const[X,re]=c.useState(void 0),[pe,le]=c.useState(void 0),[Ie,T]=c.useState(0),[ee,Y]=c.useState(()=>b.loadConversation?"loading":"ready"),Q=k.enabled?k.loading&&!P.messages.length?"loading":"ready":ee,[Ue,De]=c.useState(void 0),[Ge,ie]=c.useState(!1),q=c.useRef(void 0),oe=c.useRef(void 0),_e=c.useRef(0),we=c.useRef(null),be=c.useRef(null),Me=c.useRef(null),Ce=c.useRef(null),Ke=c.useRef(null),He=c.useRef(null),he=c.useRef(!0),Xe=c.useRef(a.app.id),Je=c.useRef(D),Ye=c.useId();c.useLayoutEffect(()=>{const h=Me.current;h&&(h.style.height="auto",h.style.height=`${Math.min(Math.max(h.scrollHeight,Fs),Ps)}px`)},[I]);const Qe=c.useMemo(()=>S??Bt(),[S]),et=c.useMemo(()=>Us(R),[R]),Ee=h=>{const K=q.current,V=oe.current?.iterator;return!K&&!V?!1:(_e.current+=1,q.current=void 0,oe.current=void 0,console.info("[make-ai-assistant] local run cancellation requested",{reason:h}),K?.abort(),Tt(V),!0)};c.useEffect(()=>()=>{Ee("unmount")},[]),c.useEffect(()=>{if(k.enabled)return;const h=b.loadConversation,K=Xe.current!==a.app.id;if(Xe.current=a.app.id,Ee("reinitialize"),K&&(z(""),he.current=!0),re(void 0),le(void 0),ie(!1),H(j.createAssistantConversationState()),!h){De(void 0),Y("ready");return}const V=new AbortController;return De(void 0),Y("loading"),console.info("[make-ai-assistant] conversation load start",{appId:a.app.id}),h.call(b,a,{signal:V.signal}).then(te=>{V.signal.aborted||(H(j.createAssistantConversationState(te)),Y("ready"),console.info("[make-ai-assistant] conversation load success",{appId:a.app.id,messageCount:te.messages.length}))}).catch(te=>{V.signal.aborted||(console.error("[make-ai-assistant] conversation load failed",{appId:a.app.id,errorType:te instanceof Error?te.name:typeof te}),De(te),Y("error"))}),()=>V.abort()},[a.app.id,Ie,b,k.enabled]),c.useEffect(()=>{const h=be.current;if(!h||!he.current)return;ie(!1);const K=requestAnimationFrame(()=>{if(!he.current)return;const V=P.status==="streaming"||globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches?"auto":"smooth";ft(h,V)});return()=>cancelAnimationFrame(K)},[P.messages,P.progress,P.status]),c.useEffect(()=>{D||(ae(!1),ce(!1))},[D]),c.useEffect(()=>{const h=D&&!Je.current;if(Je.current=D,!h)return;const K=requestAnimationFrame(()=>{const V=be.current;if(V&&he.current){ie(!1);const Ve=$.current.status==="streaming"?"auto":$t();ft(V,Ve)}else V&&ie($.current.messages.length>0);const te=Me.current;(te&&!te.disabled?te:He.current??we.current?.querySelector("button:not(:disabled)"))?.focus()});return()=>cancelAnimationFrame(K)},[D]);const Be=()=>{const h=be.current;if(!h)return;const K=na(h);he.current=K,ie(!K&&$.current.messages.length>0)},Ae=()=>{const h=be.current;if(!h)return;he.current=!0,ie(!1);const K=$t();ft(h,K)},r=async(h,K)=>{const V=h.trim(),te=$.current,ge=K?.regenerateFrom,Ve=b.regenerate;if(!V||Q!=="ready"||te.status==="streaming"||q.current||ge&&!Ve)return;if(j.countCodePointsUpTo(V,j.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)>j.MAKE_AI_CONVERSATION_LIMITS.messageCharacters){re(`输入内容过长,请控制在 ${j.MAKE_AI_CONVERSATION_LIMITS.messageCharacters} 个字符以内`);return}const st={id:ge?.userMessage.id??Ls("user"),content:V},at=ge?aa(te,ge.userMessage.id):j.appendUserMessage(te,st),nt=new AbortController,Te=_e.current+1;_e.current=Te,q.current=nt,re(void 0),le(void 0),ie(!he.current&&te.messages.length>0),ge||z(""),H(at);try{let ye=!1,ne,_t=0,bt=0,yt=0,lt=0,ze=0;const qe=new Map,xt=new Set,kt=new Set([...at.messages.map(rt=>rt.id),st.id]),Ze=new Set,jt=ke.createArtifactCapabilities(Qe),It={signal:nt.signal};let dt;if(ge){if(!Ve)throw new W("当前 AI 助手不支持重新生成");dt=Ve({threadId:at.threadId,message:st,assistantMessage:{id:ge.assistantMessage.id,content:ge.assistantMessage.content},context:a,capabilities:jt},It)}else dt=b.run({threadId:at.threadId,message:st,context:a,capabilities:jt},It);const wt=dt[Symbol.asyncIterator]();for(oe.current={iterator:wt,requestVersion:Te};;){const rt=await wt.next();if(_e.current!==Te||rt.done)break;let E;try{E=j.parseAssistantEvent(rt.value)}catch(ue){throw new W(ue instanceof Error?ue.message:"Invalid assistant event")}if(E.type==="message.start"){if(ne!==void 0&&ne!==E.runId)throw new W("AI 助手响应 run id 不一致");if(ne??=E.runId,bt+=1,bt>j.MAKE_AI_CONVERSATION_LIMITS.assistantMessagesPerRun)throw new W("AI 助手单次响应消息数量超过限制");if(kt.has(E.messageId))throw new W("AI 助手响应包含重复的 message id");kt.add(E.messageId),Ze.add(E.messageId),qe.set(E.messageId,0)}if(E.type==="message.delta"){if(!Ze.has(E.messageId))throw new W("AI 助手响应事件顺序无效");const ue=qe.get(E.messageId)??0,Re=j.countCodePointsUpTo(E.delta,j.MAKE_AI_CONVERSATION_LIMITS.messageCharacters-ze);if(ze+Re>j.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)throw new W("AI 助手响应文本超过大小限制");ze+=Re,qe.set(E.messageId,ue+Re)}if(E.type==="message.replace"){if(!Ze.has(E.messageId))throw new W("AI 助手响应事件顺序无效");const ue=qe.get(E.messageId)??0,Re=j.countCodePointsUpTo(E.content,j.MAKE_AI_CONVERSATION_LIMITS.messageCharacters),At=ze-ue+Re;if(At>j.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)throw new W("AI 助手响应文本超过大小限制");ze=At,qe.set(E.messageId,Re)}if(E.type==="run.progress"){if(ne!==void 0&&ne!==E.runId)throw new W("AI 助手响应 run id 不一致");if(ne??=E.runId,yt+=1,yt>j.MAKE_AI_CONVERSATION_LIMITS.progressStepsPerRun)throw new W("AI 助手处理过程数量超过限制");const ue=j.countCodePointsUpTo(E.message,j.MAKE_AI_CONVERSATION_LIMITS.progressCharactersPerRun-lt);if(lt+ue>j.MAKE_AI_CONVERSATION_LIMITS.progressCharactersPerRun)throw new W("AI 助手处理过程文本超过大小限制");lt+=ue}if(E.type==="artifact"){if(!Ze.has(E.messageId))throw new W("AI 助手响应事件顺序无效");if(_t+=1,_t>j.MAKE_AI_CONVERSATION_LIMITS.artifactsPerRun)throw new W("AI 助手单次响应 Artifact 数量超过限制");if(xt.has(E.artifact.id))throw new W("AI 助手响应包含重复的 Artifact id");xt.add(E.artifact.id)}if(E.type==="message.complete"&&!Ze.delete(E.messageId))throw new W("AI 助手响应事件顺序无效");if(E.type==="run.complete"&&ne!==void 0&&ne!==E.runId)throw new W("AI 助手响应 run id 不一致");if(E.type==="run.cancelled"&&E.runId!==void 0&&ne!==void 0&&ne!==E.runId)throw new W("AI 助手响应 run id 不一致");if(H(ue=>j.reduceAssistantEvent(ue,E)),E.type==="error"||E.type==="run.cancelled"||E.type==="run.complete"){ye=!0;break}}if(!ye)throw new W("AI 助手流式响应在终止事件前结束")}catch(ye){if(_e.current!==Te)return;if(nt.signal.aborted){H(ne=>j.reduceAssistantEvent(ne,{type:"run.cancelled"}));return}console.error("[make-ai-assistant] assistant run failed",{appId:a.app.id,errorType:ye instanceof Error?ye.name:typeof ye}),H(ne=>j.reduceAssistantEvent(ne,{type:"error",code:"TRANSPORT_ERROR",message:ye instanceof W?ye.message:"连接失败,请重试",retryable:!0}))}finally{_e.current===Te&&q.current===nt&&(q.current=void 0),oe.current?.requestVersion===Te&&(Tt(oe.current.iterator),oe.current=void 0)}},m=h=>{if(k.enabled){if(f.pending)return re("请等待附件上传完成,或移除失败的附件"),Promise.resolve();const K=h.trim(),V=f.parts.length?[...K?[{id:$e(),kind:"text",text:K}]:[],...f.parts]:void 0;return z(""),f.clear(),k.send(K,V)}return r(h)},g=h=>r(h.userMessage.content,{regenerateFrom:h}),y=async(h,K)=>{try{await Vs(K),le({messageId:h,message:"已复制",status:"success"})}catch(V){console.error("[make-ai-assistant] copy answer failed",{errorType:V instanceof Error?V.name:typeof V}),le({messageId:h,message:"复制失败",status:"error"})}},w=h=>{h.preventDefault(),m(I)},C=h=>{h.key==="Enter"&&!h.shiftKey&&!h.nativeEvent.isComposing&&(h.preventDefault(),m(I))},x=()=>{if(k.enabled){k.stop();return}Ee("stop")&&H(h=>j.reduceAssistantEvent(h,{type:"run.cancelled"}))},M=()=>{if(ce(!1),k.enabled){z(""),k.create(),u?.();return}Ee("new-conversation"),z(""),re(void 0),le(void 0),ie(!1),he.current=!0,H(j.createAssistantConversationState()),u?.()},N=k.enabled&&k.cancelling.length?"停止中":b.features?.remoteCancellation===!1?"停止接收":"停止生成",U=Gt(P),ve=Xt(P),Ne=sa(P),tt=typeof b.regenerate=="function"&&b.features?.regeneration!==!1,de=()=>{if(k.enabled){k.retry();return}Ne&&m(Ne.content)},Se=h=>{if(h.key==="Escape"&&!(!J&&!Z)){if(h.preventDefault(),h.stopPropagation(),J){ae(!1),Ce.current?.focus();return}ce(!1),Ke.current?.focus()}};return e.jsxs("section",{className:`make-ai-assistant make-ai-assistant__panel${k.enabled?" make-ai-assistant__panel--managed":""}`,ref:we,style:G,onKeyDown:Se,onDragOver:h=>{f.enabled&&h.dataTransfer.types.includes("Files")&&h.preventDefault()},onDrop:h=>{f.enabled&&h.dataTransfer.files.length&&(h.preventDefault(),f.add(Array.from(h.dataTransfer.files)))},children:[e.jsxs("header",{className:"make-ai-assistant__header",children:[e.jsx("div",{className:"make-ai-assistant__header-leading",children:k.enabled?e.jsxs("button",{"aria-controls":Ye,"aria-expanded":Z,"aria-haspopup":"dialog","aria-label":"任务列表",className:"make-ai-assistant__task-list-trigger",ref:Ke,type:"button",onClick:()=>ce(h=>!h),children:[e.jsx(bs,{"aria-hidden":"true",className:"make-ai-assistant__task-list-icon"}),e.jsx("span",{className:"make-ai-assistant__task-list-label",children:"任务列表"}),Z?e.jsx(ys,{"aria-hidden":"true",className:"make-ai-assistant__task-list-disclosure"}):e.jsx(gs,{"aria-hidden":"true",className:"make-ai-assistant__task-list-disclosure"})]}):null}),e.jsxs("div",{className:"make-ai-assistant__header-center",children:[e.jsx(ot,{}),e.jsx("h2",{className:"make-ai-assistant__header-title",title:n,children:n})]}),e.jsxs("div",{className:"make-ai-assistant__header-actions",children:[p?e.jsx("button",{"aria-label":v?"退出全屏":"全屏显示","aria-pressed":v,className:"make-ai-assistant__icon-button",title:v?"退出全屏":"全屏显示",type:"button",onClick:p,children:v?e.jsx(ps,{"aria-hidden":"true",className:"make-ai-assistant__icon-button-icon"}):e.jsx(_s,{"aria-hidden":"true",className:"make-ai-assistant__icon-button-icon"})}):null,b.features?.newConversation!==!1?e.jsx("button",{"aria-label":"新建对话",className:"make-ai-assistant__icon-button",type:"button",onClick:M,children:e.jsx(vt,{"aria-hidden":"true",className:"make-ai-assistant__icon-button-icon"})}):null,l?e.jsx("button",{"aria-label":`关闭 ${n}`,className:"make-ai-assistant__icon-button",type:"button",onClick:l,children:e.jsx(zs,{})}):null]})]}),k.enabled&&Z?e.jsx(Is,{id:Ye,manager:k,triggerRef:Ke,onDismiss:()=>ce(!1),onNewConversation:b.features?.newConversation!==!1?M:void 0}):null,e.jsxs("div",{className:"make-ai-assistant__body","aria-live":"polite","aria-relevant":"additions text",ref:be,role:"log",onScroll:Be,children:[Q==="loading"?e.jsxs("div",{className:"make-ai-assistant__empty",role:"status",children:[e.jsx(ot,{}),e.jsx("h3",{children:"正在恢复对话"}),e.jsx("p",{children:"正在读取当前 App 的历史消息…"})]}):Q==="error"?e.jsx("div",{className:"make-ai-assistant__empty",children:e.jsx(ra,{error:Ue,onRetry:()=>T(h=>h+1)})}):P.messages.length===0?e.jsxs("div",{className:"make-ai-assistant__empty",children:[e.jsx(ot,{}),e.jsx("h3",{children:"有什么可以帮你?"}),e.jsx("p",{children:"我会结合当前 App、页面位置和宿主允许的上下文回答,并把过程与结果分开展示。"})]}):oa(P,a,Qe,F,o,i,t,Ne?de:void 0,L,B,pe,tt,(h,K)=>{y(h,K)},h=>{g(h)},k.enabled?k:void 0,b),P.progress&&!U?e.jsx(Ot,{assistantName:t,progress:P.progress}):null,P.error&&!ve?e.jsx(Ot,{assistantName:t,error:P.error,onRetry:Ne?de:void 0}):null]}),Ge?e.jsx("button",{"aria-label":"回到最新消息",className:"make-ai-assistant__back-to-latest",type:"button",onClick:Ae,children:e.jsx(Zs,{})}):null,e.jsxs("footer",{className:"make-ai-assistant__composer-region",children:[Q==="ready"&&et.length>0&&P.messages.length===0?e.jsx("div",{className:"make-ai-assistant__suggestions","aria-label":"推荐问题",children:et.map((h,K)=>e.jsx("button",{type:"button",onClick:()=>{m(h)},children:h},`${K}-${h}`))}):null,e.jsxs("form",{className:"make-ai-assistant__composer",onSubmit:w,children:[f.enabled?e.jsx(Rs,{attachments:f,visible:D}):null,e.jsx("textarea",{"aria-label":`向 ${t} 提问`,"aria-describedby":X?"make-ai-composer-error":void 0,"aria-invalid":X?!0:void 0,autoFocus:!0,disabled:Q!=="ready"||!k.enabled&&P.status==="streaming",placeholder:`询问当前 ${a.app.name??"App"} 中的数据…`,ref:Me,rows:2,value:I,onChange:h=>{z(h.currentTarget.value),re(void 0)},onKeyDown:C,onPaste:h=>{!f.enabled||!h.clipboardData.files.length||(h.preventDefault(),f.add(Array.from(h.clipboardData.files)))}}),e.jsxs("div",{className:"make-ai-assistant__composer-toolbar",children:[f.enabled?e.jsx(Ts,{attachments:f,open:J,triggerRef:Ce,onOpenChange:ae}):null,e.jsxs("div",{className:"make-ai-assistant__composer-actions",children:[P.status==="streaming"?e.jsx("button",{"aria-label":N,className:"make-ai-assistant__send make-ai-assistant__send--stop","data-tooltip":N,ref:He,disabled:k.enabled&&k.cancelling.includes(P.activeRunId??""),type:"button",onClick:x,children:e.jsx("span",{"aria-hidden":"true"})}):e.jsx("button",{"aria-label":"发送",className:"make-ai-assistant__send",disabled:Q!=="ready"||f.pending||!I.trim()&&!f.parts.length,type:"submit",children:e.jsx(Rt,{})}),k.enabled&&P.status==="streaming"?e.jsx("button",{"aria-label":"发送",className:"make-ai-assistant__send",disabled:k.busy||f.pending||!I.trim()&&!f.parts.length,type:"submit",children:e.jsx(Rt,{})}):null]})]})]}),X?e.jsx("p",{id:"make-ai-composer-error",role:"alert",children:X}):null,e.jsx("p",{children:"AI 生成的结果可能存在偏差,重要数据请核对明细。"})]})]})}function ca(t){return e.jsx(Qt,{...t,visible:!0})}function la({defaultOpen:t=!1,hideLauncher:s=!1,launcher:a,launcherPosition:o="bottom-right",maxDrawerWidth:i,onOpenChange:l,open:u,...p}){const d=zt(p.brandName,p.title),[v,S]=c.useState(t),[R,O]=c.useState(()=>t||u===!0),[F,b]=c.useState(!1),B=c.useRef(null),L=u??v,D=pt(p.theme),k=Ds(i),f=k===void 0?void 0:{"--make-ai-internal-drawer-max-width":`${k}px`},n=A=>{u===void 0&&S(A),l?.(A),A||(b(!1),requestAnimationFrame(()=>B.current?.focus()))},_=()=>n(!L);return c.useEffect(()=>{L&&O(!0)},[L]),c.useEffect(()=>{if(!L)return;const A=G=>{if(G.key==="Escape"){if(F){b(!1);return}n(!1),requestAnimationFrame(()=>B.current?.focus())}};return document.addEventListener("keydown",A),()=>document.removeEventListener("keydown",A)},[F,l,L]),e.jsxs("div",{className:"make-ai-assistant","data-open":L||void 0,style:D,children:[!s&&(!L||a)?a?a({open:L,toggle:_}):e.jsxs("button",{"aria-label":L?`关闭 ${d}`:`打开 ${d}`,"aria-expanded":L,className:"make-ai-assistant__launcher","data-launcher-position":o,ref:B,type:"button",onClick:_,children:[e.jsx("span",{className:"make-ai-assistant__launcher-orbit","aria-hidden":"true"}),e.jsx(qt,{})]}):null,R?e.jsx("aside",{"aria-label":d,"aria-modal":"false",className:`make-ai-assistant__drawer${F?" make-ai-assistant__drawer--fullscreen":""}`,hidden:!L,role:"dialog",style:f,children:e.jsx(Qt,{...p,isFullscreen:F,onClose:()=>n(!1),onToggleFullscreen:()=>b(A=>!A),visible:L})}):null]})}exports.createArtifactCapabilities=ke.createArtifactCapabilities;exports.createArtifactTemplateRegistry=ke.createArtifactTemplateRegistry;exports.extendArtifactTemplateRegistry=ke.extendArtifactTemplateRegistry;exports.resolveArtifactTemplate=ke.resolveArtifactTemplate;exports.MAKE_AI_ARTIFACT_KINDS=j.MAKE_AI_ARTIFACT_KINDS;exports.MAKE_AI_ARTIFACT_LIMITS=j.MAKE_AI_ARTIFACT_LIMITS;exports.MAKE_AI_ARTIFACT_SCHEMA_VERSION=j.MAKE_AI_ARTIFACT_SCHEMA_VERSION;exports.MAKE_AI_CONVERSATION_LIMITS=j.MAKE_AI_CONVERSATION_LIMITS;exports.appendUserMessage=j.appendUserMessage;exports.createAssistantConversationState=j.createAssistantConversationState;exports.parseArtifact=j.parseArtifact;exports.parseAssistantEvent=j.parseAssistantEvent;exports.reduceAssistantEvent=j.reduceAssistantEvent;exports.validateArtifact=j.validateArtifact;exports.ArtifactRenderer=Ut;exports.AssistantPanel=ca;exports.MakeAiAssistant=la;exports.createPlatformArtifactRegistry=Bt;exports.formatArtifactValue=xe;exports.platformArtifactTemplates=Ht;