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