@amaster.ai/copilot-client 1.1.0-beta.4 → 1.1.0-beta.41

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/dist/index.cjs CHANGED
@@ -1,3 +1,3 @@
1
- 'use strict';var httpClient=require('@amaster.ai/http-client'),eventsourceParser=require('eventsource-parser');var a=globalThis;function N(){return typeof a?.Taro?.request=="function"?a.Taro.request.bind(a.Taro):typeof a?.wx?.request=="function"?a.wx.request.bind(a.wx):typeof a?.tt?.request=="function"?a.tt.request.bind(a.tt):typeof a?.my?.request=="function"?a.my.request.bind(a.my):typeof a?.swan?.request=="function"?a.swan.request.bind(a.swan):typeof a?.qq?.request=="function"?a.qq.request.bind(a.qq):typeof a?.jd?.request=="function"?a.jd.request.bind(a.jd):null}function m(){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?e.randomUUID():e&&typeof e.getRandomValues=="function"?"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let n=(e.getRandomValues(new Uint8Array(1))[0]??0)%16;return (t==="x"?n:n&3|8).toString(16)}):"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let o=Math.random()*16|0;return (t==="x"?o:o&3|8).toString(16)})}function b(){if(typeof window>"u")return null;try{let e=window.location.href,t=/\/app\/([\da-f-]+)(?:\/|$)/.exec(e);if(t?.[1])return t[1];let o=window.location.hostname,n=/^www\.([\da-f-]+)(?:-[^.]+)?\.[\w-]+\.(?:local|ai|cn)$/.exec(o);if(n?.[1])return n[1];let r=/^([\da-f-]+)(?:-[^.]+)?\.[\w-]+\.(?:local|ai|cn)$/.exec(o);return r?.[1]?r[1]:null}catch{return null}}var C=null;function M(){let e=b();return e||(C||(C=m()),C)}async function v(e,t){let o=N();if(o)return new Promise(s=>{let i="",c=false,u=false,g=0,y={url:e,method:"POST",header:{"Content-Type":"application/json",Accept:"text/event-stream"},data:t,timeout:6e4,success:l=>{i=typeof l.data=="string"?l.data:JSON.stringify(l.data),c=true;},fail:()=>{u=true,c=true;}};try{let l=o(y);l&&typeof l.then=="function"&&l.then(d=>{i=typeof d.data=="string"?d.data:JSON.stringify(d.data),c=!0;}).catch(()=>{u=!0,c=!0;});}catch{u=true,c=true;}s({ok:true,statusText:"OK",read:async()=>{for(;!c&&g>=i.length;)await new Promise(d=>setTimeout(d,50));if(u)return null;if(g>=i.length)return c?null:"";let l=i.slice(g);return g=i.length,l}});});let n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(t)});if(!n.body)return {ok:n.ok,statusText:n.statusText,read:async()=>null};let r=n.body.getReader(),p=new TextDecoder;return {ok:n.ok,statusText:n.statusText,read:async()=>{let{done:s,value:i}=await r.read();return s?null:p.decode(i,{stream:true})}}}function R(e){return typeof e=="string"?[{kind:"text",text:e}]:e.map(t=>{switch(t.type){case "text":return {kind:"text",text:t.text};case "image":return t.data?{kind:"file",file:{bytes:t.data,mimeType:t.mimeType||"image/png"}}:t.url?{kind:"file",file:{uri:t.url,mimeType:t.mimeType||"image/png"}}:null;case "file":return t.data?{kind:"file",file:{bytes:t.data,...t.mimeType&&{mimeType:t.mimeType},...t.name&&{name:t.name}}}:t.url?{kind:"file",file:{uri:t.url,...t.mimeType&&{mimeType:t.mimeType},...t.name&&{name:t.name}}}:null;default:return null}}).filter(t=>t!==null)}function A(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join(`
2
- `)}var I="application/json+a2ui",k="main",w=0;function f(e){return `${e}-${++w}`}function h(e,t){let o=f("text");return {surfaceUpdate:{surfaceId:t,components:[{id:o,component:{Text:{text:{literalString:e},usageHint:"body"}}}]}}}function D(e,t){let o=e.mimeType||"";if(!o.startsWith("image/"))return null;let n=f("image"),r=e.uri||(e.bytes?`data:${o};base64,${e.bytes}`:null);return r?{surfaceUpdate:{surfaceId:t,components:[{id:n,component:{Image:{url:{literalString:r}}}}]}}:null}function P(e,t){if(!e.subject&&!e.description)return null;let o=f("thought"),n=[];n.push({id:o,component:{Card:{child:`${o}-content`}}});let r=[];return e.subject&&r.push(`${o}-subject`),e.description&&r.push(`${o}-desc`),n.push({id:`${o}-content`,component:{Column:{children:{explicitList:r}}}}),e.subject&&n.push({id:`${o}-subject`,component:{Text:{text:{literalString:`\u{1F4AD} ${e.subject}`},usageHint:"h4"}}}),e.description&&n.push({id:`${o}-desc`,component:{Text:{text:{literalString:e.description},usageHint:"caption"}}}),{surfaceUpdate:{surfaceId:t,components:n}}}function V(e){switch(e){case "success":case "completed":return {icon:"check_circle",text:"\u2713 Completed"};case "failed":case "error":return {icon:"error",text:"\u2717 Failed"};case "validating":return {icon:"rule",text:"\u{1F50D} Validating..."};case "scheduled":return {icon:"schedule",text:"\u{1F4CB} Scheduled..."};case "executing":return {icon:"play_circle",text:"\u25B6\uFE0F Executing..."};case "pending":return {icon:"hourglass_empty",text:"\u23F3 Pending..."};default:return {icon:"build",text:"\u2699\uFE0F Running..."}}}function q(e,t){let o=e.tool?.displayName||e.tool?.name||e.request?.name||"Tool",n=e.status||"running",{icon:r,text:p}=V(n),s=f("tool"),i=[];i.push({id:s,component:{Card:{child:`${s}-row`}}}),i.push({id:`${s}-row`,component:{Row:{alignment:"center",children:{explicitList:[`${s}-icon`,`${s}-info`]}}}}),i.push({id:`${s}-icon`,component:{Icon:{name:{literalString:r}}}});let c=[`${s}-name`,`${s}-status`];if(e.resultDisplay&&(n==="success"||n==="completed")&&c.push(`${s}-result`),i.push({id:`${s}-info`,component:{Column:{children:{explicitList:c}}}}),i.push({id:`${s}-name`,component:{Text:{text:{literalString:o},usageHint:"body"}}}),i.push({id:`${s}-status`,component:{Text:{text:{literalString:p},usageHint:"caption"}}}),e.resultDisplay&&(n==="success"||n==="completed")){let u=e.resultDisplay.length>200?e.resultDisplay.slice(0,200)+"...":e.resultDisplay;i.push({id:`${s}-result`,component:{Text:{text:{literalString:u},usageHint:"caption"}}});}return {surfaceUpdate:{surfaceId:t,components:i}}}var x={THOUGHT:"thought",TOOL_CALL_UPDATE:"tool-call-update",TOOL_CALL_CONFIRMATION:"tool-call-confirmation",STATE_CHANGE:"state-change"};function U(e,t,o=k){let n=[];for(let r of e)if(r.kind==="text")n.push(h(r.text,o));else if(r.kind==="file"&&"file"in r){let p=r.file,s=D(p,o);s&&n.push(s);}else if(r.kind==="data"){let p=r.data;if(r.metadata?.mimeType===I)n.push(p);else if(t===x.THOUGHT){let s=p;if(s.subject){let i=P(s,o);i&&n.push(i);}else s.description&&n.push(h(s.description,o));}else if(t===x.TOOL_CALL_UPDATE||t===x.TOOL_CALL_CONFIRMATION){let s=q(p,o);s&&n.push(s);}}return n}function B(e){if("error"in e)return [];let t=e.result;if(!t||!("kind"in t)||t.kind!=="status-update")return [];let n=t.metadata?.coderAgent?.kind;if(n===x.STATE_CHANGE)return [];let r=t.status?.message?.parts;return !r||r.length===0?[]:U(r,n)}async function*O(e){let t=[],o=eventsourceParser.createParser({onEvent:n=>{try{t.push(JSON.parse(n.data));}catch{}}});try{for(;;){let n=await e.read();if(n===null)break;if(n)for(o.feed(n);t.length>0;){let r=t.shift();r&&(yield r);}}}catch{}}function j(e=httpClient.createHttpClient()){let t="/api/proxy/builtin/platform/copilot";async function*o(n){try{let r=await v(t,n);if(!r.ok)throw new Error(`Stream request failed: ${r.statusText}`);yield*O(r);}catch{}}return {async*chat(n,r={}){let{taskId:p}=r,s=n.find(l=>l.role==="system"),i=n.filter(l=>l.role!=="system"),c=i[i.length-1],u=c?R(c.content):[{kind:"text",text:""}],g=s?A(s.content):void 0,y={jsonrpc:"2.0",id:m(),method:"message/stream",params:{message:{contextId:M(),kind:"message",messageId:m(),role:"user",parts:u,...p&&{taskId:p},...g&&{metadata:{systemPrompt:g}}}}};for await(let l of o(y)){let d=B(l);d.length>0&&(yield d);}},cancelChat(n){let r={jsonrpc:"2.0",id:m(),method:"tasks/cancel",params:{id:n}};return e.request({url:t,method:"POST",data:r})},getChatStatus(n){let r={jsonrpc:"2.0",id:m(),method:"tasks/get",params:{id:n}};return e.request({url:t,method:"POST",data:r})}}}var $={};exports.A2UITypes=$;exports.createCopilotA2UIClient=j;//# sourceMappingURL=index.cjs.map
1
+ 'use strict';var httpClient=require('@amaster.ai/http-client'),eventsourceParser=require('eventsource-parser'),k=require('miniprogram-text-decoder'),I=require('miniprogram-text-encoder');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var k__default=/*#__PURE__*/_interopDefault(k);var I__default=/*#__PURE__*/_interopDefault(I);var l=globalThis;function P(){return typeof l?.Taro?.request=="function"?l.Taro.request.bind(l.Taro):typeof l?.wx?.request=="function"?l.wx.request.bind(l.wx):typeof l?.tt?.request=="function"?l.tt.request.bind(l.tt):typeof l?.my?.request=="function"?l.my.request.bind(l.my):typeof l?.swan?.request=="function"?l.swan.request.bind(l.swan):typeof l?.qq?.request=="function"?l.qq.request.bind(l.qq):typeof l?.jd?.request=="function"?l.jd.request.bind(l.jd):null}function T(){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?e.randomUUID():e&&typeof e.getRandomValues=="function"?"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let n=(e.getRandomValues(new Uint8Array(1))[0]??0)%16;return (t==="x"?n:n&3|8).toString(16)}):"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let o=Math.random()*16|0;return (t==="x"?o:o&3|8).toString(16)})}function D(){if(typeof window>"u")return null;try{let e=window.location.href,t=/\/app\/([\da-f-]+)(?:\/|$)/.exec(e);if(t?.[1])return t[1];let o=window.location.hostname,n=/^www\.([\da-f-]+)(?:-[^.]+)?\.[\w-]+\.(?:local|ai|cn)$/.exec(o);if(n?.[1])return n[1];let r=/^([\da-f-]+)(?:-[^.]+)?\.[\w-]+\.(?:local|ai|cn)$/.exec(o);return r?.[1]?r[1]:null}catch{return null}}var R=null;function U(){let e=D();return e||(R||(R=T()),R)}async function q(e,t,o={}){return new Promise(n=>{let r=new Uint8Array(0),u=new k__default.default("utf-8",{fatal:false}),s=false,i=false,c=[],d=null,y=()=>new Promise(p=>{c.length>0?p(c.shift()):s?p(null):d=p;}),g=p=>{p&&(c.push(p),d&&(d(c.shift()),d=null));},m=p=>{if(!(i||s||!p.data))try{let a=new Uint8Array(p.data),f=new Uint8Array(r.length+a.length);f.set(r),f.set(a,r.length),r=f;let C=0;for(;C<r.length;){let v=r.subarray(C),b=u.decode(v,{stream:!1});if(b)g(b),C+=new I__default.default().encode(b).length;else break}C<r.length?r=r.subarray(C):r=new Uint8Array(0);}catch(a){console.error("[mini stream] chunk process error:",a);}},h=p=>{p.header?.["content-type"]?.includes("text/event-stream")===false&&console.warn("Warning: server did not return event-stream");},x=l.wx.request.bind(l.wx);try{let p=x({url:e,method:"POST",header:{"Content-Type":"application/json",Accept:"text/event-stream",...o},data:typeof t=="string"?t:JSON.stringify(t),responseType:"arraybuffer",enableChunked:!0,timeout:3e5,success:()=>{if(r.length>0){let a=u.decode(r,{stream:!0});g(a);}s=!0,d&&d(null);},fail:a=>{console.error("[mini stream] request fail:",a),i=!0,s=!0,d&&d(null);}});p.onChunkReceived?.(m),p.onHeadersReceived?.(h),n({ok:!0,statusText:"OK",read:async()=>i?null:y()});}catch(p){console.error("miniReq error",p);}})}async function B(e,t,o){let n=o?.(),r=n?{Authorization:`Bearer ${n}`}:{};if(typeof l?.wx?.request=="function")return q(e,t,r);let u=P();if(u)return new Promise(y=>{let g="",m=false,h=false,x=0,p={url:e,method:"POST",header:{"Content-Type":"application/json",Accept:"text/event-stream",...r},data:typeof t=="string"?t:JSON.stringify(t),timeout:6e4,success:a=>{g=typeof a.data=="string"?a.data:JSON.stringify(a.data),m=true;},fail:a=>{console.error("[createStream] wx.request failed:",a),h=true,m=true;},complete:()=>{}};try{let a=u(p);a&&typeof a.then=="function"&&a.then(f=>{g=typeof f.data=="string"?f.data:JSON.stringify(f.data),m=!0;}).catch(()=>{h=!0,m=!0;});}catch(a){console.error("[createStream] Exception:",a),h=true,m=true;}y({ok:true,statusText:"OK",read:async()=>{for(;!m&&x>=g.length;)await new Promise(f=>setTimeout(f,50));if(h)return null;if(x>=g.length)return m?null:"";let a=g.slice(x);return x=g.length,a}});});let s={"Content-Type":"application/json",...r},i=await fetch(e,{method:"POST",headers:s,credentials:"include",body:JSON.stringify(t)});if(!i.body)return {ok:i.ok,statusText:i.statusText,read:async()=>null};let c=i.body.getReader(),d=new TextDecoder;return {ok:i.ok,statusText:i.statusText,read:async()=>{let{done:y,value:g}=await c.read();return y?null:d.decode(g,{stream:true})}}}function V(e){return typeof e=="string"?[{kind:"text",text:e}]:e.map(t=>{switch(t.type){case "text":return {kind:"text",text:t.text};case "image":return t.data?{kind:"file",file:{bytes:t.data,mimeType:t.mimeType||"image/png"}}:t.url?{kind:"file",file:{uri:t.url,mimeType:t.mimeType||"image/png"}}:null;case "file":return t.data?{kind:"file",file:{bytes:t.data,...t.mimeType&&{mimeType:t.mimeType},...t.name&&{name:t.name}}}:t.url?{kind:"file",file:{uri:t.url,...t.mimeType&&{mimeType:t.mimeType},...t.name&&{name:t.name}}}:null;default:return null}}).filter(t=>t!==null)}function O(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join(`
2
+ `)}var _="application/json+a2ui",E="main",L=0;function N(e){return `${e}-${++L}`}function A(e,t){let o=N("text");return {surfaceUpdate:{surfaceId:t,components:[{id:o,component:{Text:{text:{literalString:e},usageHint:"body"}}}]}}}function $(e,t){let o=e.mimeType||"";if(!o.startsWith("image/"))return null;let n=N("image"),r=e.uri||(e.bytes?`data:${o};base64,${e.bytes}`:null);return r?{surfaceUpdate:{surfaceId:t,components:[{id:n,component:{Image:{url:{literalString:r}}}}]}}:null}function j(e,t){if(!e.subject&&!e.description)return null;let o=N("thought"),n=[];n.push({id:o,component:{Card:{child:`${o}-content`}}});let r=[];return e.subject&&r.push(`${o}-subject`),e.description&&r.push(`${o}-desc`),n.push({id:`${o}-content`,component:{Column:{children:{explicitList:r}}}}),e.subject&&n.push({id:`${o}-subject`,component:{Text:{text:{literalString:`\u{1F4AD} ${e.subject}`},usageHint:"h4"}}}),e.description&&n.push({id:`${o}-desc`,component:{Text:{text:{literalString:e.description},usageHint:"caption"}}}),{surfaceUpdate:{surfaceId:t,components:n}}}function F(e){switch(e){case "success":case "completed":return {icon:"check_circle",text:"\u2713 Completed",status:e};case "failed":case "error":return {icon:"error",text:"\u2717 Failed",status:e};case "validating":return {icon:"rule",text:"\u{1F50D} Validating...",status:e};case "scheduled":return {icon:"schedule",text:"\u{1F4CB} Scheduled...",status:e};case "executing":return {icon:"play_circle",text:"\u25B6\uFE0F Executing...",status:e};case "pending":return {icon:"hourglass_empty",text:"\u23F3 Pending...",status:e};default:return {icon:"build",text:"\u2699\uFE0F Running...",status:e}}}function H(e,t){let o=e.tool?.displayName||e.tool?.name||e.request?.name||"Tool",n=e.status||"running",{icon:r,text:u}=F(n),s=N("tool"),i=[];i.push({id:s,component:{Card:{child:`${s}-row`}}}),i.push({id:`${s}-row`,component:{Row:{alignment:"center",children:{explicitList:[`${s}-icon`,`${s}-info`]}}}}),i.push({id:`${s}-icon`,component:{Icon:{name:{literalString:r}}}});let c=[`${s}-name`,`${s}-status`];if(e.resultDisplay&&(n==="success"||n==="completed")&&c.push(`${s}-result`),i.push({id:`${s}-info`,component:{Column:{children:{explicitList:c}}}}),i.push({id:`${s}-name`,component:{Text:{text:{literalString:o},usageHint:"body"}}}),i.push({id:`${s}-status`,component:{Text:{text:{literalString:u},usageHint:"caption"}}}),e.resultDisplay&&(n==="success"||n==="completed")){let d=e.resultDisplay.length>200?e.resultDisplay.slice(0,200)+"...":e.resultDisplay;i.push({id:`${s}-result`,component:{Text:{text:{literalString:d},usageHint:"caption"}}});}return {surfaceUpdate:{surfaceId:t,components:i}}}var S={THOUGHT:"thought",TOOL_CALL_UPDATE:"tool-call-update",TOOL_CALL_CONFIRMATION:"tool-call-confirmation",STATE_CHANGE:"state-change"};function G(e,t,o=E){let n=[];for(let r of e)if(r.kind==="text")n.push(A(r.text,o));else if(r.kind==="file"&&"file"in r){let u=r.file,s=$(u,o);s&&n.push(s);}else if(r.kind==="data"){let u=r.data;if(r.metadata?.mimeType===_)n.push(u);else if(t===S.THOUGHT){let s=u;if(s.subject){let i=j(s,o);i&&n.push(i);}else s.description&&n.push(A(s.description,o));}else if(t===S.TOOL_CALL_UPDATE||t===S.TOOL_CALL_CONFIRMATION){let s=H(u,o);s&&n.push(s);}}return n}function J(e){if("error"in e)return [];let t=e.result;if(!t||!("kind"in t)||t.kind!=="status-update")return [];let n=t.metadata?.coderAgent?.kind;if(n===S.STATE_CHANGE)return [];let r=t.status?.message?.parts;return !r||r.length===0?[]:G(r,n)}async function*z(e){let t=[],o=eventsourceParser.createParser({onEvent:n=>{try{t.push(JSON.parse(n.data));}catch(r){console.error("[parseSSEStream] Parse error:",r);}}});try{for(;;){let n=await e.read();if(n===null)break;if(n)for(o.feed(n);t.length>0;){let r=t.shift();r&&(yield r);}}}catch(n){console.error("[parseSSEStream] Stream error:",n);}}function W(e=httpClient.createHttpClient(),t,o){let n="",r=undefined;if(r&&(n=r.TARO_APP_API_BASE_URL||r.VITE_API_BASE_URL||""),!n)try{n=process.env.TARO_APP_API_BASE_URL||process.env.VITE_API_BASE_URL||"";}catch{}n=String(n||"").trim();let u=`${t||n}/api/proxy/builtin/platform/copilot`;async function*s(i){try{let c=await B(u,i,o);if(!c.ok)throw new Error(`Stream request failed: ${c.statusText}`);yield*z(c);}catch(c){console.error("[sendMessageStream] Error:",c);}}return {async*chat(i,c={}){let{taskId:d}=c,y=i.find(a=>a.role==="system"),g=i.filter(a=>a.role!=="system"),m=g[g.length-1],h=m?V(m.content):[{kind:"text",text:""}],x=y?O(y.content):void 0,p={jsonrpc:"2.0",id:T(),method:"message/stream",params:{message:{contextId:U(),kind:"message",messageId:T(),role:"user",parts:h,...d&&{taskId:d},...x&&{metadata:{systemPrompt:x}}}}};for await(let a of s(p)){let f=J(a);f.length>0&&(yield f);}},cancelChat(i){let c={jsonrpc:"2.0",id:T(),method:"tasks/cancel",params:{id:i}};return e.request({url:u,method:"POST",data:c})},getChatStatus(i){let c={jsonrpc:"2.0",id:T(),method:"tasks/get",params:{id:i}};return e.request({url:u,method:"POST",data:c})}}}var K={};exports.A2UITypes=K;exports.createCopilotA2UIClient=W;//# sourceMappingURL=index.cjs.map
3
3
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/copilot-a2ui-client.ts","../src/a2ui-types.ts"],"names":["g","getMiniProgramRequest","generateUUID","cryptoObj","c","r","extractAppIdFromUrl","url","pathMatch","hostname","wwwMatch","domainMatch","cachedAppId","getAppId","urlAppId","createStream","data","miniReq","resolve","buffer","completed","failed","position","opts","res","ret","chunk","response","reader","decoder","done","value","convertToA2AParts","content","part","extractTextFromContent","A2UI_MIME_TYPE","DEFAULT_SURFACE_ID","componentIdCounter","generateComponentId","prefix","textPartToA2UI","text","surfaceId","componentId","filePartToA2UI","file","mimeType","thoughtToA2UI","thought","baseId","components","childrenList","getToolStatusDisplay","status","toolCallToA2UI","toolCall","toolName","iconName","statusText","infoChildren","resultPreview","CODER_AGENT_EVENT","convertA2APartsToA2UI","parts","coderAgentKind","messages","a2uiMsg","convertResponseToA2UI","result","parseSSEStream","streamResponse","queue","parser","createParser","event","item","createCopilotA2UIClient","http","createHttpClient","baseUrl","sendMessageStream","request","chatOptions","taskId","systemMsg","m","nonSystemMsgs","lastUserMsg","systemPrompt","a2uiMessages","a2ui_types_exports"],"mappings":"+GAoBA,IAAMA,CAAAA,CAAI,UAAA,CAEV,SAASC,CAAAA,EAAsD,CAC7D,OAAI,OAAOD,CAAAA,EAAG,MAAM,OAAA,EAAY,UAAA,CAAmBA,CAAAA,CAAE,IAAA,CAAK,QAAQ,IAAA,CAAKA,CAAAA,CAAE,IAAI,CAAA,CACzE,OAAOA,CA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{\n CancelTaskRequest,\n CancelTaskResponse,\n GetTaskRequest,\n GetTaskResponse,\n Part,\n SendStreamingMessageRequest,\n SendStreamingMessageResponse,\n} from \"@a2a-js/sdk\";\nimport { type ClientResult, createHttpClient, type HttpClient } from \"@amaster.ai/http-client\";\nimport { createParser } from \"eventsource-parser\";\nimport type { ServerToClientMessage, Surface, MessageProcessor } from \"./a2ui-types.js\";\n\n// Re-export A2UI types from local definitions\nexport type { ServerToClientMessage, Surface, MessageProcessor };\n\n// ============ Internal: Platform Detection (same as http-client) ============\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst g = globalThis as any;\n\nfunction getMiniProgramRequest(): ((_opts: any) => any) | null {\n if (typeof g?.Taro?.request === \"function\") return g.Taro.request.bind(g.Taro);\n if (typeof g?.wx?.request === \"function\") return g.wx.request.bind(g.wx);\n if (typeof g?.tt?.request === \"function\") return g.tt.request.bind(g.tt);\n if (typeof g?.my?.request === \"function\") return g.my.request.bind(g.my);\n if (typeof g?.swan?.request === \"function\") return g.swan.request.bind(g.swan);\n if (typeof g?.qq?.request === \"function\") return g.qq.request.bind(g.qq);\n if (typeof g?.jd?.request === \"function\") return g.jd.request.bind(g.jd);\n return null;\n}\n\n// ============ Internal: UUID Generator ============\n\nfunction generateUUID(): string {\n const cryptoObj = typeof globalThis !== \"undefined\" ? globalThis.crypto : undefined;\n\n if (cryptoObj && typeof cryptoObj.randomUUID === \"function\") {\n return cryptoObj.randomUUID();\n }\n\n if (cryptoObj && typeof cryptoObj.getRandomValues === \"function\") {\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n const randomValues = cryptoObj.getRandomValues(new Uint8Array(1));\n const r = (randomValues[0] ?? 0) % 16;\n const v = c === \"x\" ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n }\n\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === \"x\" ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n// ============ Internal: URL Utilities ============\n\nfunction extractAppIdFromUrl(): string | null {\n if (typeof window === \"undefined\") return null;\n\n try {\n const url = window.location.href;\n const pathMatch = /\\/app\\/([\\da-f-]+)(?:\\/|$)/.exec(url);\n if (pathMatch?.[1]) return pathMatch[1];\n\n const hostname = window.location.hostname;\n\n // Pattern 1: www.{app_id}.domain.tld or www.{app_id}-{env}.domain.tld\n const wwwMatch = /^www\\.([\\da-f-]+)(?:-[^.]+)?\\.[\\w-]+\\.(?:local|ai|cn)$/.exec(hostname);\n if (wwwMatch?.[1]) return wwwMatch[1];\n\n // Pattern 2: {app_id}-{env}.domain.tld or {app_id}.domain.tld\n const domainMatch = /^([\\da-f-]+)(?:-[^.]+)?\\.[\\w-]+\\.(?:local|ai|cn)$/.exec(hostname);\n if (domainMatch?.[1]) return domainMatch[1];\n\n return null;\n } catch {\n return null;\n }\n}\n\n// Cache appId for session consistency\nlet cachedAppId: string | null = null;\n\nfunction getAppId(): string {\n const urlAppId = extractAppIdFromUrl();\n if (urlAppId) return urlAppId;\n if (!cachedAppId) cachedAppId = generateUUID();\n return cachedAppId;\n}\n\n// ============ Internal: Streaming ============\n\ninterface StreamResponse {\n ok: boolean;\n statusText: string;\n read(): Promise<string | null>;\n}\n\nasync function createStream(url: string, data: unknown): Promise<StreamResponse> {\n const miniReq = getMiniProgramRequest();\n\n if (miniReq) {\n // Mini-program: buffer full response\n return new Promise((resolve) => {\n let buffer = \"\";\n let completed = false;\n let failed = false;\n let position = 0;\n\n const opts = {\n url,\n method: \"POST\",\n header: { \"Content-Type\": \"application/json\", Accept: \"text/event-stream\" },\n data,\n timeout: 60000,\n success: (res: any) => {\n buffer = typeof res.data === \"string\" ? res.data : JSON.stringify(res.data);\n completed = true;\n },\n fail: () => {\n failed = true;\n completed = true;\n },\n };\n\n try {\n const ret = miniReq(opts);\n if (ret && typeof ret.then === \"function\") {\n ret\n .then((res: any) => {\n buffer = typeof res.data === \"string\" ? res.data : JSON.stringify(res.data);\n completed = true;\n })\n .catch(() => {\n failed = true;\n completed = true;\n });\n }\n } catch {\n failed = true;\n completed = true;\n }\n\n resolve({\n ok: true,\n statusText: \"OK\",\n read: async () => {\n while (!completed && position >= buffer.length) {\n await new Promise((r) => setTimeout(r, 50));\n }\n if (failed) return null;\n if (position >= buffer.length) return completed ? null : \"\";\n const chunk = buffer.slice(position);\n position = buffer.length;\n return chunk;\n },\n });\n });\n }\n\n // Browser: use fetch streaming\n const response = await fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n credentials: \"include\",\n body: JSON.stringify(data),\n });\n\n if (!response.body) {\n return { ok: response.ok, statusText: response.statusText, read: async () => null };\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n\n return {\n ok: response.ok,\n statusText: response.statusText,\n read: async () => {\n const { done, value } = await reader.read();\n if (done) return null;\n return decoder.decode(value, { stream: true });\n },\n };\n}\n\n// ============ Input Types ============\n\nexport interface TextContent {\n type: \"text\";\n text: string;\n}\n\nexport interface ImageContent {\n type: \"image\";\n data?: string;\n url?: string;\n mimeType?: string;\n}\n\nexport interface FileContent {\n type: \"file\";\n data?: string;\n url?: string;\n mimeType?: string;\n name?: string;\n}\n\nexport type MessageContent = TextContent | ImageContent | FileContent;\n\nexport interface ChatMessage {\n role: \"system\" | \"user\" | \"assistant\";\n content: string | MessageContent[];\n}\n\nexport interface ChatOptions {\n taskId?: string;\n}\n\n// ============ Convert Input to A2A Part ============\n\nfunction convertToA2AParts(content: string | MessageContent[]): Part[] {\n if (typeof content === \"string\") {\n return [{ kind: \"text\", text: content }];\n }\n\n return content\n .map((part): Part | null => {\n switch (part.type) {\n case \"text\":\n return { kind: \"text\", text: part.text };\n case \"image\":\n if (part.data) {\n return {\n kind: \"file\",\n file: { bytes: part.data, mimeType: part.mimeType || \"image/png\" },\n };\n }\n if (part.url) {\n return {\n kind: \"file\",\n file: { uri: part.url, mimeType: part.mimeType || \"image/png\" },\n };\n }\n return null;\n case \"file\":\n if (part.data) {\n return {\n kind: \"file\",\n file: {\n bytes: part.data,\n ...(part.mimeType && { mimeType: part.mimeType }),\n ...(part.name && { name: part.name }),\n },\n };\n }\n if (part.url) {\n return {\n kind: \"file\",\n file: {\n uri: part.url,\n ...(part.mimeType && { mimeType: part.mimeType }),\n ...(part.name && { name: part.name }),\n },\n };\n }\n return null;\n default:\n return null;\n }\n })\n .filter((part): part is Part => part !== null);\n}\n\nfunction extractTextFromContent(content: string | MessageContent[]): string {\n if (typeof content === \"string\") {\n return content;\n }\n return content\n .filter((part): part is TextContent => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\\n\");\n}\n\n// ============ A2A → A2UI Conversion ============\n\nconst A2UI_MIME_TYPE = \"application/json+a2ui\";\nconst DEFAULT_SURFACE_ID = \"main\";\n\nlet componentIdCounter = 0;\n\nfunction generateComponentId(prefix: string): string {\n return `${prefix}-${++componentIdCounter}`;\n}\n\nfunction textPartToA2UI(text: string, surfaceId: string): ServerToClientMessage {\n const componentId = generateComponentId(\"text\");\n return {\n surfaceUpdate: {\n surfaceId,\n components: [\n {\n id: componentId,\n component: {\n Text: {\n text: { literalString: text },\n usageHint: \"body\",\n },\n },\n },\n ],\n },\n };\n}\n\nfunction filePartToA2UI(\n file: { bytes?: string; uri?: string; mimeType?: string; name?: string },\n surfaceId: string\n): ServerToClientMessage | null {\n const mimeType = file.mimeType || \"\";\n if (!mimeType.startsWith(\"image/\")) {\n return null;\n }\n\n const componentId = generateComponentId(\"image\");\n const url = file.uri || (file.bytes ? `data:${mimeType};base64,${file.bytes}` : null);\n\n if (!url) {\n return null;\n }\n\n return {\n surfaceUpdate: {\n surfaceId,\n components: [\n {\n id: componentId,\n component: {\n Image: {\n url: { literalString: url },\n },\n },\n },\n ],\n },\n };\n}\n\nfunction thoughtToA2UI(\n thought: { subject?: string; description?: string },\n surfaceId: string\n): ServerToClientMessage | null {\n if (!thought.subject && !thought.description) {\n return null;\n }\n\n const baseId = generateComponentId(\"thought\");\n const components: Array<{ id: string; component: Record<string, unknown> }> = [];\n\n components.push({\n id: baseId,\n component: {\n Card: {\n child: `${baseId}-content`,\n },\n },\n });\n\n const childrenList: string[] = [];\n if (thought.subject) {\n childrenList.push(`${baseId}-subject`);\n }\n if (thought.description) {\n childrenList.push(`${baseId}-desc`);\n }\n\n components.push({\n id: `${baseId}-content`,\n component: {\n Column: {\n children: { explicitList: childrenList },\n },\n },\n });\n\n if (thought.subject) {\n components.push({\n id: `${baseId}-subject`,\n component: {\n Text: {\n text: { literalString: `💭 ${thought.subject}` },\n usageHint: \"h4\",\n },\n },\n });\n }\n\n if (thought.description) {\n components.push({\n id: `${baseId}-desc`,\n component: {\n Text: {\n text: { literalString: thought.description },\n usageHint: \"caption\",\n },\n },\n });\n }\n\n return {\n surfaceUpdate: {\n surfaceId,\n components,\n },\n };\n}\n\nfunction getToolStatusDisplay(status: string): { icon: string; text: string } {\n switch (status) {\n case \"success\":\n case \"completed\":\n return { icon: \"check_circle\", text: \"✓ Completed\" };\n case \"failed\":\n case \"error\":\n return { icon: \"error\", text: \"✗ Failed\" };\n case \"validating\":\n return { icon: \"rule\", text: \"🔍 Validating...\" };\n case \"scheduled\":\n return { icon: \"schedule\", text: \"📋 Scheduled...\" };\n case \"executing\":\n return { icon: \"play_circle\", text: \"▶️ Executing...\" };\n case \"pending\":\n return { icon: \"hourglass_empty\", text: \"⏳ Pending...\" };\n default:\n return { icon: \"build\", text: \"⚙️ Running...\" };\n }\n}\n\nfunction toolCallToA2UI(\n toolCall: {\n request?: { name?: string; args?: Record<string, unknown> };\n status?: string;\n tool?: { name?: string; displayName?: string; description?: string };\n response?: { content?: string };\n resultDisplay?: string;\n },\n surfaceId: string\n): ServerToClientMessage | null {\n const toolName =\n toolCall.tool?.displayName || toolCall.tool?.name || toolCall.request?.name || \"Tool\";\n const status = toolCall.status || \"running\";\n const { icon: iconName, text: statusText } = getToolStatusDisplay(status);\n\n const baseId = generateComponentId(\"tool\");\n const components: Array<{ id: string; component: Record<string, unknown> }> = [];\n\n components.push({\n id: baseId,\n component: {\n Card: {\n child: `${baseId}-row`,\n },\n },\n });\n\n components.push({\n id: `${baseId}-row`,\n component: {\n Row: {\n alignment: \"center\",\n children: { explicitList: [`${baseId}-icon`, `${baseId}-info`] },\n },\n },\n });\n\n components.push({\n id: `${baseId}-icon`,\n component: {\n Icon: {\n name: { literalString: iconName },\n },\n },\n });\n\n // Build info column children list\n const infoChildren = [`${baseId}-name`, `${baseId}-status`];\n\n // Add result display if available (for completed tool calls)\n if (toolCall.resultDisplay && (status === \"success\" || status === \"completed\")) {\n infoChildren.push(`${baseId}-result`);\n }\n\n components.push({\n id: `${baseId}-info`,\n component: {\n Column: {\n children: { explicitList: infoChildren },\n },\n },\n });\n\n components.push({\n id: `${baseId}-name`,\n component: {\n Text: {\n text: { literalString: toolName },\n usageHint: \"body\",\n },\n },\n });\n\n components.push({\n id: `${baseId}-status`,\n component: {\n Text: {\n text: { literalString: statusText },\n usageHint: \"caption\",\n },\n },\n });\n\n // Add result preview if available\n if (toolCall.resultDisplay && (status === \"success\" || status === \"completed\")) {\n // Truncate long results for display\n const resultPreview =\n toolCall.resultDisplay.length > 200\n ? toolCall.resultDisplay.slice(0, 200) + \"...\"\n : toolCall.resultDisplay;\n\n components.push({\n id: `${baseId}-result`,\n component: {\n Text: {\n text: { literalString: resultPreview },\n usageHint: \"caption\",\n },\n },\n });\n }\n\n return {\n surfaceUpdate: {\n surfaceId,\n components,\n },\n };\n}\n\nconst CODER_AGENT_EVENT = {\n THOUGHT: \"thought\",\n TOOL_CALL_UPDATE: \"tool-call-update\",\n TOOL_CALL_CONFIRMATION: \"tool-call-confirmation\",\n TEXT_CONTENT: \"text-content\",\n STATE_CHANGE: \"state-change\",\n} as const;\n\nfunction convertA2APartsToA2UI(\n parts: Part[],\n coderAgentKind?: string,\n surfaceId: string = DEFAULT_SURFACE_ID\n): ServerToClientMessage[] {\n const messages: ServerToClientMessage[] = [];\n\n for (const part of parts) {\n if (part.kind === \"text\") {\n // For text-content events or regular text parts, convert text to A2UI\n messages.push(textPartToA2UI(part.text, surfaceId));\n } else if (part.kind === \"file\" && \"file\" in part) {\n const file = part.file as { bytes?: string; uri?: string; mimeType?: string; name?: string };\n const a2uiMsg = filePartToA2UI(file, surfaceId);\n if (a2uiMsg) {\n messages.push(a2uiMsg);\n }\n } else if (part.kind === \"data\") {\n const data = part.data as Record<string, unknown>;\n\n if (part.metadata?.mimeType === A2UI_MIME_TYPE) {\n messages.push(data as ServerToClientMessage);\n } else if (coderAgentKind === CODER_AGENT_EVENT.THOUGHT) {\n const thought = data as { subject?: string; description?: string };\n if (thought.subject) {\n const a2uiMsg = thoughtToA2UI(thought, surfaceId);\n if (a2uiMsg) {\n messages.push(a2uiMsg);\n }\n } else if (thought.description) {\n messages.push(textPartToA2UI(thought.description, surfaceId));\n }\n } else if (\n coderAgentKind === CODER_AGENT_EVENT.TOOL_CALL_UPDATE ||\n coderAgentKind === CODER_AGENT_EVENT.TOOL_CALL_CONFIRMATION\n ) {\n const a2uiMsg = toolCallToA2UI(\n data as {\n request?: { name?: string; args?: Record<string, unknown> };\n status?: string;\n tool?: { name?: string; displayName?: string; description?: string };\n response?: { content?: string };\n },\n surfaceId\n );\n if (a2uiMsg) {\n messages.push(a2uiMsg);\n }\n }\n // Note: TEXT_CONTENT events now use \"text\" parts (handled above), not \"data\" parts\n }\n }\n\n return messages;\n}\n\nfunction convertResponseToA2UI(response: SendStreamingMessageResponse): ServerToClientMessage[] {\n if (\"error\" in response) {\n return [];\n }\n\n const result = response.result;\n if (!result || !(\"kind\" in result) || result.kind !== \"status-update\") {\n return [];\n }\n\n const metadata = result.metadata as { coderAgent?: { kind?: string } } | undefined;\n const coderAgentKind = metadata?.coderAgent?.kind;\n\n // Skip state-change events without message content (submitted/working state transitions)\n if (coderAgentKind === CODER_AGENT_EVENT.STATE_CHANGE) {\n return [];\n }\n\n // Handle messages with parts (text, file, data, tool calls, thoughts, etc.)\n const parts = result.status?.message?.parts;\n if (!parts || parts.length === 0) {\n return [];\n }\n\n return convertA2APartsToA2UI(parts, coderAgentKind);\n}\n\n// ============ SSE Stream Handling ============\n\nasync function* parseSSEStream(\n streamResponse: StreamResponse\n): AsyncGenerator<SendStreamingMessageResponse, void, unknown> {\n const queue: SendStreamingMessageResponse[] = [];\n\n const parser = createParser({\n onEvent: (event) => {\n try {\n queue.push(JSON.parse(event.data));\n } catch {\n // Ignore parse errors\n }\n },\n });\n\n try {\n while (true) {\n const chunk = await streamResponse.read();\n if (chunk === null) break;\n if (chunk) {\n parser.feed(chunk);\n while (queue.length > 0) {\n const item = queue.shift();\n if (item) yield item;\n }\n }\n }\n } catch {\n // Ignore stream errors\n }\n}\n\n// ============ Client ============\n\nexport type CopilotA2UIClient = {\n /**\n * Stream A2UI messages from Copilot Agent.\n *\n * @example\n * ```typescript\n * import { createCopilotA2UIClient, Data } from \"@amaster.ai/copilot-client\";\n *\n * const client = createCopilotA2UIClient();\n * const processor = Data.createSignalA2uiMessageProcessor();\n *\n * for await (const messages of client.chat([{ role: \"user\", content: \"Hello\" }])) {\n * processor.processMessages(messages);\n * }\n * ```\n */\n chat(\n messages: ChatMessage[],\n options?: ChatOptions\n ): AsyncGenerator<ServerToClientMessage[], void, unknown>;\n\n cancelChat(taskId: string): Promise<ClientResult<CancelTaskResponse>>;\n getChatStatus(taskId: string): Promise<ClientResult<GetTaskResponse>>;\n};\n\n/**\n * Create Copilot A2UI client\n *\n * Auto-detects runtime environment (Browser/Vite/Taro H5/Taro Mini-program)\n */\nexport function createCopilotA2UIClient(http: HttpClient = createHttpClient()): CopilotA2UIClient {\n const baseUrl = \"/api/proxy/builtin/platform/copilot\";\n\n async function* sendMessageStream(\n request: SendStreamingMessageRequest\n ): AsyncGenerator<SendStreamingMessageResponse, void, unknown> {\n try {\n const streamResponse = await createStream(baseUrl, request);\n\n if (!streamResponse.ok) {\n throw new Error(`Stream request failed: ${streamResponse.statusText}`);\n }\n\n yield* parseSSEStream(streamResponse);\n } catch {\n // Ignore stream errors\n }\n }\n\n return {\n async *chat(messages, chatOptions = {}) {\n const { taskId } = chatOptions;\n\n const systemMsg = messages.find((m) => m.role === \"system\");\n const nonSystemMsgs = messages.filter((m) => m.role !== \"system\");\n const lastUserMsg = nonSystemMsgs[nonSystemMsgs.length - 1];\n\n const parts = lastUserMsg\n ? convertToA2AParts(lastUserMsg.content)\n : [{ kind: \"text\" as const, text: \"\" }];\n\n const systemPrompt = systemMsg ? extractTextFromContent(systemMsg.content) : undefined;\n\n const request: SendStreamingMessageRequest = {\n jsonrpc: \"2.0\",\n id: generateUUID(),\n method: \"message/stream\",\n params: {\n message: {\n contextId: getAppId(),\n kind: \"message\",\n messageId: generateUUID(),\n role: \"user\",\n parts,\n ...(taskId && { taskId }),\n ...(systemPrompt && { metadata: { systemPrompt } }),\n },\n },\n };\n\n for await (const response of sendMessageStream(request)) {\n const a2uiMessages = convertResponseToA2UI(response);\n if (a2uiMessages.length > 0) {\n yield a2uiMessages;\n }\n }\n },\n\n cancelChat(taskId) {\n const request: CancelTaskRequest = {\n jsonrpc: \"2.0\",\n id: generateUUID(),\n method: \"tasks/cancel\",\n params: { id: taskId },\n };\n return http.request<CancelTaskResponse>({\n url: baseUrl,\n method: \"POST\",\n data: request,\n });\n },\n\n getChatStatus(taskId) {\n const request: GetTaskRequest = {\n jsonrpc: \"2.0\",\n id: generateUUID(),\n method: \"tasks/get\",\n params: { id: taskId },\n };\n return http.request<GetTaskResponse>({\n url: baseUrl,\n method: \"POST\",\n data: request,\n });\n },\n };\n}\n","/**\n * A2UI Types - Inlined from @a2ui/lit for Taro compatibility\n *\n * This file contains the minimal A2UI type definitions needed by copilot-client.\n * We inline these types instead of importing from @a2ui/lit because @a2ui/lit\n * uses ES2025 `import ... with { type: \"json\" }` syntax which is not supported\n * by Taro's Vite/esbuild version.\n */\n\n// ============ Primitive Types ============\n\nexport interface StringValue {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n /** A fixed, hardcoded string value. */\n literalString?: string;\n /** A fixed, hardcoded string value. */\n literal?: string;\n}\n\nexport interface NumberValue {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n /** A fixed, hardcoded number value. */\n literalNumber?: number;\n /** A fixed, hardcoded number value. */\n literal?: number;\n}\n\nexport interface BooleanValue {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n /** A fixed, hardcoded boolean value. */\n literalBoolean?: boolean;\n /** A fixed, hardcoded boolean value. */\n literal?: boolean;\n}\n\n// ============ Component Types ============\n\nexport interface Action {\n /** A unique name identifying the action (e.g., 'submitForm'). */\n name: string;\n /** A key-value map of data bindings to be resolved when the action is triggered. */\n context?: {\n key: string;\n /** The dynamic value. Define EXACTLY ONE of the nested properties. */\n value: {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n /** A fixed, hardcoded string value. */\n literalString?: string;\n literalNumber?: number;\n literalBoolean?: boolean;\n };\n }[];\n}\n\nexport interface Text {\n text: StringValue;\n usageHint: \"h1\" | \"h2\" | \"h3\" | \"h4\" | \"h5\" | \"caption\" | \"body\";\n}\n\nexport interface Image {\n url: StringValue;\n usageHint: \"icon\" | \"avatar\" | \"smallFeature\" | \"mediumFeature\" | \"largeFeature\" | \"header\";\n fit?: \"contain\" | \"cover\" | \"fill\" | \"none\" | \"scale-down\";\n}\n\nexport interface Icon {\n name: StringValue;\n}\n\nexport interface Video {\n url: StringValue;\n}\n\nexport interface AudioPlayer {\n url: StringValue;\n /** A label, title, or placeholder text. */\n description?: StringValue;\n}\n\nexport interface Tabs {\n /** A list of tabs, each with a title and a child component ID. */\n tabItems: {\n /** The title of the tab. */\n title: {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n /** A fixed, hardcoded string value. */\n literalString?: string;\n };\n /** A reference to a component instance by its unique ID. */\n child: string;\n }[];\n}\n\nexport interface Divider {\n /** The orientation. */\n axis?: \"horizontal\" | \"vertical\";\n /** The color of the divider (e.g., hex code or semantic name). */\n color?: string;\n /** The thickness of the divider. */\n thickness?: number;\n}\n\nexport interface Modal {\n /** The ID of the component (e.g., a button) that triggers the modal. */\n entryPointChild: string;\n /** The ID of the component to display as the modal's content. */\n contentChild: string;\n}\n\nexport interface Button {\n /** The ID of the component to display as the button's content. */\n child: string;\n /** Represents a user-initiated action. */\n action: Action;\n}\n\nexport interface Checkbox {\n label: StringValue;\n value: {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n literalBoolean?: boolean;\n };\n}\n\nexport interface TextField {\n text?: StringValue;\n /** A label, title, or placeholder text. */\n label: StringValue;\n type?: \"shortText\" | \"number\" | \"date\" | \"longText\";\n /** A regex string to validate the input. */\n validationRegexp?: string;\n}\n\nexport interface DateTimeInput {\n value: StringValue;\n enableDate?: boolean;\n enableTime?: boolean;\n /** The string format for the output (e.g., 'YYYY-MM-DD'). */\n outputFormat?: string;\n}\n\nexport interface MultipleChoice {\n selections: {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n literalArray?: string[];\n };\n options?: {\n label: {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n /** A fixed, hardcoded string value. */\n literalString?: string;\n };\n value: string;\n }[];\n maxAllowedSelections?: number;\n}\n\nexport interface Slider {\n value: {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n literalNumber?: number;\n };\n minValue?: number;\n maxValue?: number;\n}\n\n// ============ Data Model Types ============\n\n/** A recursive type for any valid JSON-like value in the data model. */\nexport type DataValue = string | number | boolean | null | DataMap | DataObject | DataArray;\nexport type DataObject = { [key: string]: DataValue };\nexport type DataMap = Map<string, DataValue>;\nexport type DataArray = DataValue[];\n\n/** A template for creating components from a list in the data model. */\nexport interface ComponentArrayTemplate {\n componentId: string;\n dataBinding: string;\n}\n\n/** Defines a list of child components, either explicitly or via a template. */\nexport interface ComponentArrayReference {\n explicitList?: string[];\n template?: ComponentArrayTemplate;\n}\n\n/** Represents the general shape of a component's properties. */\nexport type ComponentProperties = {\n children?: ComponentArrayReference;\n child?: string;\n [k: string]: unknown;\n};\n\n/** A raw component instance from a SurfaceUpdate message. */\nexport interface ComponentInstance {\n id: string;\n weight?: number;\n component?: ComponentProperties;\n}\n\nexport type ValueMap = DataObject & {\n key: string;\n /** May be JSON */\n valueString?: string;\n valueNumber?: number;\n valueBoolean?: boolean;\n valueMap?: ValueMap[];\n};\n\n// ============ Message Types ============\n\nexport interface BeginRenderingMessage {\n surfaceId: string;\n root: string;\n styles?: Record<string, string>;\n}\n\nexport interface SurfaceUpdateMessage {\n surfaceId: string;\n components: ComponentInstance[];\n}\n\nexport interface DataModelUpdate {\n surfaceId: string;\n path?: string;\n contents: ValueMap[];\n}\n\nexport interface DeleteSurfaceMessage {\n surfaceId: string;\n}\n\nexport interface ServerToClientMessage {\n beginRendering?: BeginRenderingMessage;\n surfaceUpdate?: SurfaceUpdateMessage;\n dataModelUpdate?: DataModelUpdate;\n deleteSurface?: DeleteSurfaceMessage;\n}\n\n// ============ Component Node Types ============\n\n/** A recursive type for any value that can appear within a resolved component tree. */\nexport type ResolvedValue =\n | string\n | number\n | boolean\n | null\n | AnyComponentNode\n | ResolvedMap\n | ResolvedArray;\n\n/** A generic map where each value has been recursively resolved. */\nexport type ResolvedMap = { [key: string]: ResolvedValue };\n\n/** A generic array where each item has been recursively resolved. */\nexport type ResolvedArray = ResolvedValue[];\n\n/** A base interface that all component nodes share. */\ninterface BaseComponentNode {\n id: string;\n weight?: number;\n dataContextPath?: string;\n slotName?: string;\n}\n\nexport interface TextNode extends BaseComponentNode {\n type: \"Text\";\n properties: Text;\n}\n\nexport interface ImageNode extends BaseComponentNode {\n type: \"Image\";\n properties: Image;\n}\n\nexport interface IconNode extends BaseComponentNode {\n type: \"Icon\";\n properties: Icon;\n}\n\nexport interface VideoNode extends BaseComponentNode {\n type: \"Video\";\n properties: Video;\n}\n\nexport interface AudioPlayerNode extends BaseComponentNode {\n type: \"AudioPlayer\";\n properties: AudioPlayer;\n}\n\nexport interface RowNode extends BaseComponentNode {\n type: \"Row\";\n properties: ResolvedRow;\n}\n\nexport interface ColumnNode extends BaseComponentNode {\n type: \"Column\";\n properties: ResolvedColumn;\n}\n\nexport interface ListNode extends BaseComponentNode {\n type: \"List\";\n properties: ResolvedList;\n}\n\nexport interface CardNode extends BaseComponentNode {\n type: \"Card\";\n properties: ResolvedCard;\n}\n\nexport interface TabsNode extends BaseComponentNode {\n type: \"Tabs\";\n properties: ResolvedTabs;\n}\n\nexport interface DividerNode extends BaseComponentNode {\n type: \"Divider\";\n properties: Divider;\n}\n\nexport interface ModalNode extends BaseComponentNode {\n type: \"Modal\";\n properties: ResolvedModal;\n}\n\nexport interface ButtonNode extends BaseComponentNode {\n type: \"Button\";\n properties: ResolvedButton;\n}\n\nexport interface CheckboxNode extends BaseComponentNode {\n type: \"CheckBox\";\n properties: Checkbox;\n}\n\nexport interface TextFieldNode extends BaseComponentNode {\n type: \"TextField\";\n properties: TextField;\n}\n\nexport interface DateTimeInputNode extends BaseComponentNode {\n type: \"DateTimeInput\";\n properties: DateTimeInput;\n}\n\nexport interface MultipleChoiceNode extends BaseComponentNode {\n type: \"MultipleChoice\";\n properties: MultipleChoice;\n}\n\nexport interface SliderNode extends BaseComponentNode {\n type: \"Slider\";\n properties: Slider;\n}\n\nexport interface CustomNode extends BaseComponentNode {\n type: string;\n properties: CustomNodeProperties;\n}\n\n/**\n * The complete discriminated union of all possible resolved component nodes.\n * A renderer would use this type for any given node in the component tree.\n */\nexport type AnyComponentNode =\n | TextNode\n | IconNode\n | ImageNode\n | VideoNode\n | AudioPlayerNode\n | RowNode\n | ColumnNode\n | ListNode\n | CardNode\n | TabsNode\n | DividerNode\n | ModalNode\n | ButtonNode\n | CheckboxNode\n | TextFieldNode\n | DateTimeInputNode\n | MultipleChoiceNode\n | SliderNode\n | CustomNode;\n\nexport interface ResolvedRow {\n children: AnyComponentNode[];\n distribution?: \"start\" | \"center\" | \"end\" | \"spaceBetween\" | \"spaceAround\" | \"spaceEvenly\";\n alignment?: \"start\" | \"center\" | \"end\" | \"stretch\";\n}\n\nexport interface ResolvedColumn {\n children: AnyComponentNode[];\n distribution?: \"start\" | \"center\" | \"end\" | \"spaceBetween\" | \"spaceAround\" | \"spaceEvenly\";\n alignment?: \"start\" | \"center\" | \"end\" | \"stretch\";\n}\n\nexport interface ResolvedButton {\n child: AnyComponentNode;\n action: Button[\"action\"];\n}\n\nexport interface ResolvedList {\n children: AnyComponentNode[];\n direction?: \"vertical\" | \"horizontal\";\n alignment?: \"start\" | \"center\" | \"end\" | \"stretch\";\n}\n\nexport interface ResolvedCard {\n child: AnyComponentNode;\n children: AnyComponentNode[];\n}\n\nexport interface ResolvedTabItem {\n title: StringValue;\n child: AnyComponentNode;\n}\n\nexport interface ResolvedTabs {\n tabItems: ResolvedTabItem[];\n}\n\nexport interface ResolvedModal {\n entryPointChild: AnyComponentNode;\n contentChild: AnyComponentNode;\n}\n\nexport interface CustomNodeProperties {\n [k: string]: ResolvedValue;\n}\n\nexport type SurfaceID = string;\n\n/** The complete state of a single UI surface. */\nexport interface Surface {\n rootComponentId: string | null;\n componentTree: AnyComponentNode | null;\n dataModel: DataMap;\n components: Map<string, ComponentInstance>;\n styles: Record<string, string>;\n}\n\n// ============ MessageProcessor Interface ============\n\nexport interface MessageProcessor {\n getSurfaces(): ReadonlyMap<string, Surface>;\n clearSurfaces(): void;\n processMessages(messages: ServerToClientMessage[]): void;\n /**\n * Retrieves the data for a given component node and a relative path string.\n * This correctly handles the special `.` path, which refers to the node's\n * own data context.\n */\n getData(node: AnyComponentNode, relativePath: string, surfaceId: string): DataValue | null;\n setData(\n node: AnyComponentNode | null,\n relativePath: string,\n value: DataValue,\n surfaceId: string\n ): void;\n resolvePath(path: string, dataContextPath?: string): string;\n}\n"]}
1
+ {"version":3,"sources":["../src/copilot-a2ui-client.ts","../src/a2ui-types.ts"],"names":["g","getMiniProgramRequest","generateUUID","cryptoObj","c","r","extractAppIdFromUrl","url","pathMatch","hostname","wwwMatch","domainMatch","cachedAppId","getAppId","urlAppId","createWeChatMiniProgramStream","data","authHeader","resolve","chunkBuffer","textDecoder","MiniProgramTextDecoder","ended","errorOccurred","dataQueue","resolveRead","pendingRead","pushChunk","text","chunkListener","res","newChunk","merged","decodeOffset","partial","decoded","MiniProgramTextEncoder","err","headersListener","miniReq","requestTask","finalText","error","createStream","getAccessToken","token","buffer","completed","failed","position","opts","ret","chunk","headers","response","reader","decoder","done","value","convertToA2AParts","content","part","extractTextFromContent","A2UI_MIME_TYPE","DEFAULT_SURFACE_ID","componentIdCounter","generateComponentId","prefix","textPartToA2UI","surfaceId","componentId","filePartToA2UI","file","mimeType","thoughtToA2UI","thought","baseId","components","childrenList","getToolStatusDisplay","status","toolCallToA2UI","toolCall","toolName","iconName","statusText","infoChildren","resultPreview","CODER_AGENT_EVENT","convertA2APartsToA2UI","parts","coderAgentKind","messages","a2uiMsg","convertResponseToA2UI","result","parseSSEStream","streamResponse","queue","parser","createParser","event","item","createCopilotA2UIClient","http","createHttpClient","baseUrl","envBaseUrl","metaEnv","sendMessageStream","request","chatOptions","taskId","systemMsg","m","nonSystemMsgs","lastUserMsg","systemPrompt","a2uiMessages","a2ui_types_exports"],"mappings":"0VAsBA,IAAMA,CAAAA,CAAI,UAAA,CAEV,SAASC,CAAAA,EAAsD,CAC7D,OAAI,OAAOD,CAAAA,EAAG,IAAA,EAAM,OAAA,EAAY,UAAA,CAAmBA,CAAAA,CAAE,IAAA,CAAK,OAAA,CAAQ,KAAKA,CAAAA,CAAE,IAAI,CAAA,CACzE,OAAOA,CAAAA,EAAG,EAAA,EAAI,OAAA,EAAY,UAAA,CAAmBA,CAAAA,CAAE,EAAA,CAAG,OAAA,CAAQ,IAAA,CAAKA,CAAAA,CAAE,EAAE,CAAA,CACnE,OAAOA,CAAAA,EAAG,EAAA,EAAI,OAAA,EAAY,UAAA,C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AAMuG,CACR,CAAC,CACH,CACF,CACF,KCl/BAS,CAAAA,CAAA","file":"index.cjs","sourcesContent":["/* eslint-disable no-undef, no-unused-vars */\nimport type {\n CancelTaskRequest,\n CancelTaskResponse,\n GetTaskRequest,\n GetTaskResponse,\n Part,\n SendStreamingMessageRequest,\n SendStreamingMessageResponse,\n} from \"@a2a-js/sdk\";\nimport { type ClientResult, createHttpClient, type HttpClient } from \"@amaster.ai/http-client\";\nimport { createParser } from \"eventsource-parser\";\nimport type { ServerToClientMessage, Surface, MessageProcessor } from \"./a2ui-types\";\nimport MiniProgramTextDecoder from \"miniprogram-text-decoder\";\nimport MiniProgramTextEncoder from \"miniprogram-text-encoder\";\n\n// Re-export A2UI types from local definitions\nexport type { ServerToClientMessage, Surface, MessageProcessor };\n\n// ============ Internal: Platform Detection (same as http-client) ============\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst g = globalThis as any;\n\nfunction getMiniProgramRequest(): ((_opts: any) => any) | null {\n if (typeof g?.Taro?.request === \"function\") return g.Taro.request.bind(g.Taro);\n if (typeof g?.wx?.request === \"function\") return g.wx.request.bind(g.wx);\n if (typeof g?.tt?.request === \"function\") return g.tt.request.bind(g.tt);\n if (typeof g?.my?.request === \"function\") return g.my.request.bind(g.my);\n if (typeof g?.swan?.request === \"function\") return g.swan.request.bind(g.swan);\n if (typeof g?.qq?.request === \"function\") return g.qq.request.bind(g.qq);\n if (typeof g?.jd?.request === \"function\") return g.jd.request.bind(g.jd);\n return null;\n}\n\n// ============ Internal: UUID Generator ============\n\nfunction generateUUID(): string {\n const cryptoObj = typeof globalThis !== \"undefined\" ? globalThis.crypto : undefined;\n\n if (cryptoObj && typeof cryptoObj.randomUUID === \"function\") {\n return cryptoObj.randomUUID();\n }\n\n if (cryptoObj && typeof cryptoObj.getRandomValues === \"function\") {\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n const randomValues = cryptoObj.getRandomValues(new Uint8Array(1));\n const r = (randomValues[0] ?? 0) % 16;\n const v = c === \"x\" ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n }\n\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === \"x\" ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n// ============ Internal: URL Utilities ============\n\nfunction extractAppIdFromUrl(): string | null {\n if (typeof window === \"undefined\") return null;\n\n try {\n const url = window.location.href;\n const pathMatch = /\\/app\\/([\\da-f-]+)(?:\\/|$)/.exec(url);\n if (pathMatch?.[1]) return pathMatch[1];\n\n const hostname = window.location.hostname;\n\n // Pattern 1: www.{app_id}.domain.tld or www.{app_id}-{env}.domain.tld\n const wwwMatch = /^www\\.([\\da-f-]+)(?:-[^.]+)?\\.[\\w-]+\\.(?:local|ai|cn)$/.exec(hostname);\n if (wwwMatch?.[1]) return wwwMatch[1];\n\n // Pattern 2: {app_id}-{env}.domain.tld or {app_id}.domain.tld\n const domainMatch = /^([\\da-f-]+)(?:-[^.]+)?\\.[\\w-]+\\.(?:local|ai|cn)$/.exec(hostname);\n if (domainMatch?.[1]) return domainMatch[1];\n\n return null;\n } catch {\n return null;\n }\n}\n\n// Cache appId for session consistency\nlet cachedAppId: string | null = null;\n\nfunction getAppId(): string {\n const urlAppId = extractAppIdFromUrl();\n if (urlAppId) return urlAppId;\n if (!cachedAppId) cachedAppId = generateUUID();\n return cachedAppId;\n}\n\n// ============ Internal: Streaming ============\n\ninterface StreamResponse {\n ok: boolean;\n statusText: string;\n read(): Promise<string | null>;\n}\n\n// 小程序专用的流式请求\nasync function createWeChatMiniProgramStream(\n url: string, \n data: unknown,\n authHeader: Record<string, string> = {}\n): Promise<StreamResponse> {\n return new Promise<StreamResponse>((resolve) => {\n let chunkBuffer = new Uint8Array(0); // 字节缓冲,用于处理 UTF-8 截断\n const textDecoder = new MiniProgramTextDecoder(\"utf-8\", {\n fatal: false,\n });\n\n let ended = false;\n let errorOccurred = false;\n\n // 用于外部调用 read() 时取数据的队列\n const dataQueue: string[] = [];\n let resolveRead: ((value: string | null) => void) | null = null;\n\n const pendingRead = () =>\n new Promise<string | null>((r) => {\n if (dataQueue.length > 0) {\n r(dataQueue.shift()!);\n } else if (ended) {\n r(null);\n } else {\n resolveRead = r;\n }\n });\n\n const pushChunk = (text: string) => {\n if (text) {\n dataQueue.push(text);\n if (resolveRead) {\n resolveRead(dataQueue.shift()!);\n resolveRead = null;\n }\n }\n };\n\n const chunkListener = (res: any) => {\n if (errorOccurred || ended || !res.data) return;\n\n try {\n const newChunk = new Uint8Array(res.data as ArrayBuffer);\n // 追加到缓冲\n const merged = new Uint8Array(chunkBuffer.length + newChunk.length);\n merged.set(chunkBuffer);\n merged.set(newChunk, chunkBuffer.length);\n chunkBuffer = merged;\n\n // 尝试解码尽可能多的完整字符\n let decodeOffset = 0;\n while (decodeOffset < chunkBuffer.length) {\n const partial = chunkBuffer.subarray(decodeOffset);\n const decoded = textDecoder.decode(partial, { stream: false });\n\n // 如果解码出内容,说明前面是完整字符\n if (decoded) {\n pushChunk(decoded);\n // 移动偏移(注意:TextDecoder 内部会处理多字节边界)\n // 但为了安全,我们粗略估算已消费字节(不完美但够用)\n // 实际生产中可使用更精确的边界检测\n decodeOffset += new MiniProgramTextEncoder().encode(decoded).length;\n } else {\n // 剩余部分可能是半个字符,留到下次\n break;\n }\n }\n\n // 保留未解码的部分\n if (decodeOffset < chunkBuffer.length) {\n chunkBuffer = chunkBuffer.subarray(decodeOffset);\n } else {\n chunkBuffer = new Uint8Array(0);\n }\n } catch (err) {\n console.error(\"[mini stream] chunk process error:\", err);\n }\n };\n\n const headersListener = (res: any) => {\n if (res.header?.[\"content-type\"]?.includes(\"text/event-stream\") === false) {\n console.warn(\"Warning: server did not return event-stream\");\n }\n };\n\n const miniReq = g.wx.request.bind(g.wx);\n\n try {\n const requestTask = miniReq({\n url,\n method: \"POST\",\n header: {\n \"Content-Type\": \"application/json\",\n Accept: \"text/event-stream\",\n ...authHeader,\n },\n data: typeof data === \"string\" ? data : JSON.stringify(data),\n responseType: \"arraybuffer\", // 必须!\n enableChunked: true, // 必须!\n timeout: 300000,\n\n success: () => {\n // 成功结束时,把剩余缓冲区解码\n if (chunkBuffer.length > 0) {\n const finalText = textDecoder.decode(chunkBuffer, {\n stream: true,\n });\n pushChunk(finalText);\n }\n ended = true;\n if (resolveRead) resolveRead(null);\n },\n\n fail: (err: any) => {\n console.error(\"[mini stream] request fail:\", err);\n errorOccurred = true;\n ended = true;\n if (resolveRead) resolveRead(null);\n },\n });\n // 关键:监听分块到达\n requestTask.onChunkReceived?.(chunkListener);\n // 可选:监听 HTTP headers 到达(可用于检查状态码)\n requestTask.onHeadersReceived?.(headersListener);\n\n resolve({\n ok: true, // 稍后可根据 headers 更精确判断\n statusText: \"OK\",\n read: async () => {\n if (errorOccurred) return null;\n return pendingRead();\n },\n });\n } catch (error) {\n console.error(\"miniReq error\", error);\n }\n });\n}\n\nasync function createStream(\n url: string, \n data: unknown,\n getAccessToken?: () => string | null\n): Promise<StreamResponse> {\n // Get token for authentication\n const token = getAccessToken?.();\n const authHeader: Record<string, string> = token ? { Authorization: `Bearer ${token}` } : {};\n\n if (typeof g?.wx?.request === \"function\") {\n return createWeChatMiniProgramStream(url, data, authHeader);\n }\n const miniReq = getMiniProgramRequest();\n if (miniReq) {\n // Mini-program: buffer full response\n return new Promise((resolve) => {\n let buffer = \"\";\n let completed = false;\n let failed = false;\n let position = 0;\n\n const opts = {\n url,\n method: \"POST\",\n header: {\n \"Content-Type\": \"application/json\",\n Accept: \"text/event-stream\",\n ...authHeader,\n },\n data: typeof data === \"string\" ? data : JSON.stringify(data),\n timeout: 60000,\n success: (res: any) => {\n buffer = typeof res.data === \"string\" ? res.data : JSON.stringify(res.data);\n completed = true;\n },\n fail: (err: any) => {\n console.error(\"[createStream] wx.request failed:\", err);\n failed = true;\n completed = true;\n },\n complete: () => {},\n };\n\n try {\n const ret = miniReq(opts);\n\n if (ret && typeof ret.then === \"function\") {\n ret\n .then((res: any) => {\n buffer = typeof res.data === \"string\" ? res.data : JSON.stringify(res.data);\n completed = true;\n })\n .catch(() => {\n failed = true;\n completed = true;\n });\n }\n } catch (err) {\n console.error(\"[createStream] Exception:\", err);\n failed = true;\n completed = true;\n }\n\n resolve({\n ok: true,\n statusText: \"OK\",\n read: async () => {\n while (!completed && position >= buffer.length) {\n await new Promise((r) => setTimeout(r, 50));\n }\n if (failed) return null;\n if (position >= buffer.length) return completed ? null : \"\";\n const chunk = buffer.slice(position);\n position = buffer.length;\n return chunk;\n },\n });\n });\n }\n\n // Browser: use fetch streaming with authentication\n const headers: Record<string, string> = { \n \"Content-Type\": \"application/json\",\n ...authHeader,\n };\n \n const response = await fetch(url, {\n method: \"POST\",\n headers,\n credentials: \"include\",\n body: JSON.stringify(data),\n });\n\n if (!response.body) {\n return {\n ok: response.ok,\n statusText: response.statusText,\n read: async () => null,\n };\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n\n return {\n ok: response.ok,\n statusText: response.statusText,\n read: async () => {\n const { done, value } = await reader.read();\n if (done) return null;\n return decoder.decode(value, { stream: true });\n },\n };\n}\n\n// ============ Input Types ============\n\nexport interface TextContent {\n type: \"text\";\n text: string;\n}\n\nexport interface ImageContent {\n type: \"image\";\n data?: string;\n url?: string;\n mimeType?: string;\n}\n\nexport interface FileContent {\n type: \"file\";\n data?: string;\n url?: string;\n mimeType?: string;\n name?: string;\n}\n\nexport type MessageContent = TextContent | ImageContent | FileContent;\n\nexport interface ChatMessage {\n role: \"system\" | \"user\" | \"assistant\";\n content: string | MessageContent[];\n}\n\nexport interface ChatOptions {\n taskId?: string;\n}\n\n// ============ Convert Input to A2A Part ============\n\nfunction convertToA2AParts(content: string | MessageContent[]): Part[] {\n if (typeof content === \"string\") {\n return [{ kind: \"text\", text: content }];\n }\n\n return content\n .map((part): Part | null => {\n switch (part.type) {\n case \"text\":\n return { kind: \"text\", text: part.text };\n case \"image\":\n if (part.data) {\n return {\n kind: \"file\",\n file: {\n bytes: part.data,\n mimeType: part.mimeType || \"image/png\",\n },\n };\n }\n if (part.url) {\n return {\n kind: \"file\",\n file: { uri: part.url, mimeType: part.mimeType || \"image/png\" },\n };\n }\n return null;\n case \"file\":\n if (part.data) {\n return {\n kind: \"file\",\n file: {\n bytes: part.data,\n ...(part.mimeType && { mimeType: part.mimeType }),\n ...(part.name && { name: part.name }),\n },\n };\n }\n if (part.url) {\n return {\n kind: \"file\",\n file: {\n uri: part.url,\n ...(part.mimeType && { mimeType: part.mimeType }),\n ...(part.name && { name: part.name }),\n },\n };\n }\n return null;\n default:\n return null;\n }\n })\n .filter((part): part is Part => part !== null);\n}\n\nfunction extractTextFromContent(content: string | MessageContent[]): string {\n if (typeof content === \"string\") {\n return content;\n }\n return content\n .filter((part): part is TextContent => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\\n\");\n}\n\n// ============ A2A → A2UI Conversion ============\n\nconst A2UI_MIME_TYPE = \"application/json+a2ui\";\nconst DEFAULT_SURFACE_ID = \"main\";\n\nlet componentIdCounter = 0;\n\nfunction generateComponentId(prefix: string): string {\n return `${prefix}-${++componentIdCounter}`;\n}\n\nfunction textPartToA2UI(text: string, surfaceId: string): ServerToClientMessage {\n const componentId = generateComponentId(\"text\");\n return {\n surfaceUpdate: {\n surfaceId,\n components: [\n {\n id: componentId,\n component: {\n Text: {\n text: { literalString: text },\n usageHint: \"body\",\n },\n },\n },\n ],\n },\n };\n}\n\nfunction filePartToA2UI(\n file: { bytes?: string; uri?: string; mimeType?: string; name?: string },\n surfaceId: string\n): ServerToClientMessage | null {\n const mimeType = file.mimeType || \"\";\n if (!mimeType.startsWith(\"image/\")) {\n return null;\n }\n\n const componentId = generateComponentId(\"image\");\n const url = file.uri || (file.bytes ? `data:${mimeType};base64,${file.bytes}` : null);\n\n if (!url) {\n return null;\n }\n\n return {\n surfaceUpdate: {\n surfaceId,\n components: [\n {\n id: componentId,\n component: {\n Image: {\n url: { literalString: url },\n },\n },\n },\n ],\n },\n };\n}\n\nfunction thoughtToA2UI(\n thought: { subject?: string; description?: string },\n surfaceId: string\n): ServerToClientMessage | null {\n if (!thought.subject && !thought.description) {\n return null;\n }\n\n const baseId = generateComponentId(\"thought\");\n const components: Array<{ id: string; component: Record<string, unknown> }> = [];\n\n components.push({\n id: baseId,\n component: {\n Card: {\n child: `${baseId}-content`,\n },\n },\n });\n\n const childrenList: string[] = [];\n if (thought.subject) {\n childrenList.push(`${baseId}-subject`);\n }\n if (thought.description) {\n childrenList.push(`${baseId}-desc`);\n }\n\n components.push({\n id: `${baseId}-content`,\n component: {\n Column: {\n children: { explicitList: childrenList },\n },\n },\n });\n\n if (thought.subject) {\n components.push({\n id: `${baseId}-subject`,\n component: {\n Text: {\n text: { literalString: `💭 ${thought.subject}` },\n usageHint: \"h4\",\n },\n },\n });\n }\n\n if (thought.description) {\n components.push({\n id: `${baseId}-desc`,\n component: {\n Text: {\n text: { literalString: thought.description },\n usageHint: \"caption\",\n },\n },\n });\n }\n\n return {\n surfaceUpdate: {\n surfaceId,\n components,\n },\n };\n}\n\nfunction getToolStatusDisplay(status: string): { icon: string; text: string; status: string } {\n switch (status) {\n case \"success\":\n case \"completed\":\n return { icon: \"check_circle\", text: \"✓ Completed\", status };\n case \"failed\":\n case \"error\":\n return { icon: \"error\", text: \"✗ Failed\", status };\n case \"validating\":\n return { icon: \"rule\", text: \"🔍 Validating...\", status };\n case \"scheduled\":\n return { icon: \"schedule\", text: \"📋 Scheduled...\", status };\n case \"executing\":\n return { icon: \"play_circle\", text: \"▶️ Executing...\", status };\n case \"pending\":\n return { icon: \"hourglass_empty\", text: \"⏳ Pending...\", status };\n default:\n return { icon: \"build\", text: \"⚙️ Running...\", status };\n }\n}\n\nfunction toolCallToA2UI(\n toolCall: {\n request?: { name?: string; args?: Record<string, unknown> };\n status?: string;\n tool?: { name?: string; displayName?: string; description?: string };\n response?: { content?: string };\n resultDisplay?: string;\n },\n surfaceId: string\n): ServerToClientMessage | null {\n const toolName =\n toolCall.tool?.displayName || toolCall.tool?.name || toolCall.request?.name || \"Tool\";\n const status = toolCall.status || \"running\";\n const { icon: iconName, text: statusText } = getToolStatusDisplay(status);\n\n const baseId = generateComponentId(\"tool\");\n const components: Array<{ id: string; component: Record<string, unknown> }> = [];\n\n components.push({\n id: baseId,\n component: {\n Card: {\n child: `${baseId}-row`,\n },\n },\n });\n\n components.push({\n id: `${baseId}-row`,\n component: {\n Row: {\n alignment: \"center\",\n children: { explicitList: [`${baseId}-icon`, `${baseId}-info`] },\n },\n },\n });\n\n components.push({\n id: `${baseId}-icon`,\n component: {\n Icon: {\n name: { literalString: iconName },\n },\n },\n });\n\n // Build info column children list\n const infoChildren = [`${baseId}-name`, `${baseId}-status`];\n\n // Add result display if available (for completed tool calls)\n if (toolCall.resultDisplay && (status === \"success\" || status === \"completed\")) {\n infoChildren.push(`${baseId}-result`);\n }\n\n components.push({\n id: `${baseId}-info`,\n component: {\n Column: {\n children: { explicitList: infoChildren },\n },\n },\n });\n\n components.push({\n id: `${baseId}-name`,\n component: {\n Text: {\n text: { literalString: toolName },\n usageHint: \"body\",\n },\n },\n });\n\n components.push({\n id: `${baseId}-status`,\n component: {\n Text: {\n text: { literalString: statusText },\n usageHint: \"caption\",\n },\n },\n });\n\n // Add result preview if available\n if (toolCall.resultDisplay && (status === \"success\" || status === \"completed\")) {\n // Truncate long results for display\n const resultPreview =\n toolCall.resultDisplay.length > 200\n ? toolCall.resultDisplay.slice(0, 200) + \"...\"\n : toolCall.resultDisplay;\n\n components.push({\n id: `${baseId}-result`,\n component: {\n Text: {\n text: { literalString: resultPreview },\n usageHint: \"caption\",\n },\n },\n });\n }\n\n return {\n surfaceUpdate: {\n surfaceId,\n components,\n },\n };\n}\n\nconst CODER_AGENT_EVENT = {\n THOUGHT: \"thought\",\n TOOL_CALL_UPDATE: \"tool-call-update\",\n TOOL_CALL_CONFIRMATION: \"tool-call-confirmation\",\n TEXT_CONTENT: \"text-content\",\n STATE_CHANGE: \"state-change\",\n} as const;\n\nfunction convertA2APartsToA2UI(\n parts: Part[],\n coderAgentKind?: string,\n surfaceId: string = DEFAULT_SURFACE_ID\n): ServerToClientMessage[] {\n const messages: ServerToClientMessage[] = [];\n\n for (const part of parts) {\n if (part.kind === \"text\") {\n // For text-content events or regular text parts, convert text to A2UI\n messages.push(textPartToA2UI(part.text, surfaceId));\n } else if (part.kind === \"file\" && \"file\" in part) {\n const file = part.file as {\n bytes?: string;\n uri?: string;\n mimeType?: string;\n name?: string;\n };\n const a2uiMsg = filePartToA2UI(file, surfaceId);\n if (a2uiMsg) {\n messages.push(a2uiMsg);\n }\n } else if (part.kind === \"data\") {\n const data = part.data as Record<string, unknown>;\n\n if (part.metadata?.mimeType === A2UI_MIME_TYPE) {\n messages.push(data as ServerToClientMessage);\n } else if (coderAgentKind === CODER_AGENT_EVENT.THOUGHT) {\n const thought = data as { subject?: string; description?: string };\n if (thought.subject) {\n const a2uiMsg = thoughtToA2UI(thought, surfaceId);\n if (a2uiMsg) {\n messages.push(a2uiMsg);\n }\n } else if (thought.description) {\n messages.push(textPartToA2UI(thought.description, surfaceId));\n }\n } else if (\n coderAgentKind === CODER_AGENT_EVENT.TOOL_CALL_UPDATE ||\n coderAgentKind === CODER_AGENT_EVENT.TOOL_CALL_CONFIRMATION\n ) {\n const a2uiMsg = toolCallToA2UI(\n data as {\n request?: { name?: string; args?: Record<string, unknown> };\n status?: string;\n tool?: {\n name?: string;\n displayName?: string;\n description?: string;\n };\n response?: { content?: string };\n },\n surfaceId\n );\n if (a2uiMsg) {\n messages.push(a2uiMsg);\n }\n }\n // Note: TEXT_CONTENT events now use \"text\" parts (handled above), not \"data\" parts\n }\n }\n\n return messages;\n}\n\nfunction convertResponseToA2UI(response: SendStreamingMessageResponse): ServerToClientMessage[] {\n if (\"error\" in response) {\n return [];\n }\n\n const result = response.result;\n if (!result || !(\"kind\" in result) || result.kind !== \"status-update\") {\n return [];\n }\n\n const metadata = result.metadata as { coderAgent?: { kind?: string } } | undefined;\n const coderAgentKind = metadata?.coderAgent?.kind;\n\n // Skip state-change events without message content (submitted/working state transitions)\n if (coderAgentKind === CODER_AGENT_EVENT.STATE_CHANGE) {\n return [];\n }\n\n // Handle messages with parts (text, file, data, tool calls, thoughts, etc.)\n const parts = result.status?.message?.parts;\n if (!parts || parts.length === 0) {\n return [];\n }\n\n return convertA2APartsToA2UI(parts, coderAgentKind);\n}\n\n// ============ SSE Stream Handling ============\n\nasync function* parseSSEStream(\n streamResponse: StreamResponse\n): AsyncGenerator<SendStreamingMessageResponse, void, unknown> {\n const queue: SendStreamingMessageResponse[] = [];\n\n const parser = createParser({\n onEvent: (event) => {\n try {\n queue.push(JSON.parse(event.data));\n } catch (err) {\n console.error(\"[parseSSEStream] Parse error:\", err);\n // Ignore parse errors\n }\n },\n });\n\n try {\n while (true) {\n const chunk = await streamResponse.read();\n if (chunk === null) {\n break;\n }\n if (chunk) {\n parser.feed(chunk);\n while (queue.length > 0) {\n const item = queue.shift();\n if (item) {\n yield item;\n }\n }\n }\n }\n } catch (err) {\n console.error(\"[parseSSEStream] Stream error:\", err);\n // Ignore stream errors\n }\n}\n\n// ============ Client ============\n\nexport type CopilotA2UIClient = {\n /**\n * Stream A2UI messages from Copilot Agent.\n *\n * @example\n * ```typescript\n * import { createCopilotA2UIClient, Data } from \"@amaster.ai/copilot-client\";\n *\n * const client = createCopilotA2UIClient();\n * const processor = Data.createSignalA2uiMessageProcessor();\n *\n * for await (const messages of client.chat([{ role: \"user\", content: \"Hello\" }])) {\n * processor.processMessages(messages);\n * }\n * ```\n */\n chat(\n messages: ChatMessage[],\n options?: ChatOptions\n ): AsyncGenerator<ServerToClientMessage[], void, unknown>;\n\n cancelChat(taskId: string): Promise<ClientResult<CancelTaskResponse>>;\n getChatStatus(taskId: string): Promise<ClientResult<GetTaskResponse>>;\n};\n\n/**\n * Create Copilot A2UI client\n *\n * Auto-detects runtime environment (Browser/Vite/Taro H5/Taro Mini-program)\n */\nexport function createCopilotA2UIClient(\n http: HttpClient = createHttpClient(),\n baseUrl?: string,\n getAccessToken?: () => string | null\n): CopilotA2UIClient {\n let envBaseUrl = \"\";\n\n // Vite/H5:必须直接写 import.meta.env,Vite 才能正确处理\n const metaEnv = (import.meta as any)?.env;\n if (metaEnv) {\n envBaseUrl = metaEnv.TARO_APP_API_BASE_URL || metaEnv.VITE_API_BASE_URL || \"\";\n }\n\n // Taro 小程序 build:defineConstants 会把 process.env.xxx 替换为字面量\n // H5 环境:process 不存在会抛 ReferenceError,这里用 try/catch 吞掉\n if (!envBaseUrl) {\n try {\n envBaseUrl =\n process.env.TARO_APP_API_BASE_URL ||\n process.env.VITE_API_BASE_URL ||\n \"\";\n } catch {\n // process is not defined -> ignore\n }\n }\n\n envBaseUrl = String(envBaseUrl || \"\").trim();\n const url = `${baseUrl || envBaseUrl}/api/proxy/builtin/platform/copilot`;\n\n async function* sendMessageStream(\n request: SendStreamingMessageRequest\n ): AsyncGenerator<SendStreamingMessageResponse, void, unknown> {\n try {\n const streamResponse = await createStream(url, request, getAccessToken);\n\n if (!streamResponse.ok) {\n throw new Error(`Stream request failed: ${streamResponse.statusText}`);\n }\n\n yield* parseSSEStream(streamResponse);\n } catch (err) {\n console.error(\"[sendMessageStream] Error:\", err);\n // Ignore stream errors\n }\n }\n\n return {\n async *chat(messages, chatOptions = {}) {\n const { taskId } = chatOptions;\n\n const systemMsg = messages.find((m) => m.role === \"system\");\n const nonSystemMsgs = messages.filter((m) => m.role !== \"system\");\n const lastUserMsg = nonSystemMsgs[nonSystemMsgs.length - 1];\n\n const parts = lastUserMsg\n ? convertToA2AParts(lastUserMsg.content)\n : [{ kind: \"text\" as const, text: \"\" }];\n\n const systemPrompt = systemMsg ? extractTextFromContent(systemMsg.content) : undefined;\n\n const request: SendStreamingMessageRequest = {\n jsonrpc: \"2.0\",\n id: generateUUID(),\n method: \"message/stream\",\n params: {\n message: {\n contextId: getAppId(),\n kind: \"message\",\n messageId: generateUUID(),\n role: \"user\",\n parts,\n ...(taskId && { taskId }),\n ...(systemPrompt && { metadata: { systemPrompt } }),\n },\n },\n };\n\n for await (const response of sendMessageStream(request)) {\n const a2uiMessages = convertResponseToA2UI(response);\n if (a2uiMessages.length > 0) {\n yield a2uiMessages;\n }\n }\n },\n\n cancelChat(taskId) {\n const request: CancelTaskRequest = {\n jsonrpc: \"2.0\",\n id: generateUUID(),\n method: \"tasks/cancel\",\n params: { id: taskId },\n };\n return http.request<CancelTaskResponse>({\n url,\n method: \"POST\",\n data: request,\n });\n },\n\n getChatStatus(taskId) {\n const request: GetTaskRequest = {\n jsonrpc: \"2.0\",\n id: generateUUID(),\n method: \"tasks/get\",\n params: { id: taskId },\n };\n return http.request<GetTaskResponse>({\n url,\n method: \"POST\",\n data: request,\n });\n },\n };\n}\n","/**\n * A2UI Types - Inlined from @a2ui/lit for Taro compatibility\n *\n * This file contains the minimal A2UI type definitions needed by copilot-client.\n * We inline these types instead of importing from @a2ui/lit because @a2ui/lit\n * uses ES2025 `import ... with { type: \"json\" }` syntax which is not supported\n * by Taro's Vite/esbuild version.\n */\n\n// ============ Primitive Types ============\n\nexport interface StringValue {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n /** A fixed, hardcoded string value. */\n literalString?: string;\n /** A fixed, hardcoded string value. */\n literal?: string;\n}\n\nexport interface NumberValue {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n /** A fixed, hardcoded number value. */\n literalNumber?: number;\n /** A fixed, hardcoded number value. */\n literal?: number;\n}\n\nexport interface BooleanValue {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n /** A fixed, hardcoded boolean value. */\n literalBoolean?: boolean;\n /** A fixed, hardcoded boolean value. */\n literal?: boolean;\n}\n\n// ============ Component Types ============\n\nexport interface Action {\n /** A unique name identifying the action (e.g., 'submitForm'). */\n name: string;\n /** A key-value map of data bindings to be resolved when the action is triggered. */\n context?: {\n key: string;\n /** The dynamic value. Define EXACTLY ONE of the nested properties. */\n value: {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n /** A fixed, hardcoded string value. */\n literalString?: string;\n literalNumber?: number;\n literalBoolean?: boolean;\n };\n }[];\n}\n\nexport interface Text {\n text: StringValue;\n usageHint: \"h1\" | \"h2\" | \"h3\" | \"h4\" | \"h5\" | \"caption\" | \"body\";\n}\n\nexport interface Image {\n url: StringValue;\n usageHint: \"icon\" | \"avatar\" | \"smallFeature\" | \"mediumFeature\" | \"largeFeature\" | \"header\";\n fit?: \"contain\" | \"cover\" | \"fill\" | \"none\" | \"scale-down\";\n}\n\nexport interface Icon {\n name: StringValue;\n}\n\nexport interface Video {\n url: StringValue;\n}\n\nexport interface AudioPlayer {\n url: StringValue;\n /** A label, title, or placeholder text. */\n description?: StringValue;\n}\n\nexport interface Tabs {\n /** A list of tabs, each with a title and a child component ID. */\n tabItems: {\n /** The title of the tab. */\n title: {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n /** A fixed, hardcoded string value. */\n literalString?: string;\n };\n /** A reference to a component instance by its unique ID. */\n child: string;\n }[];\n}\n\nexport interface Divider {\n /** The orientation. */\n axis?: \"horizontal\" | \"vertical\";\n /** The color of the divider (e.g., hex code or semantic name). */\n color?: string;\n /** The thickness of the divider. */\n thickness?: number;\n}\n\nexport interface Modal {\n /** The ID of the component (e.g., a button) that triggers the modal. */\n entryPointChild: string;\n /** The ID of the component to display as the modal's content. */\n contentChild: string;\n}\n\nexport interface Button {\n /** The ID of the component to display as the button's content. */\n child: string;\n /** Represents a user-initiated action. */\n action: Action;\n}\n\nexport interface Checkbox {\n label: StringValue;\n value: {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n literalBoolean?: boolean;\n };\n}\n\nexport interface TextField {\n text?: StringValue;\n /** A label, title, or placeholder text. */\n label: StringValue;\n type?: \"shortText\" | \"number\" | \"date\" | \"longText\";\n /** A regex string to validate the input. */\n validationRegexp?: string;\n}\n\nexport interface DateTimeInput {\n value: StringValue;\n enableDate?: boolean;\n enableTime?: boolean;\n /** The string format for the output (e.g., 'YYYY-MM-DD'). */\n outputFormat?: string;\n}\n\nexport interface MultipleChoice {\n selections: {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n literalArray?: string[];\n };\n options?: {\n label: {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n /** A fixed, hardcoded string value. */\n literalString?: string;\n };\n value: string;\n }[];\n maxAllowedSelections?: number;\n}\n\nexport interface Slider {\n value: {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n literalNumber?: number;\n };\n minValue?: number;\n maxValue?: number;\n}\n\n// ============ Data Model Types ============\n\n/** A recursive type for any valid JSON-like value in the data model. */\nexport type DataValue = string | number | boolean | null | DataMap | DataObject | DataArray;\nexport type DataObject = { [key: string]: DataValue };\nexport type DataMap = Map<string, DataValue>;\nexport type DataArray = DataValue[];\n\n/** A template for creating components from a list in the data model. */\nexport interface ComponentArrayTemplate {\n componentId: string;\n dataBinding: string;\n}\n\n/** Defines a list of child components, either explicitly or via a template. */\nexport interface ComponentArrayReference {\n explicitList?: string[];\n template?: ComponentArrayTemplate;\n}\n\n/** Represents the general shape of a component's properties. */\nexport type ComponentProperties = {\n children?: ComponentArrayReference;\n child?: string;\n [k: string]: unknown;\n};\n\n/** A raw component instance from a SurfaceUpdate message. */\nexport interface ComponentInstance {\n id: string;\n weight?: number;\n component?: ComponentProperties;\n}\n\nexport type ValueMap = DataObject & {\n key: string;\n /** May be JSON */\n valueString?: string;\n valueNumber?: number;\n valueBoolean?: boolean;\n valueMap?: ValueMap[];\n};\n\n// ============ Message Types ============\n\nexport interface BeginRenderingMessage {\n surfaceId: string;\n root: string;\n styles?: Record<string, string>;\n}\n\nexport interface SurfaceUpdateMessage {\n surfaceId: string;\n components: ComponentInstance[];\n}\n\nexport interface DataModelUpdate {\n surfaceId: string;\n path?: string;\n contents: ValueMap[];\n}\n\nexport interface DeleteSurfaceMessage {\n surfaceId: string;\n}\n\nexport interface ServerToClientMessage {\n beginRendering?: BeginRenderingMessage;\n surfaceUpdate?: SurfaceUpdateMessage;\n dataModelUpdate?: DataModelUpdate;\n deleteSurface?: DeleteSurfaceMessage;\n}\n\n// ============ Component Node Types ============\n\n/** A recursive type for any value that can appear within a resolved component tree. */\nexport type ResolvedValue =\n | string\n | number\n | boolean\n | null\n | AnyComponentNode\n | ResolvedMap\n | ResolvedArray;\n\n/** A generic map where each value has been recursively resolved. */\nexport type ResolvedMap = { [key: string]: ResolvedValue };\n\n/** A generic array where each item has been recursively resolved. */\nexport type ResolvedArray = ResolvedValue[];\n\n/** A base interface that all component nodes share. */\ninterface BaseComponentNode {\n id: string;\n weight?: number;\n dataContextPath?: string;\n slotName?: string;\n}\n\nexport interface TextNode extends BaseComponentNode {\n type: \"Text\";\n properties: Text;\n}\n\nexport interface ImageNode extends BaseComponentNode {\n type: \"Image\";\n properties: Image;\n}\n\nexport interface IconNode extends BaseComponentNode {\n type: \"Icon\";\n properties: Icon;\n}\n\nexport interface VideoNode extends BaseComponentNode {\n type: \"Video\";\n properties: Video;\n}\n\nexport interface AudioPlayerNode extends BaseComponentNode {\n type: \"AudioPlayer\";\n properties: AudioPlayer;\n}\n\nexport interface RowNode extends BaseComponentNode {\n type: \"Row\";\n properties: ResolvedRow;\n}\n\nexport interface ColumnNode extends BaseComponentNode {\n type: \"Column\";\n properties: ResolvedColumn;\n}\n\nexport interface ListNode extends BaseComponentNode {\n type: \"List\";\n properties: ResolvedList;\n}\n\nexport interface CardNode extends BaseComponentNode {\n type: \"Card\";\n properties: ResolvedCard;\n}\n\nexport interface TabsNode extends BaseComponentNode {\n type: \"Tabs\";\n properties: ResolvedTabs;\n}\n\nexport interface DividerNode extends BaseComponentNode {\n type: \"Divider\";\n properties: Divider;\n}\n\nexport interface ModalNode extends BaseComponentNode {\n type: \"Modal\";\n properties: ResolvedModal;\n}\n\nexport interface ButtonNode extends BaseComponentNode {\n type: \"Button\";\n properties: ResolvedButton;\n}\n\nexport interface CheckboxNode extends BaseComponentNode {\n type: \"CheckBox\";\n properties: Checkbox;\n}\n\nexport interface TextFieldNode extends BaseComponentNode {\n type: \"TextField\";\n properties: TextField;\n}\n\nexport interface DateTimeInputNode extends BaseComponentNode {\n type: \"DateTimeInput\";\n properties: DateTimeInput;\n}\n\nexport interface MultipleChoiceNode extends BaseComponentNode {\n type: \"MultipleChoice\";\n properties: MultipleChoice;\n}\n\nexport interface SliderNode extends BaseComponentNode {\n type: \"Slider\";\n properties: Slider;\n}\n\nexport interface CustomNode extends BaseComponentNode {\n type: string;\n properties: CustomNodeProperties;\n}\n\n/**\n * The complete discriminated union of all possible resolved component nodes.\n * A renderer would use this type for any given node in the component tree.\n */\nexport type AnyComponentNode =\n | TextNode\n | IconNode\n | ImageNode\n | VideoNode\n | AudioPlayerNode\n | RowNode\n | ColumnNode\n | ListNode\n | CardNode\n | TabsNode\n | DividerNode\n | ModalNode\n | ButtonNode\n | CheckboxNode\n | TextFieldNode\n | DateTimeInputNode\n | MultipleChoiceNode\n | SliderNode\n | CustomNode;\n\nexport interface ResolvedRow {\n children: AnyComponentNode[];\n distribution?: \"start\" | \"center\" | \"end\" | \"spaceBetween\" | \"spaceAround\" | \"spaceEvenly\";\n alignment?: \"start\" | \"center\" | \"end\" | \"stretch\";\n}\n\nexport interface ResolvedColumn {\n children: AnyComponentNode[];\n distribution?: \"start\" | \"center\" | \"end\" | \"spaceBetween\" | \"spaceAround\" | \"spaceEvenly\";\n alignment?: \"start\" | \"center\" | \"end\" | \"stretch\";\n}\n\nexport interface ResolvedButton {\n child: AnyComponentNode;\n action: Button[\"action\"];\n}\n\nexport interface ResolvedList {\n children: AnyComponentNode[];\n direction?: \"vertical\" | \"horizontal\";\n alignment?: \"start\" | \"center\" | \"end\" | \"stretch\";\n}\n\nexport interface ResolvedCard {\n child: AnyComponentNode;\n children: AnyComponentNode[];\n}\n\nexport interface ResolvedTabItem {\n title: StringValue;\n child: AnyComponentNode;\n}\n\nexport interface ResolvedTabs {\n tabItems: ResolvedTabItem[];\n}\n\nexport interface ResolvedModal {\n entryPointChild: AnyComponentNode;\n contentChild: AnyComponentNode;\n}\n\nexport interface CustomNodeProperties {\n [k: string]: ResolvedValue;\n}\n\nexport type SurfaceID = string;\n\n/** The complete state of a single UI surface. */\nexport interface Surface {\n rootComponentId: string | null;\n componentTree: AnyComponentNode | null;\n dataModel: DataMap;\n components: Map<string, ComponentInstance>;\n styles: Record<string, string>;\n}\n\n// ============ MessageProcessor Interface ============\n\nexport interface MessageProcessor {\n getSurfaces(): ReadonlyMap<string, Surface>;\n clearSurfaces(): void;\n processMessages(messages: ServerToClientMessage[]): void;\n /**\n * Retrieves the data for a given component node and a relative path string.\n * This correctly handles the special `.` path, which refers to the node's\n * own data context.\n */\n getData(node: AnyComponentNode, relativePath: string, surfaceId: string): DataValue | null;\n setData(\n node: AnyComponentNode | null,\n relativePath: string,\n value: DataValue,\n surfaceId: string\n ): void;\n resolvePath(path: string, dataContextPath?: string): string;\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -490,6 +490,6 @@ type CopilotA2UIClient = {
490
490
  *
491
491
  * Auto-detects runtime environment (Browser/Vite/Taro H5/Taro Mini-program)
492
492
  */
493
- declare function createCopilotA2UIClient(http?: HttpClient): CopilotA2UIClient;
493
+ declare function createCopilotA2UIClient(http?: HttpClient, baseUrl?: string, getAccessToken?: () => string | null): CopilotA2UIClient;
494
494
 
495
495
  export { a2uiTypes as A2UITypes, type ChatMessage, type ChatOptions, type CopilotA2UIClient, type FileContent, type ImageContent, type MessageContent, type MessageProcessor, type ServerToClientMessage, type Surface, type TextContent, createCopilotA2UIClient };
package/dist/index.d.ts CHANGED
@@ -490,6 +490,6 @@ type CopilotA2UIClient = {
490
490
  *
491
491
  * Auto-detects runtime environment (Browser/Vite/Taro H5/Taro Mini-program)
492
492
  */
493
- declare function createCopilotA2UIClient(http?: HttpClient): CopilotA2UIClient;
493
+ declare function createCopilotA2UIClient(http?: HttpClient, baseUrl?: string, getAccessToken?: () => string | null): CopilotA2UIClient;
494
494
 
495
495
  export { a2uiTypes as A2UITypes, type ChatMessage, type ChatOptions, type CopilotA2UIClient, type FileContent, type ImageContent, type MessageContent, type MessageProcessor, type ServerToClientMessage, type Surface, type TextContent, createCopilotA2UIClient };
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- import {createHttpClient}from'@amaster.ai/http-client';import {createParser}from'eventsource-parser';var a=globalThis;function N(){return typeof a?.Taro?.request=="function"?a.Taro.request.bind(a.Taro):typeof a?.wx?.request=="function"?a.wx.request.bind(a.wx):typeof a?.tt?.request=="function"?a.tt.request.bind(a.tt):typeof a?.my?.request=="function"?a.my.request.bind(a.my):typeof a?.swan?.request=="function"?a.swan.request.bind(a.swan):typeof a?.qq?.request=="function"?a.qq.request.bind(a.qq):typeof a?.jd?.request=="function"?a.jd.request.bind(a.jd):null}function m(){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?e.randomUUID():e&&typeof e.getRandomValues=="function"?"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let n=(e.getRandomValues(new Uint8Array(1))[0]??0)%16;return (t==="x"?n:n&3|8).toString(16)}):"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let o=Math.random()*16|0;return (t==="x"?o:o&3|8).toString(16)})}function b(){if(typeof window>"u")return null;try{let e=window.location.href,t=/\/app\/([\da-f-]+)(?:\/|$)/.exec(e);if(t?.[1])return t[1];let o=window.location.hostname,n=/^www\.([\da-f-]+)(?:-[^.]+)?\.[\w-]+\.(?:local|ai|cn)$/.exec(o);if(n?.[1])return n[1];let r=/^([\da-f-]+)(?:-[^.]+)?\.[\w-]+\.(?:local|ai|cn)$/.exec(o);return r?.[1]?r[1]:null}catch{return null}}var C=null;function M(){let e=b();return e||(C||(C=m()),C)}async function v(e,t){let o=N();if(o)return new Promise(s=>{let i="",c=false,u=false,g=0,y={url:e,method:"POST",header:{"Content-Type":"application/json",Accept:"text/event-stream"},data:t,timeout:6e4,success:l=>{i=typeof l.data=="string"?l.data:JSON.stringify(l.data),c=true;},fail:()=>{u=true,c=true;}};try{let l=o(y);l&&typeof l.then=="function"&&l.then(d=>{i=typeof d.data=="string"?d.data:JSON.stringify(d.data),c=!0;}).catch(()=>{u=!0,c=!0;});}catch{u=true,c=true;}s({ok:true,statusText:"OK",read:async()=>{for(;!c&&g>=i.length;)await new Promise(d=>setTimeout(d,50));if(u)return null;if(g>=i.length)return c?null:"";let l=i.slice(g);return g=i.length,l}});});let n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(t)});if(!n.body)return {ok:n.ok,statusText:n.statusText,read:async()=>null};let r=n.body.getReader(),p=new TextDecoder;return {ok:n.ok,statusText:n.statusText,read:async()=>{let{done:s,value:i}=await r.read();return s?null:p.decode(i,{stream:true})}}}function R(e){return typeof e=="string"?[{kind:"text",text:e}]:e.map(t=>{switch(t.type){case "text":return {kind:"text",text:t.text};case "image":return t.data?{kind:"file",file:{bytes:t.data,mimeType:t.mimeType||"image/png"}}:t.url?{kind:"file",file:{uri:t.url,mimeType:t.mimeType||"image/png"}}:null;case "file":return t.data?{kind:"file",file:{bytes:t.data,...t.mimeType&&{mimeType:t.mimeType},...t.name&&{name:t.name}}}:t.url?{kind:"file",file:{uri:t.url,...t.mimeType&&{mimeType:t.mimeType},...t.name&&{name:t.name}}}:null;default:return null}}).filter(t=>t!==null)}function A(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join(`
2
- `)}var I="application/json+a2ui",k="main",w=0;function f(e){return `${e}-${++w}`}function h(e,t){let o=f("text");return {surfaceUpdate:{surfaceId:t,components:[{id:o,component:{Text:{text:{literalString:e},usageHint:"body"}}}]}}}function D(e,t){let o=e.mimeType||"";if(!o.startsWith("image/"))return null;let n=f("image"),r=e.uri||(e.bytes?`data:${o};base64,${e.bytes}`:null);return r?{surfaceUpdate:{surfaceId:t,components:[{id:n,component:{Image:{url:{literalString:r}}}}]}}:null}function P(e,t){if(!e.subject&&!e.description)return null;let o=f("thought"),n=[];n.push({id:o,component:{Card:{child:`${o}-content`}}});let r=[];return e.subject&&r.push(`${o}-subject`),e.description&&r.push(`${o}-desc`),n.push({id:`${o}-content`,component:{Column:{children:{explicitList:r}}}}),e.subject&&n.push({id:`${o}-subject`,component:{Text:{text:{literalString:`\u{1F4AD} ${e.subject}`},usageHint:"h4"}}}),e.description&&n.push({id:`${o}-desc`,component:{Text:{text:{literalString:e.description},usageHint:"caption"}}}),{surfaceUpdate:{surfaceId:t,components:n}}}function V(e){switch(e){case "success":case "completed":return {icon:"check_circle",text:"\u2713 Completed"};case "failed":case "error":return {icon:"error",text:"\u2717 Failed"};case "validating":return {icon:"rule",text:"\u{1F50D} Validating..."};case "scheduled":return {icon:"schedule",text:"\u{1F4CB} Scheduled..."};case "executing":return {icon:"play_circle",text:"\u25B6\uFE0F Executing..."};case "pending":return {icon:"hourglass_empty",text:"\u23F3 Pending..."};default:return {icon:"build",text:"\u2699\uFE0F Running..."}}}function q(e,t){let o=e.tool?.displayName||e.tool?.name||e.request?.name||"Tool",n=e.status||"running",{icon:r,text:p}=V(n),s=f("tool"),i=[];i.push({id:s,component:{Card:{child:`${s}-row`}}}),i.push({id:`${s}-row`,component:{Row:{alignment:"center",children:{explicitList:[`${s}-icon`,`${s}-info`]}}}}),i.push({id:`${s}-icon`,component:{Icon:{name:{literalString:r}}}});let c=[`${s}-name`,`${s}-status`];if(e.resultDisplay&&(n==="success"||n==="completed")&&c.push(`${s}-result`),i.push({id:`${s}-info`,component:{Column:{children:{explicitList:c}}}}),i.push({id:`${s}-name`,component:{Text:{text:{literalString:o},usageHint:"body"}}}),i.push({id:`${s}-status`,component:{Text:{text:{literalString:p},usageHint:"caption"}}}),e.resultDisplay&&(n==="success"||n==="completed")){let u=e.resultDisplay.length>200?e.resultDisplay.slice(0,200)+"...":e.resultDisplay;i.push({id:`${s}-result`,component:{Text:{text:{literalString:u},usageHint:"caption"}}});}return {surfaceUpdate:{surfaceId:t,components:i}}}var x={THOUGHT:"thought",TOOL_CALL_UPDATE:"tool-call-update",TOOL_CALL_CONFIRMATION:"tool-call-confirmation",STATE_CHANGE:"state-change"};function U(e,t,o=k){let n=[];for(let r of e)if(r.kind==="text")n.push(h(r.text,o));else if(r.kind==="file"&&"file"in r){let p=r.file,s=D(p,o);s&&n.push(s);}else if(r.kind==="data"){let p=r.data;if(r.metadata?.mimeType===I)n.push(p);else if(t===x.THOUGHT){let s=p;if(s.subject){let i=P(s,o);i&&n.push(i);}else s.description&&n.push(h(s.description,o));}else if(t===x.TOOL_CALL_UPDATE||t===x.TOOL_CALL_CONFIRMATION){let s=q(p,o);s&&n.push(s);}}return n}function B(e){if("error"in e)return [];let t=e.result;if(!t||!("kind"in t)||t.kind!=="status-update")return [];let n=t.metadata?.coderAgent?.kind;if(n===x.STATE_CHANGE)return [];let r=t.status?.message?.parts;return !r||r.length===0?[]:U(r,n)}async function*O(e){let t=[],o=createParser({onEvent:n=>{try{t.push(JSON.parse(n.data));}catch{}}});try{for(;;){let n=await e.read();if(n===null)break;if(n)for(o.feed(n);t.length>0;){let r=t.shift();r&&(yield r);}}}catch{}}function j(e=createHttpClient()){let t="/api/proxy/builtin/platform/copilot";async function*o(n){try{let r=await v(t,n);if(!r.ok)throw new Error(`Stream request failed: ${r.statusText}`);yield*O(r);}catch{}}return {async*chat(n,r={}){let{taskId:p}=r,s=n.find(l=>l.role==="system"),i=n.filter(l=>l.role!=="system"),c=i[i.length-1],u=c?R(c.content):[{kind:"text",text:""}],g=s?A(s.content):void 0,y={jsonrpc:"2.0",id:m(),method:"message/stream",params:{message:{contextId:M(),kind:"message",messageId:m(),role:"user",parts:u,...p&&{taskId:p},...g&&{metadata:{systemPrompt:g}}}}};for await(let l of o(y)){let d=B(l);d.length>0&&(yield d);}},cancelChat(n){let r={jsonrpc:"2.0",id:m(),method:"tasks/cancel",params:{id:n}};return e.request({url:t,method:"POST",data:r})},getChatStatus(n){let r={jsonrpc:"2.0",id:m(),method:"tasks/get",params:{id:n}};return e.request({url:t,method:"POST",data:r})}}}var $={};export{$ as A2UITypes,j as createCopilotA2UIClient};//# sourceMappingURL=index.js.map
1
+ import {createHttpClient}from'@amaster.ai/http-client';import {createParser}from'eventsource-parser';import k from'miniprogram-text-decoder';import I from'miniprogram-text-encoder';var l=globalThis;function P(){return typeof l?.Taro?.request=="function"?l.Taro.request.bind(l.Taro):typeof l?.wx?.request=="function"?l.wx.request.bind(l.wx):typeof l?.tt?.request=="function"?l.tt.request.bind(l.tt):typeof l?.my?.request=="function"?l.my.request.bind(l.my):typeof l?.swan?.request=="function"?l.swan.request.bind(l.swan):typeof l?.qq?.request=="function"?l.qq.request.bind(l.qq):typeof l?.jd?.request=="function"?l.jd.request.bind(l.jd):null}function T(){let e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?e.randomUUID():e&&typeof e.getRandomValues=="function"?"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let n=(e.getRandomValues(new Uint8Array(1))[0]??0)%16;return (t==="x"?n:n&3|8).toString(16)}):"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let o=Math.random()*16|0;return (t==="x"?o:o&3|8).toString(16)})}function D(){if(typeof window>"u")return null;try{let e=window.location.href,t=/\/app\/([\da-f-]+)(?:\/|$)/.exec(e);if(t?.[1])return t[1];let o=window.location.hostname,n=/^www\.([\da-f-]+)(?:-[^.]+)?\.[\w-]+\.(?:local|ai|cn)$/.exec(o);if(n?.[1])return n[1];let r=/^([\da-f-]+)(?:-[^.]+)?\.[\w-]+\.(?:local|ai|cn)$/.exec(o);return r?.[1]?r[1]:null}catch{return null}}var R=null;function U(){let e=D();return e||(R||(R=T()),R)}async function q(e,t,o={}){return new Promise(n=>{let r=new Uint8Array(0),u=new k("utf-8",{fatal:false}),s=false,i=false,c=[],d=null,y=()=>new Promise(p=>{c.length>0?p(c.shift()):s?p(null):d=p;}),g=p=>{p&&(c.push(p),d&&(d(c.shift()),d=null));},m=p=>{if(!(i||s||!p.data))try{let a=new Uint8Array(p.data),f=new Uint8Array(r.length+a.length);f.set(r),f.set(a,r.length),r=f;let C=0;for(;C<r.length;){let v=r.subarray(C),b=u.decode(v,{stream:!1});if(b)g(b),C+=new I().encode(b).length;else break}C<r.length?r=r.subarray(C):r=new Uint8Array(0);}catch(a){console.error("[mini stream] chunk process error:",a);}},h=p=>{p.header?.["content-type"]?.includes("text/event-stream")===false&&console.warn("Warning: server did not return event-stream");},x=l.wx.request.bind(l.wx);try{let p=x({url:e,method:"POST",header:{"Content-Type":"application/json",Accept:"text/event-stream",...o},data:typeof t=="string"?t:JSON.stringify(t),responseType:"arraybuffer",enableChunked:!0,timeout:3e5,success:()=>{if(r.length>0){let a=u.decode(r,{stream:!0});g(a);}s=!0,d&&d(null);},fail:a=>{console.error("[mini stream] request fail:",a),i=!0,s=!0,d&&d(null);}});p.onChunkReceived?.(m),p.onHeadersReceived?.(h),n({ok:!0,statusText:"OK",read:async()=>i?null:y()});}catch(p){console.error("miniReq error",p);}})}async function B(e,t,o){let n=o?.(),r=n?{Authorization:`Bearer ${n}`}:{};if(typeof l?.wx?.request=="function")return q(e,t,r);let u=P();if(u)return new Promise(y=>{let g="",m=false,h=false,x=0,p={url:e,method:"POST",header:{"Content-Type":"application/json",Accept:"text/event-stream",...r},data:typeof t=="string"?t:JSON.stringify(t),timeout:6e4,success:a=>{g=typeof a.data=="string"?a.data:JSON.stringify(a.data),m=true;},fail:a=>{console.error("[createStream] wx.request failed:",a),h=true,m=true;},complete:()=>{}};try{let a=u(p);a&&typeof a.then=="function"&&a.then(f=>{g=typeof f.data=="string"?f.data:JSON.stringify(f.data),m=!0;}).catch(()=>{h=!0,m=!0;});}catch(a){console.error("[createStream] Exception:",a),h=true,m=true;}y({ok:true,statusText:"OK",read:async()=>{for(;!m&&x>=g.length;)await new Promise(f=>setTimeout(f,50));if(h)return null;if(x>=g.length)return m?null:"";let a=g.slice(x);return x=g.length,a}});});let s={"Content-Type":"application/json",...r},i=await fetch(e,{method:"POST",headers:s,credentials:"include",body:JSON.stringify(t)});if(!i.body)return {ok:i.ok,statusText:i.statusText,read:async()=>null};let c=i.body.getReader(),d=new TextDecoder;return {ok:i.ok,statusText:i.statusText,read:async()=>{let{done:y,value:g}=await c.read();return y?null:d.decode(g,{stream:true})}}}function V(e){return typeof e=="string"?[{kind:"text",text:e}]:e.map(t=>{switch(t.type){case "text":return {kind:"text",text:t.text};case "image":return t.data?{kind:"file",file:{bytes:t.data,mimeType:t.mimeType||"image/png"}}:t.url?{kind:"file",file:{uri:t.url,mimeType:t.mimeType||"image/png"}}:null;case "file":return t.data?{kind:"file",file:{bytes:t.data,...t.mimeType&&{mimeType:t.mimeType},...t.name&&{name:t.name}}}:t.url?{kind:"file",file:{uri:t.url,...t.mimeType&&{mimeType:t.mimeType},...t.name&&{name:t.name}}}:null;default:return null}}).filter(t=>t!==null)}function O(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join(`
2
+ `)}var _="application/json+a2ui",E="main",L=0;function N(e){return `${e}-${++L}`}function A(e,t){let o=N("text");return {surfaceUpdate:{surfaceId:t,components:[{id:o,component:{Text:{text:{literalString:e},usageHint:"body"}}}]}}}function $(e,t){let o=e.mimeType||"";if(!o.startsWith("image/"))return null;let n=N("image"),r=e.uri||(e.bytes?`data:${o};base64,${e.bytes}`:null);return r?{surfaceUpdate:{surfaceId:t,components:[{id:n,component:{Image:{url:{literalString:r}}}}]}}:null}function j(e,t){if(!e.subject&&!e.description)return null;let o=N("thought"),n=[];n.push({id:o,component:{Card:{child:`${o}-content`}}});let r=[];return e.subject&&r.push(`${o}-subject`),e.description&&r.push(`${o}-desc`),n.push({id:`${o}-content`,component:{Column:{children:{explicitList:r}}}}),e.subject&&n.push({id:`${o}-subject`,component:{Text:{text:{literalString:`\u{1F4AD} ${e.subject}`},usageHint:"h4"}}}),e.description&&n.push({id:`${o}-desc`,component:{Text:{text:{literalString:e.description},usageHint:"caption"}}}),{surfaceUpdate:{surfaceId:t,components:n}}}function F(e){switch(e){case "success":case "completed":return {icon:"check_circle",text:"\u2713 Completed",status:e};case "failed":case "error":return {icon:"error",text:"\u2717 Failed",status:e};case "validating":return {icon:"rule",text:"\u{1F50D} Validating...",status:e};case "scheduled":return {icon:"schedule",text:"\u{1F4CB} Scheduled...",status:e};case "executing":return {icon:"play_circle",text:"\u25B6\uFE0F Executing...",status:e};case "pending":return {icon:"hourglass_empty",text:"\u23F3 Pending...",status:e};default:return {icon:"build",text:"\u2699\uFE0F Running...",status:e}}}function H(e,t){let o=e.tool?.displayName||e.tool?.name||e.request?.name||"Tool",n=e.status||"running",{icon:r,text:u}=F(n),s=N("tool"),i=[];i.push({id:s,component:{Card:{child:`${s}-row`}}}),i.push({id:`${s}-row`,component:{Row:{alignment:"center",children:{explicitList:[`${s}-icon`,`${s}-info`]}}}}),i.push({id:`${s}-icon`,component:{Icon:{name:{literalString:r}}}});let c=[`${s}-name`,`${s}-status`];if(e.resultDisplay&&(n==="success"||n==="completed")&&c.push(`${s}-result`),i.push({id:`${s}-info`,component:{Column:{children:{explicitList:c}}}}),i.push({id:`${s}-name`,component:{Text:{text:{literalString:o},usageHint:"body"}}}),i.push({id:`${s}-status`,component:{Text:{text:{literalString:u},usageHint:"caption"}}}),e.resultDisplay&&(n==="success"||n==="completed")){let d=e.resultDisplay.length>200?e.resultDisplay.slice(0,200)+"...":e.resultDisplay;i.push({id:`${s}-result`,component:{Text:{text:{literalString:d},usageHint:"caption"}}});}return {surfaceUpdate:{surfaceId:t,components:i}}}var S={THOUGHT:"thought",TOOL_CALL_UPDATE:"tool-call-update",TOOL_CALL_CONFIRMATION:"tool-call-confirmation",STATE_CHANGE:"state-change"};function G(e,t,o=E){let n=[];for(let r of e)if(r.kind==="text")n.push(A(r.text,o));else if(r.kind==="file"&&"file"in r){let u=r.file,s=$(u,o);s&&n.push(s);}else if(r.kind==="data"){let u=r.data;if(r.metadata?.mimeType===_)n.push(u);else if(t===S.THOUGHT){let s=u;if(s.subject){let i=j(s,o);i&&n.push(i);}else s.description&&n.push(A(s.description,o));}else if(t===S.TOOL_CALL_UPDATE||t===S.TOOL_CALL_CONFIRMATION){let s=H(u,o);s&&n.push(s);}}return n}function J(e){if("error"in e)return [];let t=e.result;if(!t||!("kind"in t)||t.kind!=="status-update")return [];let n=t.metadata?.coderAgent?.kind;if(n===S.STATE_CHANGE)return [];let r=t.status?.message?.parts;return !r||r.length===0?[]:G(r,n)}async function*z(e){let t=[],o=createParser({onEvent:n=>{try{t.push(JSON.parse(n.data));}catch(r){console.error("[parseSSEStream] Parse error:",r);}}});try{for(;;){let n=await e.read();if(n===null)break;if(n)for(o.feed(n);t.length>0;){let r=t.shift();r&&(yield r);}}}catch(n){console.error("[parseSSEStream] Stream error:",n);}}function W(e=createHttpClient(),t,o){let n="",r=import.meta?.env;if(r&&(n=r.TARO_APP_API_BASE_URL||r.VITE_API_BASE_URL||""),!n)try{n=process.env.TARO_APP_API_BASE_URL||process.env.VITE_API_BASE_URL||"";}catch{}n=String(n||"").trim();let u=`${t||n}/api/proxy/builtin/platform/copilot`;async function*s(i){try{let c=await B(u,i,o);if(!c.ok)throw new Error(`Stream request failed: ${c.statusText}`);yield*z(c);}catch(c){console.error("[sendMessageStream] Error:",c);}}return {async*chat(i,c={}){let{taskId:d}=c,y=i.find(a=>a.role==="system"),g=i.filter(a=>a.role!=="system"),m=g[g.length-1],h=m?V(m.content):[{kind:"text",text:""}],x=y?O(y.content):void 0,p={jsonrpc:"2.0",id:T(),method:"message/stream",params:{message:{contextId:U(),kind:"message",messageId:T(),role:"user",parts:h,...d&&{taskId:d},...x&&{metadata:{systemPrompt:x}}}}};for await(let a of s(p)){let f=J(a);f.length>0&&(yield f);}},cancelChat(i){let c={jsonrpc:"2.0",id:T(),method:"tasks/cancel",params:{id:i}};return e.request({url:u,method:"POST",data:c})},getChatStatus(i){let c={jsonrpc:"2.0",id:T(),method:"tasks/get",params:{id:i}};return e.request({url:u,method:"POST",data:c})}}}var K={};export{K as A2UITypes,W as createCopilotA2UIClient};//# sourceMappingURL=index.js.map
3
3
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/copilot-a2ui-client.ts","../src/a2ui-types.ts"],"names":["g","getMiniProgramRequest","generateUUID","cryptoObj","c","r","extractAppIdFromUrl","url","pathMatch","hostname","wwwMatch","domainMatch","cachedAppId","getAppId","urlAppId","createStream","data","miniReq","resolve","buffer","completed","failed","position","opts","res","ret","chunk","response","reader","decoder","done","value","convertToA2AParts","content","part","extractTextFromContent","A2UI_MIME_TYPE","DEFAULT_SURFACE_ID","componentIdCounter","generateComponentId","prefix","textPartToA2UI","text","surfaceId","componentId","filePartToA2UI","file","mimeType","thoughtToA2UI","thought","baseId","components","childrenList","getToolStatusDisplay","status","toolCallToA2UI","toolCall","toolName","iconName","statusText","infoChildren","resultPreview","CODER_AGENT_EVENT","convertA2APartsToA2UI","parts","coderAgentKind","messages","a2uiMsg","convertResponseToA2UI","result","parseSSEStream","streamResponse","queue","parser","createParser","event","item","createCopilotA2UIClient","http","createHttpClient","baseUrl","sendMessageStream","request","chatOptions","taskId","systemMsg","m","nonSystemMsgs","lastUserMsg","systemPrompt","a2uiMessages","a2ui_types_exports"],"mappings":"qGAoBA,IAAMA,CAAAA,CAAI,UAAA,CAEV,SAASC,CAAAA,EAAsD,CAC7D,OAAI,OAAOD,CAAAA,EAAG,MAAM,OAAA,EAAY,UAAA,CAAmBA,CAAAA,CAAE,IAAA,CAAK,QAAQ,IAAA,CAAKA,CAAAA,CAAE,IAAI,CAAA,CACzE,OAAOA,CAAAA,EAAG,EAAA,EAAI,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AA,CAAWW,CAAAA,EAAS,CACpB,IAAA,CAAM,SAAA,CACN,SAAA,CAAWX,CAAAA,EAAa,CACxB,IAAA,CAAM,MAAA,CACN,KAAA,CAAA8D,CAAAA,CACA,GAAIoB,CAAAA,EAAU,CAAE,MAAA,CAAAA,CAAO,CAAA,CACvB,GAAIK,CAAAA,EAAgB,CAAE,QAAA,CAAU,CAAE,YAAA,CAAAA,CAAa,CAAE,CACnD,CACF,CACF,EAEA,UAAA,IAAiB9D,CAAAA,IAAYsD,CAAAA,CAAkBC,CAAO,CAAA,CAAG,CACvD,IAAMQ,CAAAA,CAAetB,CAAAA,CAAsBzC,CAAQ,CAAA,CAC/C+D,CAAAA,CAAa,MAAA,CAAS,CAAA,GACxB,MAAMA,CAAAA,EAEV,CACF,CAAA,CAEA,UAAA,CAAWN,CAAAA,CAAQ,CACjB,IAAMF,CAAAA,CAA6B,CACjC,OAAA,CAAS,KAAA,CACT,EAAA,CAAIhF,CAAAA,EAAa,CACjB,MAAA,CAAQ,cAAA,CACR,MAAA,CAAQ,CAAE,GAAIkF,CAAO,CACvB,CAAA,CACA,OAAON,CAAAA,CAAK,OAAA,CAA4B,CACtC,GAAA,CAAKE,CAAAA,CACL,MAAA,CAAQ,MAAA,CACR,IAAA,CAAME,CACR,CAAC,CACH,CAAA,CAEA,cAAcE,CAAAA,CAAQ,CACpB,IAAMF,CAAAA,CAA0B,CAC9B,OAAA,CAAS,KAAA,CACT,EAAA,CAAIhF,CAAAA,EAAa,CACjB,MAAA,CAAQ,WAAA,CACR,MAAA,CAAQ,CAAE,EAAA,CAAIkF,CAAO,CACvB,CAAA,CACA,OAAON,CAAAA,CAAK,OAAA,CAAyB,CACnC,GAAA,CAAKE,CAAAA,CACL,MAAA,CAAQ,MAAA,CACR,IAAA,CAAME,CACR,CAAC,CACH,CACF,CACF,KC3xBAS,CAAAA,CAAA","file":"index.js","sourcesContent":["/* eslint-disable no-undef, no-unused-vars */\nimport type {\n CancelTaskRequest,\n CancelTaskResponse,\n GetTaskRequest,\n GetTaskResponse,\n Part,\n SendStreamingMessageRequest,\n SendStreamingMessageResponse,\n} from \"@a2a-js/sdk\";\nimport { type ClientResult, createHttpClient, type HttpClient } from \"@amaster.ai/http-client\";\nimport { createParser } from \"eventsource-parser\";\nimport type { ServerToClientMessage, Surface, MessageProcessor } from \"./a2ui-types.js\";\n\n// Re-export A2UI types from local definitions\nexport type { ServerToClientMessage, Surface, MessageProcessor };\n\n// ============ Internal: Platform Detection (same as http-client) ============\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst g = globalThis as any;\n\nfunction getMiniProgramRequest(): ((_opts: any) => any) | null {\n if (typeof g?.Taro?.request === \"function\") return g.Taro.request.bind(g.Taro);\n if (typeof g?.wx?.request === \"function\") return g.wx.request.bind(g.wx);\n if (typeof g?.tt?.request === \"function\") return g.tt.request.bind(g.tt);\n if (typeof g?.my?.request === \"function\") return g.my.request.bind(g.my);\n if (typeof g?.swan?.request === \"function\") return g.swan.request.bind(g.swan);\n if (typeof g?.qq?.request === \"function\") return g.qq.request.bind(g.qq);\n if (typeof g?.jd?.request === \"function\") return g.jd.request.bind(g.jd);\n return null;\n}\n\n// ============ Internal: UUID Generator ============\n\nfunction generateUUID(): string {\n const cryptoObj = typeof globalThis !== \"undefined\" ? globalThis.crypto : undefined;\n\n if (cryptoObj && typeof cryptoObj.randomUUID === \"function\") {\n return cryptoObj.randomUUID();\n }\n\n if (cryptoObj && typeof cryptoObj.getRandomValues === \"function\") {\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n const randomValues = cryptoObj.getRandomValues(new Uint8Array(1));\n const r = (randomValues[0] ?? 0) % 16;\n const v = c === \"x\" ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n }\n\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === \"x\" ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n// ============ Internal: URL Utilities ============\n\nfunction extractAppIdFromUrl(): string | null {\n if (typeof window === \"undefined\") return null;\n\n try {\n const url = window.location.href;\n const pathMatch = /\\/app\\/([\\da-f-]+)(?:\\/|$)/.exec(url);\n if (pathMatch?.[1]) return pathMatch[1];\n\n const hostname = window.location.hostname;\n\n // Pattern 1: www.{app_id}.domain.tld or www.{app_id}-{env}.domain.tld\n const wwwMatch = /^www\\.([\\da-f-]+)(?:-[^.]+)?\\.[\\w-]+\\.(?:local|ai|cn)$/.exec(hostname);\n if (wwwMatch?.[1]) return wwwMatch[1];\n\n // Pattern 2: {app_id}-{env}.domain.tld or {app_id}.domain.tld\n const domainMatch = /^([\\da-f-]+)(?:-[^.]+)?\\.[\\w-]+\\.(?:local|ai|cn)$/.exec(hostname);\n if (domainMatch?.[1]) return domainMatch[1];\n\n return null;\n } catch {\n return null;\n }\n}\n\n// Cache appId for session consistency\nlet cachedAppId: string | null = null;\n\nfunction getAppId(): string {\n const urlAppId = extractAppIdFromUrl();\n if (urlAppId) return urlAppId;\n if (!cachedAppId) cachedAppId = generateUUID();\n return cachedAppId;\n}\n\n// ============ Internal: Streaming ============\n\ninterface StreamResponse {\n ok: boolean;\n statusText: string;\n read(): Promise<string | null>;\n}\n\nasync function createStream(url: string, data: unknown): Promise<StreamResponse> {\n const miniReq = getMiniProgramRequest();\n\n if (miniReq) {\n // Mini-program: buffer full response\n return new Promise((resolve) => {\n let buffer = \"\";\n let completed = false;\n let failed = false;\n let position = 0;\n\n const opts = {\n url,\n method: \"POST\",\n header: { \"Content-Type\": \"application/json\", Accept: \"text/event-stream\" },\n data,\n timeout: 60000,\n success: (res: any) => {\n buffer = typeof res.data === \"string\" ? res.data : JSON.stringify(res.data);\n completed = true;\n },\n fail: () => {\n failed = true;\n completed = true;\n },\n };\n\n try {\n const ret = miniReq(opts);\n if (ret && typeof ret.then === \"function\") {\n ret\n .then((res: any) => {\n buffer = typeof res.data === \"string\" ? res.data : JSON.stringify(res.data);\n completed = true;\n })\n .catch(() => {\n failed = true;\n completed = true;\n });\n }\n } catch {\n failed = true;\n completed = true;\n }\n\n resolve({\n ok: true,\n statusText: \"OK\",\n read: async () => {\n while (!completed && position >= buffer.length) {\n await new Promise((r) => setTimeout(r, 50));\n }\n if (failed) return null;\n if (position >= buffer.length) return completed ? null : \"\";\n const chunk = buffer.slice(position);\n position = buffer.length;\n return chunk;\n },\n });\n });\n }\n\n // Browser: use fetch streaming\n const response = await fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n credentials: \"include\",\n body: JSON.stringify(data),\n });\n\n if (!response.body) {\n return { ok: response.ok, statusText: response.statusText, read: async () => null };\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n\n return {\n ok: response.ok,\n statusText: response.statusText,\n read: async () => {\n const { done, value } = await reader.read();\n if (done) return null;\n return decoder.decode(value, { stream: true });\n },\n };\n}\n\n// ============ Input Types ============\n\nexport interface TextContent {\n type: \"text\";\n text: string;\n}\n\nexport interface ImageContent {\n type: \"image\";\n data?: string;\n url?: string;\n mimeType?: string;\n}\n\nexport interface FileContent {\n type: \"file\";\n data?: string;\n url?: string;\n mimeType?: string;\n name?: string;\n}\n\nexport type MessageContent = TextContent | ImageContent | FileContent;\n\nexport interface ChatMessage {\n role: \"system\" | \"user\" | \"assistant\";\n content: string | MessageContent[];\n}\n\nexport interface ChatOptions {\n taskId?: string;\n}\n\n// ============ Convert Input to A2A Part ============\n\nfunction convertToA2AParts(content: string | MessageContent[]): Part[] {\n if (typeof content === \"string\") {\n return [{ kind: \"text\", text: content }];\n }\n\n return content\n .map((part): Part | null => {\n switch (part.type) {\n case \"text\":\n return { kind: \"text\", text: part.text };\n case \"image\":\n if (part.data) {\n return {\n kind: \"file\",\n file: { bytes: part.data, mimeType: part.mimeType || \"image/png\" },\n };\n }\n if (part.url) {\n return {\n kind: \"file\",\n file: { uri: part.url, mimeType: part.mimeType || \"image/png\" },\n };\n }\n return null;\n case \"file\":\n if (part.data) {\n return {\n kind: \"file\",\n file: {\n bytes: part.data,\n ...(part.mimeType && { mimeType: part.mimeType }),\n ...(part.name && { name: part.name }),\n },\n };\n }\n if (part.url) {\n return {\n kind: \"file\",\n file: {\n uri: part.url,\n ...(part.mimeType && { mimeType: part.mimeType }),\n ...(part.name && { name: part.name }),\n },\n };\n }\n return null;\n default:\n return null;\n }\n })\n .filter((part): part is Part => part !== null);\n}\n\nfunction extractTextFromContent(content: string | MessageContent[]): string {\n if (typeof content === \"string\") {\n return content;\n }\n return content\n .filter((part): part is TextContent => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\\n\");\n}\n\n// ============ A2A → A2UI Conversion ============\n\nconst A2UI_MIME_TYPE = \"application/json+a2ui\";\nconst DEFAULT_SURFACE_ID = \"main\";\n\nlet componentIdCounter = 0;\n\nfunction generateComponentId(prefix: string): string {\n return `${prefix}-${++componentIdCounter}`;\n}\n\nfunction textPartToA2UI(text: string, surfaceId: string): ServerToClientMessage {\n const componentId = generateComponentId(\"text\");\n return {\n surfaceUpdate: {\n surfaceId,\n components: [\n {\n id: componentId,\n component: {\n Text: {\n text: { literalString: text },\n usageHint: \"body\",\n },\n },\n },\n ],\n },\n };\n}\n\nfunction filePartToA2UI(\n file: { bytes?: string; uri?: string; mimeType?: string; name?: string },\n surfaceId: string\n): ServerToClientMessage | null {\n const mimeType = file.mimeType || \"\";\n if (!mimeType.startsWith(\"image/\")) {\n return null;\n }\n\n const componentId = generateComponentId(\"image\");\n const url = file.uri || (file.bytes ? `data:${mimeType};base64,${file.bytes}` : null);\n\n if (!url) {\n return null;\n }\n\n return {\n surfaceUpdate: {\n surfaceId,\n components: [\n {\n id: componentId,\n component: {\n Image: {\n url: { literalString: url },\n },\n },\n },\n ],\n },\n };\n}\n\nfunction thoughtToA2UI(\n thought: { subject?: string; description?: string },\n surfaceId: string\n): ServerToClientMessage | null {\n if (!thought.subject && !thought.description) {\n return null;\n }\n\n const baseId = generateComponentId(\"thought\");\n const components: Array<{ id: string; component: Record<string, unknown> }> = [];\n\n components.push({\n id: baseId,\n component: {\n Card: {\n child: `${baseId}-content`,\n },\n },\n });\n\n const childrenList: string[] = [];\n if (thought.subject) {\n childrenList.push(`${baseId}-subject`);\n }\n if (thought.description) {\n childrenList.push(`${baseId}-desc`);\n }\n\n components.push({\n id: `${baseId}-content`,\n component: {\n Column: {\n children: { explicitList: childrenList },\n },\n },\n });\n\n if (thought.subject) {\n components.push({\n id: `${baseId}-subject`,\n component: {\n Text: {\n text: { literalString: `💭 ${thought.subject}` },\n usageHint: \"h4\",\n },\n },\n });\n }\n\n if (thought.description) {\n components.push({\n id: `${baseId}-desc`,\n component: {\n Text: {\n text: { literalString: thought.description },\n usageHint: \"caption\",\n },\n },\n });\n }\n\n return {\n surfaceUpdate: {\n surfaceId,\n components,\n },\n };\n}\n\nfunction getToolStatusDisplay(status: string): { icon: string; text: string } {\n switch (status) {\n case \"success\":\n case \"completed\":\n return { icon: \"check_circle\", text: \"✓ Completed\" };\n case \"failed\":\n case \"error\":\n return { icon: \"error\", text: \"✗ Failed\" };\n case \"validating\":\n return { icon: \"rule\", text: \"🔍 Validating...\" };\n case \"scheduled\":\n return { icon: \"schedule\", text: \"📋 Scheduled...\" };\n case \"executing\":\n return { icon: \"play_circle\", text: \"▶️ Executing...\" };\n case \"pending\":\n return { icon: \"hourglass_empty\", text: \"⏳ Pending...\" };\n default:\n return { icon: \"build\", text: \"⚙️ Running...\" };\n }\n}\n\nfunction toolCallToA2UI(\n toolCall: {\n request?: { name?: string; args?: Record<string, unknown> };\n status?: string;\n tool?: { name?: string; displayName?: string; description?: string };\n response?: { content?: string };\n resultDisplay?: string;\n },\n surfaceId: string\n): ServerToClientMessage | null {\n const toolName =\n toolCall.tool?.displayName || toolCall.tool?.name || toolCall.request?.name || \"Tool\";\n const status = toolCall.status || \"running\";\n const { icon: iconName, text: statusText } = getToolStatusDisplay(status);\n\n const baseId = generateComponentId(\"tool\");\n const components: Array<{ id: string; component: Record<string, unknown> }> = [];\n\n components.push({\n id: baseId,\n component: {\n Card: {\n child: `${baseId}-row`,\n },\n },\n });\n\n components.push({\n id: `${baseId}-row`,\n component: {\n Row: {\n alignment: \"center\",\n children: { explicitList: [`${baseId}-icon`, `${baseId}-info`] },\n },\n },\n });\n\n components.push({\n id: `${baseId}-icon`,\n component: {\n Icon: {\n name: { literalString: iconName },\n },\n },\n });\n\n // Build info column children list\n const infoChildren = [`${baseId}-name`, `${baseId}-status`];\n\n // Add result display if available (for completed tool calls)\n if (toolCall.resultDisplay && (status === \"success\" || status === \"completed\")) {\n infoChildren.push(`${baseId}-result`);\n }\n\n components.push({\n id: `${baseId}-info`,\n component: {\n Column: {\n children: { explicitList: infoChildren },\n },\n },\n });\n\n components.push({\n id: `${baseId}-name`,\n component: {\n Text: {\n text: { literalString: toolName },\n usageHint: \"body\",\n },\n },\n });\n\n components.push({\n id: `${baseId}-status`,\n component: {\n Text: {\n text: { literalString: statusText },\n usageHint: \"caption\",\n },\n },\n });\n\n // Add result preview if available\n if (toolCall.resultDisplay && (status === \"success\" || status === \"completed\")) {\n // Truncate long results for display\n const resultPreview =\n toolCall.resultDisplay.length > 200\n ? toolCall.resultDisplay.slice(0, 200) + \"...\"\n : toolCall.resultDisplay;\n\n components.push({\n id: `${baseId}-result`,\n component: {\n Text: {\n text: { literalString: resultPreview },\n usageHint: \"caption\",\n },\n },\n });\n }\n\n return {\n surfaceUpdate: {\n surfaceId,\n components,\n },\n };\n}\n\nconst CODER_AGENT_EVENT = {\n THOUGHT: \"thought\",\n TOOL_CALL_UPDATE: \"tool-call-update\",\n TOOL_CALL_CONFIRMATION: \"tool-call-confirmation\",\n TEXT_CONTENT: \"text-content\",\n STATE_CHANGE: \"state-change\",\n} as const;\n\nfunction convertA2APartsToA2UI(\n parts: Part[],\n coderAgentKind?: string,\n surfaceId: string = DEFAULT_SURFACE_ID\n): ServerToClientMessage[] {\n const messages: ServerToClientMessage[] = [];\n\n for (const part of parts) {\n if (part.kind === \"text\") {\n // For text-content events or regular text parts, convert text to A2UI\n messages.push(textPartToA2UI(part.text, surfaceId));\n } else if (part.kind === \"file\" && \"file\" in part) {\n const file = part.file as { bytes?: string; uri?: string; mimeType?: string; name?: string };\n const a2uiMsg = filePartToA2UI(file, surfaceId);\n if (a2uiMsg) {\n messages.push(a2uiMsg);\n }\n } else if (part.kind === \"data\") {\n const data = part.data as Record<string, unknown>;\n\n if (part.metadata?.mimeType === A2UI_MIME_TYPE) {\n messages.push(data as ServerToClientMessage);\n } else if (coderAgentKind === CODER_AGENT_EVENT.THOUGHT) {\n const thought = data as { subject?: string; description?: string };\n if (thought.subject) {\n const a2uiMsg = thoughtToA2UI(thought, surfaceId);\n if (a2uiMsg) {\n messages.push(a2uiMsg);\n }\n } else if (thought.description) {\n messages.push(textPartToA2UI(thought.description, surfaceId));\n }\n } else if (\n coderAgentKind === CODER_AGENT_EVENT.TOOL_CALL_UPDATE ||\n coderAgentKind === CODER_AGENT_EVENT.TOOL_CALL_CONFIRMATION\n ) {\n const a2uiMsg = toolCallToA2UI(\n data as {\n request?: { name?: string; args?: Record<string, unknown> };\n status?: string;\n tool?: { name?: string; displayName?: string; description?: string };\n response?: { content?: string };\n },\n surfaceId\n );\n if (a2uiMsg) {\n messages.push(a2uiMsg);\n }\n }\n // Note: TEXT_CONTENT events now use \"text\" parts (handled above), not \"data\" parts\n }\n }\n\n return messages;\n}\n\nfunction convertResponseToA2UI(response: SendStreamingMessageResponse): ServerToClientMessage[] {\n if (\"error\" in response) {\n return [];\n }\n\n const result = response.result;\n if (!result || !(\"kind\" in result) || result.kind !== \"status-update\") {\n return [];\n }\n\n const metadata = result.metadata as { coderAgent?: { kind?: string } } | undefined;\n const coderAgentKind = metadata?.coderAgent?.kind;\n\n // Skip state-change events without message content (submitted/working state transitions)\n if (coderAgentKind === CODER_AGENT_EVENT.STATE_CHANGE) {\n return [];\n }\n\n // Handle messages with parts (text, file, data, tool calls, thoughts, etc.)\n const parts = result.status?.message?.parts;\n if (!parts || parts.length === 0) {\n return [];\n }\n\n return convertA2APartsToA2UI(parts, coderAgentKind);\n}\n\n// ============ SSE Stream Handling ============\n\nasync function* parseSSEStream(\n streamResponse: StreamResponse\n): AsyncGenerator<SendStreamingMessageResponse, void, unknown> {\n const queue: SendStreamingMessageResponse[] = [];\n\n const parser = createParser({\n onEvent: (event) => {\n try {\n queue.push(JSON.parse(event.data));\n } catch {\n // Ignore parse errors\n }\n },\n });\n\n try {\n while (true) {\n const chunk = await streamResponse.read();\n if (chunk === null) break;\n if (chunk) {\n parser.feed(chunk);\n while (queue.length > 0) {\n const item = queue.shift();\n if (item) yield item;\n }\n }\n }\n } catch {\n // Ignore stream errors\n }\n}\n\n// ============ Client ============\n\nexport type CopilotA2UIClient = {\n /**\n * Stream A2UI messages from Copilot Agent.\n *\n * @example\n * ```typescript\n * import { createCopilotA2UIClient, Data } from \"@amaster.ai/copilot-client\";\n *\n * const client = createCopilotA2UIClient();\n * const processor = Data.createSignalA2uiMessageProcessor();\n *\n * for await (const messages of client.chat([{ role: \"user\", content: \"Hello\" }])) {\n * processor.processMessages(messages);\n * }\n * ```\n */\n chat(\n messages: ChatMessage[],\n options?: ChatOptions\n ): AsyncGenerator<ServerToClientMessage[], void, unknown>;\n\n cancelChat(taskId: string): Promise<ClientResult<CancelTaskResponse>>;\n getChatStatus(taskId: string): Promise<ClientResult<GetTaskResponse>>;\n};\n\n/**\n * Create Copilot A2UI client\n *\n * Auto-detects runtime environment (Browser/Vite/Taro H5/Taro Mini-program)\n */\nexport function createCopilotA2UIClient(http: HttpClient = createHttpClient()): CopilotA2UIClient {\n const baseUrl = \"/api/proxy/builtin/platform/copilot\";\n\n async function* sendMessageStream(\n request: SendStreamingMessageRequest\n ): AsyncGenerator<SendStreamingMessageResponse, void, unknown> {\n try {\n const streamResponse = await createStream(baseUrl, request);\n\n if (!streamResponse.ok) {\n throw new Error(`Stream request failed: ${streamResponse.statusText}`);\n }\n\n yield* parseSSEStream(streamResponse);\n } catch {\n // Ignore stream errors\n }\n }\n\n return {\n async *chat(messages, chatOptions = {}) {\n const { taskId } = chatOptions;\n\n const systemMsg = messages.find((m) => m.role === \"system\");\n const nonSystemMsgs = messages.filter((m) => m.role !== \"system\");\n const lastUserMsg = nonSystemMsgs[nonSystemMsgs.length - 1];\n\n const parts = lastUserMsg\n ? convertToA2AParts(lastUserMsg.content)\n : [{ kind: \"text\" as const, text: \"\" }];\n\n const systemPrompt = systemMsg ? extractTextFromContent(systemMsg.content) : undefined;\n\n const request: SendStreamingMessageRequest = {\n jsonrpc: \"2.0\",\n id: generateUUID(),\n method: \"message/stream\",\n params: {\n message: {\n contextId: getAppId(),\n kind: \"message\",\n messageId: generateUUID(),\n role: \"user\",\n parts,\n ...(taskId && { taskId }),\n ...(systemPrompt && { metadata: { systemPrompt } }),\n },\n },\n };\n\n for await (const response of sendMessageStream(request)) {\n const a2uiMessages = convertResponseToA2UI(response);\n if (a2uiMessages.length > 0) {\n yield a2uiMessages;\n }\n }\n },\n\n cancelChat(taskId) {\n const request: CancelTaskRequest = {\n jsonrpc: \"2.0\",\n id: generateUUID(),\n method: \"tasks/cancel\",\n params: { id: taskId },\n };\n return http.request<CancelTaskResponse>({\n url: baseUrl,\n method: \"POST\",\n data: request,\n });\n },\n\n getChatStatus(taskId) {\n const request: GetTaskRequest = {\n jsonrpc: \"2.0\",\n id: generateUUID(),\n method: \"tasks/get\",\n params: { id: taskId },\n };\n return http.request<GetTaskResponse>({\n url: baseUrl,\n method: \"POST\",\n data: request,\n });\n },\n };\n}\n","/**\n * A2UI Types - Inlined from @a2ui/lit for Taro compatibility\n *\n * This file contains the minimal A2UI type definitions needed by copilot-client.\n * We inline these types instead of importing from @a2ui/lit because @a2ui/lit\n * uses ES2025 `import ... with { type: \"json\" }` syntax which is not supported\n * by Taro's Vite/esbuild version.\n */\n\n// ============ Primitive Types ============\n\nexport interface StringValue {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n /** A fixed, hardcoded string value. */\n literalString?: string;\n /** A fixed, hardcoded string value. */\n literal?: string;\n}\n\nexport interface NumberValue {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n /** A fixed, hardcoded number value. */\n literalNumber?: number;\n /** A fixed, hardcoded number value. */\n literal?: number;\n}\n\nexport interface BooleanValue {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n /** A fixed, hardcoded boolean value. */\n literalBoolean?: boolean;\n /** A fixed, hardcoded boolean value. */\n literal?: boolean;\n}\n\n// ============ Component Types ============\n\nexport interface Action {\n /** A unique name identifying the action (e.g., 'submitForm'). */\n name: string;\n /** A key-value map of data bindings to be resolved when the action is triggered. */\n context?: {\n key: string;\n /** The dynamic value. Define EXACTLY ONE of the nested properties. */\n value: {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n /** A fixed, hardcoded string value. */\n literalString?: string;\n literalNumber?: number;\n literalBoolean?: boolean;\n };\n }[];\n}\n\nexport interface Text {\n text: StringValue;\n usageHint: \"h1\" | \"h2\" | \"h3\" | \"h4\" | \"h5\" | \"caption\" | \"body\";\n}\n\nexport interface Image {\n url: StringValue;\n usageHint: \"icon\" | \"avatar\" | \"smallFeature\" | \"mediumFeature\" | \"largeFeature\" | \"header\";\n fit?: \"contain\" | \"cover\" | \"fill\" | \"none\" | \"scale-down\";\n}\n\nexport interface Icon {\n name: StringValue;\n}\n\nexport interface Video {\n url: StringValue;\n}\n\nexport interface AudioPlayer {\n url: StringValue;\n /** A label, title, or placeholder text. */\n description?: StringValue;\n}\n\nexport interface Tabs {\n /** A list of tabs, each with a title and a child component ID. */\n tabItems: {\n /** The title of the tab. */\n title: {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n /** A fixed, hardcoded string value. */\n literalString?: string;\n };\n /** A reference to a component instance by its unique ID. */\n child: string;\n }[];\n}\n\nexport interface Divider {\n /** The orientation. */\n axis?: \"horizontal\" | \"vertical\";\n /** The color of the divider (e.g., hex code or semantic name). */\n color?: string;\n /** The thickness of the divider. */\n thickness?: number;\n}\n\nexport interface Modal {\n /** The ID of the component (e.g., a button) that triggers the modal. */\n entryPointChild: string;\n /** The ID of the component to display as the modal's content. */\n contentChild: string;\n}\n\nexport interface Button {\n /** The ID of the component to display as the button's content. */\n child: string;\n /** Represents a user-initiated action. */\n action: Action;\n}\n\nexport interface Checkbox {\n label: StringValue;\n value: {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n literalBoolean?: boolean;\n };\n}\n\nexport interface TextField {\n text?: StringValue;\n /** A label, title, or placeholder text. */\n label: StringValue;\n type?: \"shortText\" | \"number\" | \"date\" | \"longText\";\n /** A regex string to validate the input. */\n validationRegexp?: string;\n}\n\nexport interface DateTimeInput {\n value: StringValue;\n enableDate?: boolean;\n enableTime?: boolean;\n /** The string format for the output (e.g., 'YYYY-MM-DD'). */\n outputFormat?: string;\n}\n\nexport interface MultipleChoice {\n selections: {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n literalArray?: string[];\n };\n options?: {\n label: {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n /** A fixed, hardcoded string value. */\n literalString?: string;\n };\n value: string;\n }[];\n maxAllowedSelections?: number;\n}\n\nexport interface Slider {\n value: {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n literalNumber?: number;\n };\n minValue?: number;\n maxValue?: number;\n}\n\n// ============ Data Model Types ============\n\n/** A recursive type for any valid JSON-like value in the data model. */\nexport type DataValue = string | number | boolean | null | DataMap | DataObject | DataArray;\nexport type DataObject = { [key: string]: DataValue };\nexport type DataMap = Map<string, DataValue>;\nexport type DataArray = DataValue[];\n\n/** A template for creating components from a list in the data model. */\nexport interface ComponentArrayTemplate {\n componentId: string;\n dataBinding: string;\n}\n\n/** Defines a list of child components, either explicitly or via a template. */\nexport interface ComponentArrayReference {\n explicitList?: string[];\n template?: ComponentArrayTemplate;\n}\n\n/** Represents the general shape of a component's properties. */\nexport type ComponentProperties = {\n children?: ComponentArrayReference;\n child?: string;\n [k: string]: unknown;\n};\n\n/** A raw component instance from a SurfaceUpdate message. */\nexport interface ComponentInstance {\n id: string;\n weight?: number;\n component?: ComponentProperties;\n}\n\nexport type ValueMap = DataObject & {\n key: string;\n /** May be JSON */\n valueString?: string;\n valueNumber?: number;\n valueBoolean?: boolean;\n valueMap?: ValueMap[];\n};\n\n// ============ Message Types ============\n\nexport interface BeginRenderingMessage {\n surfaceId: string;\n root: string;\n styles?: Record<string, string>;\n}\n\nexport interface SurfaceUpdateMessage {\n surfaceId: string;\n components: ComponentInstance[];\n}\n\nexport interface DataModelUpdate {\n surfaceId: string;\n path?: string;\n contents: ValueMap[];\n}\n\nexport interface DeleteSurfaceMessage {\n surfaceId: string;\n}\n\nexport interface ServerToClientMessage {\n beginRendering?: BeginRenderingMessage;\n surfaceUpdate?: SurfaceUpdateMessage;\n dataModelUpdate?: DataModelUpdate;\n deleteSurface?: DeleteSurfaceMessage;\n}\n\n// ============ Component Node Types ============\n\n/** A recursive type for any value that can appear within a resolved component tree. */\nexport type ResolvedValue =\n | string\n | number\n | boolean\n | null\n | AnyComponentNode\n | ResolvedMap\n | ResolvedArray;\n\n/** A generic map where each value has been recursively resolved. */\nexport type ResolvedMap = { [key: string]: ResolvedValue };\n\n/** A generic array where each item has been recursively resolved. */\nexport type ResolvedArray = ResolvedValue[];\n\n/** A base interface that all component nodes share. */\ninterface BaseComponentNode {\n id: string;\n weight?: number;\n dataContextPath?: string;\n slotName?: string;\n}\n\nexport interface TextNode extends BaseComponentNode {\n type: \"Text\";\n properties: Text;\n}\n\nexport interface ImageNode extends BaseComponentNode {\n type: \"Image\";\n properties: Image;\n}\n\nexport interface IconNode extends BaseComponentNode {\n type: \"Icon\";\n properties: Icon;\n}\n\nexport interface VideoNode extends BaseComponentNode {\n type: \"Video\";\n properties: Video;\n}\n\nexport interface AudioPlayerNode extends BaseComponentNode {\n type: \"AudioPlayer\";\n properties: AudioPlayer;\n}\n\nexport interface RowNode extends BaseComponentNode {\n type: \"Row\";\n properties: ResolvedRow;\n}\n\nexport interface ColumnNode extends BaseComponentNode {\n type: \"Column\";\n properties: ResolvedColumn;\n}\n\nexport interface ListNode extends BaseComponentNode {\n type: \"List\";\n properties: ResolvedList;\n}\n\nexport interface CardNode extends BaseComponentNode {\n type: \"Card\";\n properties: ResolvedCard;\n}\n\nexport interface TabsNode extends BaseComponentNode {\n type: \"Tabs\";\n properties: ResolvedTabs;\n}\n\nexport interface DividerNode extends BaseComponentNode {\n type: \"Divider\";\n properties: Divider;\n}\n\nexport interface ModalNode extends BaseComponentNode {\n type: \"Modal\";\n properties: ResolvedModal;\n}\n\nexport interface ButtonNode extends BaseComponentNode {\n type: \"Button\";\n properties: ResolvedButton;\n}\n\nexport interface CheckboxNode extends BaseComponentNode {\n type: \"CheckBox\";\n properties: Checkbox;\n}\n\nexport interface TextFieldNode extends BaseComponentNode {\n type: \"TextField\";\n properties: TextField;\n}\n\nexport interface DateTimeInputNode extends BaseComponentNode {\n type: \"DateTimeInput\";\n properties: DateTimeInput;\n}\n\nexport interface MultipleChoiceNode extends BaseComponentNode {\n type: \"MultipleChoice\";\n properties: MultipleChoice;\n}\n\nexport interface SliderNode extends BaseComponentNode {\n type: \"Slider\";\n properties: Slider;\n}\n\nexport interface CustomNode extends BaseComponentNode {\n type: string;\n properties: CustomNodeProperties;\n}\n\n/**\n * The complete discriminated union of all possible resolved component nodes.\n * A renderer would use this type for any given node in the component tree.\n */\nexport type AnyComponentNode =\n | TextNode\n | IconNode\n | ImageNode\n | VideoNode\n | AudioPlayerNode\n | RowNode\n | ColumnNode\n | ListNode\n | CardNode\n | TabsNode\n | DividerNode\n | ModalNode\n | ButtonNode\n | CheckboxNode\n | TextFieldNode\n | DateTimeInputNode\n | MultipleChoiceNode\n | SliderNode\n | CustomNode;\n\nexport interface ResolvedRow {\n children: AnyComponentNode[];\n distribution?: \"start\" | \"center\" | \"end\" | \"spaceBetween\" | \"spaceAround\" | \"spaceEvenly\";\n alignment?: \"start\" | \"center\" | \"end\" | \"stretch\";\n}\n\nexport interface ResolvedColumn {\n children: AnyComponentNode[];\n distribution?: \"start\" | \"center\" | \"end\" | \"spaceBetween\" | \"spaceAround\" | \"spaceEvenly\";\n alignment?: \"start\" | \"center\" | \"end\" | \"stretch\";\n}\n\nexport interface ResolvedButton {\n child: AnyComponentNode;\n action: Button[\"action\"];\n}\n\nexport interface ResolvedList {\n children: AnyComponentNode[];\n direction?: \"vertical\" | \"horizontal\";\n alignment?: \"start\" | \"center\" | \"end\" | \"stretch\";\n}\n\nexport interface ResolvedCard {\n child: AnyComponentNode;\n children: AnyComponentNode[];\n}\n\nexport interface ResolvedTabItem {\n title: StringValue;\n child: AnyComponentNode;\n}\n\nexport interface ResolvedTabs {\n tabItems: ResolvedTabItem[];\n}\n\nexport interface ResolvedModal {\n entryPointChild: AnyComponentNode;\n contentChild: AnyComponentNode;\n}\n\nexport interface CustomNodeProperties {\n [k: string]: ResolvedValue;\n}\n\nexport type SurfaceID = string;\n\n/** The complete state of a single UI surface. */\nexport interface Surface {\n rootComponentId: string | null;\n componentTree: AnyComponentNode | null;\n dataModel: DataMap;\n components: Map<string, ComponentInstance>;\n styles: Record<string, string>;\n}\n\n// ============ MessageProcessor Interface ============\n\nexport interface MessageProcessor {\n getSurfaces(): ReadonlyMap<string, Surface>;\n clearSurfaces(): void;\n processMessages(messages: ServerToClientMessage[]): void;\n /**\n * Retrieves the data for a given component node and a relative path string.\n * This correctly handles the special `.` path, which refers to the node's\n * own data context.\n */\n getData(node: AnyComponentNode, relativePath: string, surfaceId: string): DataValue | null;\n setData(\n node: AnyComponentNode | null,\n relativePath: string,\n value: DataValue,\n surfaceId: string\n ): void;\n resolvePath(path: string, dataContextPath?: string): string;\n}\n"]}
1
+ {"version":3,"sources":["../src/copilot-a2ui-client.ts","../src/a2ui-types.ts"],"names":["g","getMiniProgramRequest","generateUUID","cryptoObj","c","r","extractAppIdFromUrl","url","pathMatch","hostname","wwwMatch","domainMatch","cachedAppId","getAppId","urlAppId","createWeChatMiniProgramStream","data","authHeader","resolve","chunkBuffer","textDecoder","MiniProgramTextDecoder","ended","errorOccurred","dataQueue","resolveRead","pendingRead","pushChunk","text","chunkListener","res","newChunk","merged","decodeOffset","partial","decoded","MiniProgramTextEncoder","err","headersListener","miniReq","requestTask","finalText","error","createStream","getAccessToken","token","buffer","completed","failed","position","opts","ret","chunk","headers","response","reader","decoder","done","value","convertToA2AParts","content","part","extractTextFromContent","A2UI_MIME_TYPE","DEFAULT_SURFACE_ID","componentIdCounter","generateComponentId","prefix","textPartToA2UI","surfaceId","componentId","filePartToA2UI","file","mimeType","thoughtToA2UI","thought","baseId","components","childrenList","getToolStatusDisplay","status","toolCallToA2UI","toolCall","toolName","iconName","statusText","infoChildren","resultPreview","CODER_AGENT_EVENT","convertA2APartsToA2UI","parts","coderAgentKind","messages","a2uiMsg","convertResponseToA2UI","result","parseSSEStream","streamResponse","queue","parser","createParser","event","item","createCopilotA2UIClient","http","createHttpClient","baseUrl","envBaseUrl","metaEnv","sendMessageStream","request","chatOptions","taskId","systemMsg","m","nonSystemMsgs","lastUserMsg","systemPrompt","a2uiMessages","a2ui_types_exports"],"mappings":"qLAsBA,IAAMA,CAAAA,CAAI,UAAA,CAEV,SAASC,CAAAA,EAAsD,CAC7D,OAAI,OAAOD,CAAAA,EAAG,IAAA,EAAM,OAAA,EAAY,UAAA,CAAmBA,CAAAA,CAAE,IAAA,CAAK,OAAA,CAAQ,KAAKA,CAAAA,CAAE,IAAI,CAAA,CACzE,OAAOA,CAAAA,EAAG,EAAA,EAAI,OAAA,EAAY,UAAA,CAAmBA,CAAAA,CAAE,EAAA,CAAG,OAAA,CAAQ,IAAA,CAAKA,CAAAA,CAAE,EAAE,CAAA,CACnE,OAAOA,CAAAA,EAAG,EAAA,EAAI,OAAA,EAAY,UAAA,CAAmBA,CAAAA,CAAE,EAAA,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G,CACR,CAAC,CACH,CACF,CACF,KCl/BAS,CAAAA,CAAA","file":"index.js","sourcesContent":["/* eslint-disable no-undef, no-unused-vars */\nimport type {\n CancelTaskRequest,\n CancelTaskResponse,\n GetTaskRequest,\n GetTaskResponse,\n Part,\n SendStreamingMessageRequest,\n SendStreamingMessageResponse,\n} from \"@a2a-js/sdk\";\nimport { type ClientResult, createHttpClient, type HttpClient } from \"@amaster.ai/http-client\";\nimport { createParser } from \"eventsource-parser\";\nimport type { ServerToClientMessage, Surface, MessageProcessor } from \"./a2ui-types\";\nimport MiniProgramTextDecoder from \"miniprogram-text-decoder\";\nimport MiniProgramTextEncoder from \"miniprogram-text-encoder\";\n\n// Re-export A2UI types from local definitions\nexport type { ServerToClientMessage, Surface, MessageProcessor };\n\n// ============ Internal: Platform Detection (same as http-client) ============\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst g = globalThis as any;\n\nfunction getMiniProgramRequest(): ((_opts: any) => any) | null {\n if (typeof g?.Taro?.request === \"function\") return g.Taro.request.bind(g.Taro);\n if (typeof g?.wx?.request === \"function\") return g.wx.request.bind(g.wx);\n if (typeof g?.tt?.request === \"function\") return g.tt.request.bind(g.tt);\n if (typeof g?.my?.request === \"function\") return g.my.request.bind(g.my);\n if (typeof g?.swan?.request === \"function\") return g.swan.request.bind(g.swan);\n if (typeof g?.qq?.request === \"function\") return g.qq.request.bind(g.qq);\n if (typeof g?.jd?.request === \"function\") return g.jd.request.bind(g.jd);\n return null;\n}\n\n// ============ Internal: UUID Generator ============\n\nfunction generateUUID(): string {\n const cryptoObj = typeof globalThis !== \"undefined\" ? globalThis.crypto : undefined;\n\n if (cryptoObj && typeof cryptoObj.randomUUID === \"function\") {\n return cryptoObj.randomUUID();\n }\n\n if (cryptoObj && typeof cryptoObj.getRandomValues === \"function\") {\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n const randomValues = cryptoObj.getRandomValues(new Uint8Array(1));\n const r = (randomValues[0] ?? 0) % 16;\n const v = c === \"x\" ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n }\n\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === \"x\" ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n// ============ Internal: URL Utilities ============\n\nfunction extractAppIdFromUrl(): string | null {\n if (typeof window === \"undefined\") return null;\n\n try {\n const url = window.location.href;\n const pathMatch = /\\/app\\/([\\da-f-]+)(?:\\/|$)/.exec(url);\n if (pathMatch?.[1]) return pathMatch[1];\n\n const hostname = window.location.hostname;\n\n // Pattern 1: www.{app_id}.domain.tld or www.{app_id}-{env}.domain.tld\n const wwwMatch = /^www\\.([\\da-f-]+)(?:-[^.]+)?\\.[\\w-]+\\.(?:local|ai|cn)$/.exec(hostname);\n if (wwwMatch?.[1]) return wwwMatch[1];\n\n // Pattern 2: {app_id}-{env}.domain.tld or {app_id}.domain.tld\n const domainMatch = /^([\\da-f-]+)(?:-[^.]+)?\\.[\\w-]+\\.(?:local|ai|cn)$/.exec(hostname);\n if (domainMatch?.[1]) return domainMatch[1];\n\n return null;\n } catch {\n return null;\n }\n}\n\n// Cache appId for session consistency\nlet cachedAppId: string | null = null;\n\nfunction getAppId(): string {\n const urlAppId = extractAppIdFromUrl();\n if (urlAppId) return urlAppId;\n if (!cachedAppId) cachedAppId = generateUUID();\n return cachedAppId;\n}\n\n// ============ Internal: Streaming ============\n\ninterface StreamResponse {\n ok: boolean;\n statusText: string;\n read(): Promise<string | null>;\n}\n\n// 小程序专用的流式请求\nasync function createWeChatMiniProgramStream(\n url: string, \n data: unknown,\n authHeader: Record<string, string> = {}\n): Promise<StreamResponse> {\n return new Promise<StreamResponse>((resolve) => {\n let chunkBuffer = new Uint8Array(0); // 字节缓冲,用于处理 UTF-8 截断\n const textDecoder = new MiniProgramTextDecoder(\"utf-8\", {\n fatal: false,\n });\n\n let ended = false;\n let errorOccurred = false;\n\n // 用于外部调用 read() 时取数据的队列\n const dataQueue: string[] = [];\n let resolveRead: ((value: string | null) => void) | null = null;\n\n const pendingRead = () =>\n new Promise<string | null>((r) => {\n if (dataQueue.length > 0) {\n r(dataQueue.shift()!);\n } else if (ended) {\n r(null);\n } else {\n resolveRead = r;\n }\n });\n\n const pushChunk = (text: string) => {\n if (text) {\n dataQueue.push(text);\n if (resolveRead) {\n resolveRead(dataQueue.shift()!);\n resolveRead = null;\n }\n }\n };\n\n const chunkListener = (res: any) => {\n if (errorOccurred || ended || !res.data) return;\n\n try {\n const newChunk = new Uint8Array(res.data as ArrayBuffer);\n // 追加到缓冲\n const merged = new Uint8Array(chunkBuffer.length + newChunk.length);\n merged.set(chunkBuffer);\n merged.set(newChunk, chunkBuffer.length);\n chunkBuffer = merged;\n\n // 尝试解码尽可能多的完整字符\n let decodeOffset = 0;\n while (decodeOffset < chunkBuffer.length) {\n const partial = chunkBuffer.subarray(decodeOffset);\n const decoded = textDecoder.decode(partial, { stream: false });\n\n // 如果解码出内容,说明前面是完整字符\n if (decoded) {\n pushChunk(decoded);\n // 移动偏移(注意:TextDecoder 内部会处理多字节边界)\n // 但为了安全,我们粗略估算已消费字节(不完美但够用)\n // 实际生产中可使用更精确的边界检测\n decodeOffset += new MiniProgramTextEncoder().encode(decoded).length;\n } else {\n // 剩余部分可能是半个字符,留到下次\n break;\n }\n }\n\n // 保留未解码的部分\n if (decodeOffset < chunkBuffer.length) {\n chunkBuffer = chunkBuffer.subarray(decodeOffset);\n } else {\n chunkBuffer = new Uint8Array(0);\n }\n } catch (err) {\n console.error(\"[mini stream] chunk process error:\", err);\n }\n };\n\n const headersListener = (res: any) => {\n if (res.header?.[\"content-type\"]?.includes(\"text/event-stream\") === false) {\n console.warn(\"Warning: server did not return event-stream\");\n }\n };\n\n const miniReq = g.wx.request.bind(g.wx);\n\n try {\n const requestTask = miniReq({\n url,\n method: \"POST\",\n header: {\n \"Content-Type\": \"application/json\",\n Accept: \"text/event-stream\",\n ...authHeader,\n },\n data: typeof data === \"string\" ? data : JSON.stringify(data),\n responseType: \"arraybuffer\", // 必须!\n enableChunked: true, // 必须!\n timeout: 300000,\n\n success: () => {\n // 成功结束时,把剩余缓冲区解码\n if (chunkBuffer.length > 0) {\n const finalText = textDecoder.decode(chunkBuffer, {\n stream: true,\n });\n pushChunk(finalText);\n }\n ended = true;\n if (resolveRead) resolveRead(null);\n },\n\n fail: (err: any) => {\n console.error(\"[mini stream] request fail:\", err);\n errorOccurred = true;\n ended = true;\n if (resolveRead) resolveRead(null);\n },\n });\n // 关键:监听分块到达\n requestTask.onChunkReceived?.(chunkListener);\n // 可选:监听 HTTP headers 到达(可用于检查状态码)\n requestTask.onHeadersReceived?.(headersListener);\n\n resolve({\n ok: true, // 稍后可根据 headers 更精确判断\n statusText: \"OK\",\n read: async () => {\n if (errorOccurred) return null;\n return pendingRead();\n },\n });\n } catch (error) {\n console.error(\"miniReq error\", error);\n }\n });\n}\n\nasync function createStream(\n url: string, \n data: unknown,\n getAccessToken?: () => string | null\n): Promise<StreamResponse> {\n // Get token for authentication\n const token = getAccessToken?.();\n const authHeader: Record<string, string> = token ? { Authorization: `Bearer ${token}` } : {};\n\n if (typeof g?.wx?.request === \"function\") {\n return createWeChatMiniProgramStream(url, data, authHeader);\n }\n const miniReq = getMiniProgramRequest();\n if (miniReq) {\n // Mini-program: buffer full response\n return new Promise((resolve) => {\n let buffer = \"\";\n let completed = false;\n let failed = false;\n let position = 0;\n\n const opts = {\n url,\n method: \"POST\",\n header: {\n \"Content-Type\": \"application/json\",\n Accept: \"text/event-stream\",\n ...authHeader,\n },\n data: typeof data === \"string\" ? data : JSON.stringify(data),\n timeout: 60000,\n success: (res: any) => {\n buffer = typeof res.data === \"string\" ? res.data : JSON.stringify(res.data);\n completed = true;\n },\n fail: (err: any) => {\n console.error(\"[createStream] wx.request failed:\", err);\n failed = true;\n completed = true;\n },\n complete: () => {},\n };\n\n try {\n const ret = miniReq(opts);\n\n if (ret && typeof ret.then === \"function\") {\n ret\n .then((res: any) => {\n buffer = typeof res.data === \"string\" ? res.data : JSON.stringify(res.data);\n completed = true;\n })\n .catch(() => {\n failed = true;\n completed = true;\n });\n }\n } catch (err) {\n console.error(\"[createStream] Exception:\", err);\n failed = true;\n completed = true;\n }\n\n resolve({\n ok: true,\n statusText: \"OK\",\n read: async () => {\n while (!completed && position >= buffer.length) {\n await new Promise((r) => setTimeout(r, 50));\n }\n if (failed) return null;\n if (position >= buffer.length) return completed ? null : \"\";\n const chunk = buffer.slice(position);\n position = buffer.length;\n return chunk;\n },\n });\n });\n }\n\n // Browser: use fetch streaming with authentication\n const headers: Record<string, string> = { \n \"Content-Type\": \"application/json\",\n ...authHeader,\n };\n \n const response = await fetch(url, {\n method: \"POST\",\n headers,\n credentials: \"include\",\n body: JSON.stringify(data),\n });\n\n if (!response.body) {\n return {\n ok: response.ok,\n statusText: response.statusText,\n read: async () => null,\n };\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n\n return {\n ok: response.ok,\n statusText: response.statusText,\n read: async () => {\n const { done, value } = await reader.read();\n if (done) return null;\n return decoder.decode(value, { stream: true });\n },\n };\n}\n\n// ============ Input Types ============\n\nexport interface TextContent {\n type: \"text\";\n text: string;\n}\n\nexport interface ImageContent {\n type: \"image\";\n data?: string;\n url?: string;\n mimeType?: string;\n}\n\nexport interface FileContent {\n type: \"file\";\n data?: string;\n url?: string;\n mimeType?: string;\n name?: string;\n}\n\nexport type MessageContent = TextContent | ImageContent | FileContent;\n\nexport interface ChatMessage {\n role: \"system\" | \"user\" | \"assistant\";\n content: string | MessageContent[];\n}\n\nexport interface ChatOptions {\n taskId?: string;\n}\n\n// ============ Convert Input to A2A Part ============\n\nfunction convertToA2AParts(content: string | MessageContent[]): Part[] {\n if (typeof content === \"string\") {\n return [{ kind: \"text\", text: content }];\n }\n\n return content\n .map((part): Part | null => {\n switch (part.type) {\n case \"text\":\n return { kind: \"text\", text: part.text };\n case \"image\":\n if (part.data) {\n return {\n kind: \"file\",\n file: {\n bytes: part.data,\n mimeType: part.mimeType || \"image/png\",\n },\n };\n }\n if (part.url) {\n return {\n kind: \"file\",\n file: { uri: part.url, mimeType: part.mimeType || \"image/png\" },\n };\n }\n return null;\n case \"file\":\n if (part.data) {\n return {\n kind: \"file\",\n file: {\n bytes: part.data,\n ...(part.mimeType && { mimeType: part.mimeType }),\n ...(part.name && { name: part.name }),\n },\n };\n }\n if (part.url) {\n return {\n kind: \"file\",\n file: {\n uri: part.url,\n ...(part.mimeType && { mimeType: part.mimeType }),\n ...(part.name && { name: part.name }),\n },\n };\n }\n return null;\n default:\n return null;\n }\n })\n .filter((part): part is Part => part !== null);\n}\n\nfunction extractTextFromContent(content: string | MessageContent[]): string {\n if (typeof content === \"string\") {\n return content;\n }\n return content\n .filter((part): part is TextContent => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\\n\");\n}\n\n// ============ A2A → A2UI Conversion ============\n\nconst A2UI_MIME_TYPE = \"application/json+a2ui\";\nconst DEFAULT_SURFACE_ID = \"main\";\n\nlet componentIdCounter = 0;\n\nfunction generateComponentId(prefix: string): string {\n return `${prefix}-${++componentIdCounter}`;\n}\n\nfunction textPartToA2UI(text: string, surfaceId: string): ServerToClientMessage {\n const componentId = generateComponentId(\"text\");\n return {\n surfaceUpdate: {\n surfaceId,\n components: [\n {\n id: componentId,\n component: {\n Text: {\n text: { literalString: text },\n usageHint: \"body\",\n },\n },\n },\n ],\n },\n };\n}\n\nfunction filePartToA2UI(\n file: { bytes?: string; uri?: string; mimeType?: string; name?: string },\n surfaceId: string\n): ServerToClientMessage | null {\n const mimeType = file.mimeType || \"\";\n if (!mimeType.startsWith(\"image/\")) {\n return null;\n }\n\n const componentId = generateComponentId(\"image\");\n const url = file.uri || (file.bytes ? `data:${mimeType};base64,${file.bytes}` : null);\n\n if (!url) {\n return null;\n }\n\n return {\n surfaceUpdate: {\n surfaceId,\n components: [\n {\n id: componentId,\n component: {\n Image: {\n url: { literalString: url },\n },\n },\n },\n ],\n },\n };\n}\n\nfunction thoughtToA2UI(\n thought: { subject?: string; description?: string },\n surfaceId: string\n): ServerToClientMessage | null {\n if (!thought.subject && !thought.description) {\n return null;\n }\n\n const baseId = generateComponentId(\"thought\");\n const components: Array<{ id: string; component: Record<string, unknown> }> = [];\n\n components.push({\n id: baseId,\n component: {\n Card: {\n child: `${baseId}-content`,\n },\n },\n });\n\n const childrenList: string[] = [];\n if (thought.subject) {\n childrenList.push(`${baseId}-subject`);\n }\n if (thought.description) {\n childrenList.push(`${baseId}-desc`);\n }\n\n components.push({\n id: `${baseId}-content`,\n component: {\n Column: {\n children: { explicitList: childrenList },\n },\n },\n });\n\n if (thought.subject) {\n components.push({\n id: `${baseId}-subject`,\n component: {\n Text: {\n text: { literalString: `💭 ${thought.subject}` },\n usageHint: \"h4\",\n },\n },\n });\n }\n\n if (thought.description) {\n components.push({\n id: `${baseId}-desc`,\n component: {\n Text: {\n text: { literalString: thought.description },\n usageHint: \"caption\",\n },\n },\n });\n }\n\n return {\n surfaceUpdate: {\n surfaceId,\n components,\n },\n };\n}\n\nfunction getToolStatusDisplay(status: string): { icon: string; text: string; status: string } {\n switch (status) {\n case \"success\":\n case \"completed\":\n return { icon: \"check_circle\", text: \"✓ Completed\", status };\n case \"failed\":\n case \"error\":\n return { icon: \"error\", text: \"✗ Failed\", status };\n case \"validating\":\n return { icon: \"rule\", text: \"🔍 Validating...\", status };\n case \"scheduled\":\n return { icon: \"schedule\", text: \"📋 Scheduled...\", status };\n case \"executing\":\n return { icon: \"play_circle\", text: \"▶️ Executing...\", status };\n case \"pending\":\n return { icon: \"hourglass_empty\", text: \"⏳ Pending...\", status };\n default:\n return { icon: \"build\", text: \"⚙️ Running...\", status };\n }\n}\n\nfunction toolCallToA2UI(\n toolCall: {\n request?: { name?: string; args?: Record<string, unknown> };\n status?: string;\n tool?: { name?: string; displayName?: string; description?: string };\n response?: { content?: string };\n resultDisplay?: string;\n },\n surfaceId: string\n): ServerToClientMessage | null {\n const toolName =\n toolCall.tool?.displayName || toolCall.tool?.name || toolCall.request?.name || \"Tool\";\n const status = toolCall.status || \"running\";\n const { icon: iconName, text: statusText } = getToolStatusDisplay(status);\n\n const baseId = generateComponentId(\"tool\");\n const components: Array<{ id: string; component: Record<string, unknown> }> = [];\n\n components.push({\n id: baseId,\n component: {\n Card: {\n child: `${baseId}-row`,\n },\n },\n });\n\n components.push({\n id: `${baseId}-row`,\n component: {\n Row: {\n alignment: \"center\",\n children: { explicitList: [`${baseId}-icon`, `${baseId}-info`] },\n },\n },\n });\n\n components.push({\n id: `${baseId}-icon`,\n component: {\n Icon: {\n name: { literalString: iconName },\n },\n },\n });\n\n // Build info column children list\n const infoChildren = [`${baseId}-name`, `${baseId}-status`];\n\n // Add result display if available (for completed tool calls)\n if (toolCall.resultDisplay && (status === \"success\" || status === \"completed\")) {\n infoChildren.push(`${baseId}-result`);\n }\n\n components.push({\n id: `${baseId}-info`,\n component: {\n Column: {\n children: { explicitList: infoChildren },\n },\n },\n });\n\n components.push({\n id: `${baseId}-name`,\n component: {\n Text: {\n text: { literalString: toolName },\n usageHint: \"body\",\n },\n },\n });\n\n components.push({\n id: `${baseId}-status`,\n component: {\n Text: {\n text: { literalString: statusText },\n usageHint: \"caption\",\n },\n },\n });\n\n // Add result preview if available\n if (toolCall.resultDisplay && (status === \"success\" || status === \"completed\")) {\n // Truncate long results for display\n const resultPreview =\n toolCall.resultDisplay.length > 200\n ? toolCall.resultDisplay.slice(0, 200) + \"...\"\n : toolCall.resultDisplay;\n\n components.push({\n id: `${baseId}-result`,\n component: {\n Text: {\n text: { literalString: resultPreview },\n usageHint: \"caption\",\n },\n },\n });\n }\n\n return {\n surfaceUpdate: {\n surfaceId,\n components,\n },\n };\n}\n\nconst CODER_AGENT_EVENT = {\n THOUGHT: \"thought\",\n TOOL_CALL_UPDATE: \"tool-call-update\",\n TOOL_CALL_CONFIRMATION: \"tool-call-confirmation\",\n TEXT_CONTENT: \"text-content\",\n STATE_CHANGE: \"state-change\",\n} as const;\n\nfunction convertA2APartsToA2UI(\n parts: Part[],\n coderAgentKind?: string,\n surfaceId: string = DEFAULT_SURFACE_ID\n): ServerToClientMessage[] {\n const messages: ServerToClientMessage[] = [];\n\n for (const part of parts) {\n if (part.kind === \"text\") {\n // For text-content events or regular text parts, convert text to A2UI\n messages.push(textPartToA2UI(part.text, surfaceId));\n } else if (part.kind === \"file\" && \"file\" in part) {\n const file = part.file as {\n bytes?: string;\n uri?: string;\n mimeType?: string;\n name?: string;\n };\n const a2uiMsg = filePartToA2UI(file, surfaceId);\n if (a2uiMsg) {\n messages.push(a2uiMsg);\n }\n } else if (part.kind === \"data\") {\n const data = part.data as Record<string, unknown>;\n\n if (part.metadata?.mimeType === A2UI_MIME_TYPE) {\n messages.push(data as ServerToClientMessage);\n } else if (coderAgentKind === CODER_AGENT_EVENT.THOUGHT) {\n const thought = data as { subject?: string; description?: string };\n if (thought.subject) {\n const a2uiMsg = thoughtToA2UI(thought, surfaceId);\n if (a2uiMsg) {\n messages.push(a2uiMsg);\n }\n } else if (thought.description) {\n messages.push(textPartToA2UI(thought.description, surfaceId));\n }\n } else if (\n coderAgentKind === CODER_AGENT_EVENT.TOOL_CALL_UPDATE ||\n coderAgentKind === CODER_AGENT_EVENT.TOOL_CALL_CONFIRMATION\n ) {\n const a2uiMsg = toolCallToA2UI(\n data as {\n request?: { name?: string; args?: Record<string, unknown> };\n status?: string;\n tool?: {\n name?: string;\n displayName?: string;\n description?: string;\n };\n response?: { content?: string };\n },\n surfaceId\n );\n if (a2uiMsg) {\n messages.push(a2uiMsg);\n }\n }\n // Note: TEXT_CONTENT events now use \"text\" parts (handled above), not \"data\" parts\n }\n }\n\n return messages;\n}\n\nfunction convertResponseToA2UI(response: SendStreamingMessageResponse): ServerToClientMessage[] {\n if (\"error\" in response) {\n return [];\n }\n\n const result = response.result;\n if (!result || !(\"kind\" in result) || result.kind !== \"status-update\") {\n return [];\n }\n\n const metadata = result.metadata as { coderAgent?: { kind?: string } } | undefined;\n const coderAgentKind = metadata?.coderAgent?.kind;\n\n // Skip state-change events without message content (submitted/working state transitions)\n if (coderAgentKind === CODER_AGENT_EVENT.STATE_CHANGE) {\n return [];\n }\n\n // Handle messages with parts (text, file, data, tool calls, thoughts, etc.)\n const parts = result.status?.message?.parts;\n if (!parts || parts.length === 0) {\n return [];\n }\n\n return convertA2APartsToA2UI(parts, coderAgentKind);\n}\n\n// ============ SSE Stream Handling ============\n\nasync function* parseSSEStream(\n streamResponse: StreamResponse\n): AsyncGenerator<SendStreamingMessageResponse, void, unknown> {\n const queue: SendStreamingMessageResponse[] = [];\n\n const parser = createParser({\n onEvent: (event) => {\n try {\n queue.push(JSON.parse(event.data));\n } catch (err) {\n console.error(\"[parseSSEStream] Parse error:\", err);\n // Ignore parse errors\n }\n },\n });\n\n try {\n while (true) {\n const chunk = await streamResponse.read();\n if (chunk === null) {\n break;\n }\n if (chunk) {\n parser.feed(chunk);\n while (queue.length > 0) {\n const item = queue.shift();\n if (item) {\n yield item;\n }\n }\n }\n }\n } catch (err) {\n console.error(\"[parseSSEStream] Stream error:\", err);\n // Ignore stream errors\n }\n}\n\n// ============ Client ============\n\nexport type CopilotA2UIClient = {\n /**\n * Stream A2UI messages from Copilot Agent.\n *\n * @example\n * ```typescript\n * import { createCopilotA2UIClient, Data } from \"@amaster.ai/copilot-client\";\n *\n * const client = createCopilotA2UIClient();\n * const processor = Data.createSignalA2uiMessageProcessor();\n *\n * for await (const messages of client.chat([{ role: \"user\", content: \"Hello\" }])) {\n * processor.processMessages(messages);\n * }\n * ```\n */\n chat(\n messages: ChatMessage[],\n options?: ChatOptions\n ): AsyncGenerator<ServerToClientMessage[], void, unknown>;\n\n cancelChat(taskId: string): Promise<ClientResult<CancelTaskResponse>>;\n getChatStatus(taskId: string): Promise<ClientResult<GetTaskResponse>>;\n};\n\n/**\n * Create Copilot A2UI client\n *\n * Auto-detects runtime environment (Browser/Vite/Taro H5/Taro Mini-program)\n */\nexport function createCopilotA2UIClient(\n http: HttpClient = createHttpClient(),\n baseUrl?: string,\n getAccessToken?: () => string | null\n): CopilotA2UIClient {\n let envBaseUrl = \"\";\n\n // Vite/H5:必须直接写 import.meta.env,Vite 才能正确处理\n const metaEnv = (import.meta as any)?.env;\n if (metaEnv) {\n envBaseUrl = metaEnv.TARO_APP_API_BASE_URL || metaEnv.VITE_API_BASE_URL || \"\";\n }\n\n // Taro 小程序 build:defineConstants 会把 process.env.xxx 替换为字面量\n // H5 环境:process 不存在会抛 ReferenceError,这里用 try/catch 吞掉\n if (!envBaseUrl) {\n try {\n envBaseUrl =\n process.env.TARO_APP_API_BASE_URL ||\n process.env.VITE_API_BASE_URL ||\n \"\";\n } catch {\n // process is not defined -> ignore\n }\n }\n\n envBaseUrl = String(envBaseUrl || \"\").trim();\n const url = `${baseUrl || envBaseUrl}/api/proxy/builtin/platform/copilot`;\n\n async function* sendMessageStream(\n request: SendStreamingMessageRequest\n ): AsyncGenerator<SendStreamingMessageResponse, void, unknown> {\n try {\n const streamResponse = await createStream(url, request, getAccessToken);\n\n if (!streamResponse.ok) {\n throw new Error(`Stream request failed: ${streamResponse.statusText}`);\n }\n\n yield* parseSSEStream(streamResponse);\n } catch (err) {\n console.error(\"[sendMessageStream] Error:\", err);\n // Ignore stream errors\n }\n }\n\n return {\n async *chat(messages, chatOptions = {}) {\n const { taskId } = chatOptions;\n\n const systemMsg = messages.find((m) => m.role === \"system\");\n const nonSystemMsgs = messages.filter((m) => m.role !== \"system\");\n const lastUserMsg = nonSystemMsgs[nonSystemMsgs.length - 1];\n\n const parts = lastUserMsg\n ? convertToA2AParts(lastUserMsg.content)\n : [{ kind: \"text\" as const, text: \"\" }];\n\n const systemPrompt = systemMsg ? extractTextFromContent(systemMsg.content) : undefined;\n\n const request: SendStreamingMessageRequest = {\n jsonrpc: \"2.0\",\n id: generateUUID(),\n method: \"message/stream\",\n params: {\n message: {\n contextId: getAppId(),\n kind: \"message\",\n messageId: generateUUID(),\n role: \"user\",\n parts,\n ...(taskId && { taskId }),\n ...(systemPrompt && { metadata: { systemPrompt } }),\n },\n },\n };\n\n for await (const response of sendMessageStream(request)) {\n const a2uiMessages = convertResponseToA2UI(response);\n if (a2uiMessages.length > 0) {\n yield a2uiMessages;\n }\n }\n },\n\n cancelChat(taskId) {\n const request: CancelTaskRequest = {\n jsonrpc: \"2.0\",\n id: generateUUID(),\n method: \"tasks/cancel\",\n params: { id: taskId },\n };\n return http.request<CancelTaskResponse>({\n url,\n method: \"POST\",\n data: request,\n });\n },\n\n getChatStatus(taskId) {\n const request: GetTaskRequest = {\n jsonrpc: \"2.0\",\n id: generateUUID(),\n method: \"tasks/get\",\n params: { id: taskId },\n };\n return http.request<GetTaskResponse>({\n url,\n method: \"POST\",\n data: request,\n });\n },\n };\n}\n","/**\n * A2UI Types - Inlined from @a2ui/lit for Taro compatibility\n *\n * This file contains the minimal A2UI type definitions needed by copilot-client.\n * We inline these types instead of importing from @a2ui/lit because @a2ui/lit\n * uses ES2025 `import ... with { type: \"json\" }` syntax which is not supported\n * by Taro's Vite/esbuild version.\n */\n\n// ============ Primitive Types ============\n\nexport interface StringValue {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n /** A fixed, hardcoded string value. */\n literalString?: string;\n /** A fixed, hardcoded string value. */\n literal?: string;\n}\n\nexport interface NumberValue {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n /** A fixed, hardcoded number value. */\n literalNumber?: number;\n /** A fixed, hardcoded number value. */\n literal?: number;\n}\n\nexport interface BooleanValue {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n /** A fixed, hardcoded boolean value. */\n literalBoolean?: boolean;\n /** A fixed, hardcoded boolean value. */\n literal?: boolean;\n}\n\n// ============ Component Types ============\n\nexport interface Action {\n /** A unique name identifying the action (e.g., 'submitForm'). */\n name: string;\n /** A key-value map of data bindings to be resolved when the action is triggered. */\n context?: {\n key: string;\n /** The dynamic value. Define EXACTLY ONE of the nested properties. */\n value: {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n /** A fixed, hardcoded string value. */\n literalString?: string;\n literalNumber?: number;\n literalBoolean?: boolean;\n };\n }[];\n}\n\nexport interface Text {\n text: StringValue;\n usageHint: \"h1\" | \"h2\" | \"h3\" | \"h4\" | \"h5\" | \"caption\" | \"body\";\n}\n\nexport interface Image {\n url: StringValue;\n usageHint: \"icon\" | \"avatar\" | \"smallFeature\" | \"mediumFeature\" | \"largeFeature\" | \"header\";\n fit?: \"contain\" | \"cover\" | \"fill\" | \"none\" | \"scale-down\";\n}\n\nexport interface Icon {\n name: StringValue;\n}\n\nexport interface Video {\n url: StringValue;\n}\n\nexport interface AudioPlayer {\n url: StringValue;\n /** A label, title, or placeholder text. */\n description?: StringValue;\n}\n\nexport interface Tabs {\n /** A list of tabs, each with a title and a child component ID. */\n tabItems: {\n /** The title of the tab. */\n title: {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n /** A fixed, hardcoded string value. */\n literalString?: string;\n };\n /** A reference to a component instance by its unique ID. */\n child: string;\n }[];\n}\n\nexport interface Divider {\n /** The orientation. */\n axis?: \"horizontal\" | \"vertical\";\n /** The color of the divider (e.g., hex code or semantic name). */\n color?: string;\n /** The thickness of the divider. */\n thickness?: number;\n}\n\nexport interface Modal {\n /** The ID of the component (e.g., a button) that triggers the modal. */\n entryPointChild: string;\n /** The ID of the component to display as the modal's content. */\n contentChild: string;\n}\n\nexport interface Button {\n /** The ID of the component to display as the button's content. */\n child: string;\n /** Represents a user-initiated action. */\n action: Action;\n}\n\nexport interface Checkbox {\n label: StringValue;\n value: {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n literalBoolean?: boolean;\n };\n}\n\nexport interface TextField {\n text?: StringValue;\n /** A label, title, or placeholder text. */\n label: StringValue;\n type?: \"shortText\" | \"number\" | \"date\" | \"longText\";\n /** A regex string to validate the input. */\n validationRegexp?: string;\n}\n\nexport interface DateTimeInput {\n value: StringValue;\n enableDate?: boolean;\n enableTime?: boolean;\n /** The string format for the output (e.g., 'YYYY-MM-DD'). */\n outputFormat?: string;\n}\n\nexport interface MultipleChoice {\n selections: {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n literalArray?: string[];\n };\n options?: {\n label: {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n /** A fixed, hardcoded string value. */\n literalString?: string;\n };\n value: string;\n }[];\n maxAllowedSelections?: number;\n}\n\nexport interface Slider {\n value: {\n /** A data binding reference to a location in the data model (e.g., '/user/name'). */\n path?: string;\n literalNumber?: number;\n };\n minValue?: number;\n maxValue?: number;\n}\n\n// ============ Data Model Types ============\n\n/** A recursive type for any valid JSON-like value in the data model. */\nexport type DataValue = string | number | boolean | null | DataMap | DataObject | DataArray;\nexport type DataObject = { [key: string]: DataValue };\nexport type DataMap = Map<string, DataValue>;\nexport type DataArray = DataValue[];\n\n/** A template for creating components from a list in the data model. */\nexport interface ComponentArrayTemplate {\n componentId: string;\n dataBinding: string;\n}\n\n/** Defines a list of child components, either explicitly or via a template. */\nexport interface ComponentArrayReference {\n explicitList?: string[];\n template?: ComponentArrayTemplate;\n}\n\n/** Represents the general shape of a component's properties. */\nexport type ComponentProperties = {\n children?: ComponentArrayReference;\n child?: string;\n [k: string]: unknown;\n};\n\n/** A raw component instance from a SurfaceUpdate message. */\nexport interface ComponentInstance {\n id: string;\n weight?: number;\n component?: ComponentProperties;\n}\n\nexport type ValueMap = DataObject & {\n key: string;\n /** May be JSON */\n valueString?: string;\n valueNumber?: number;\n valueBoolean?: boolean;\n valueMap?: ValueMap[];\n};\n\n// ============ Message Types ============\n\nexport interface BeginRenderingMessage {\n surfaceId: string;\n root: string;\n styles?: Record<string, string>;\n}\n\nexport interface SurfaceUpdateMessage {\n surfaceId: string;\n components: ComponentInstance[];\n}\n\nexport interface DataModelUpdate {\n surfaceId: string;\n path?: string;\n contents: ValueMap[];\n}\n\nexport interface DeleteSurfaceMessage {\n surfaceId: string;\n}\n\nexport interface ServerToClientMessage {\n beginRendering?: BeginRenderingMessage;\n surfaceUpdate?: SurfaceUpdateMessage;\n dataModelUpdate?: DataModelUpdate;\n deleteSurface?: DeleteSurfaceMessage;\n}\n\n// ============ Component Node Types ============\n\n/** A recursive type for any value that can appear within a resolved component tree. */\nexport type ResolvedValue =\n | string\n | number\n | boolean\n | null\n | AnyComponentNode\n | ResolvedMap\n | ResolvedArray;\n\n/** A generic map where each value has been recursively resolved. */\nexport type ResolvedMap = { [key: string]: ResolvedValue };\n\n/** A generic array where each item has been recursively resolved. */\nexport type ResolvedArray = ResolvedValue[];\n\n/** A base interface that all component nodes share. */\ninterface BaseComponentNode {\n id: string;\n weight?: number;\n dataContextPath?: string;\n slotName?: string;\n}\n\nexport interface TextNode extends BaseComponentNode {\n type: \"Text\";\n properties: Text;\n}\n\nexport interface ImageNode extends BaseComponentNode {\n type: \"Image\";\n properties: Image;\n}\n\nexport interface IconNode extends BaseComponentNode {\n type: \"Icon\";\n properties: Icon;\n}\n\nexport interface VideoNode extends BaseComponentNode {\n type: \"Video\";\n properties: Video;\n}\n\nexport interface AudioPlayerNode extends BaseComponentNode {\n type: \"AudioPlayer\";\n properties: AudioPlayer;\n}\n\nexport interface RowNode extends BaseComponentNode {\n type: \"Row\";\n properties: ResolvedRow;\n}\n\nexport interface ColumnNode extends BaseComponentNode {\n type: \"Column\";\n properties: ResolvedColumn;\n}\n\nexport interface ListNode extends BaseComponentNode {\n type: \"List\";\n properties: ResolvedList;\n}\n\nexport interface CardNode extends BaseComponentNode {\n type: \"Card\";\n properties: ResolvedCard;\n}\n\nexport interface TabsNode extends BaseComponentNode {\n type: \"Tabs\";\n properties: ResolvedTabs;\n}\n\nexport interface DividerNode extends BaseComponentNode {\n type: \"Divider\";\n properties: Divider;\n}\n\nexport interface ModalNode extends BaseComponentNode {\n type: \"Modal\";\n properties: ResolvedModal;\n}\n\nexport interface ButtonNode extends BaseComponentNode {\n type: \"Button\";\n properties: ResolvedButton;\n}\n\nexport interface CheckboxNode extends BaseComponentNode {\n type: \"CheckBox\";\n properties: Checkbox;\n}\n\nexport interface TextFieldNode extends BaseComponentNode {\n type: \"TextField\";\n properties: TextField;\n}\n\nexport interface DateTimeInputNode extends BaseComponentNode {\n type: \"DateTimeInput\";\n properties: DateTimeInput;\n}\n\nexport interface MultipleChoiceNode extends BaseComponentNode {\n type: \"MultipleChoice\";\n properties: MultipleChoice;\n}\n\nexport interface SliderNode extends BaseComponentNode {\n type: \"Slider\";\n properties: Slider;\n}\n\nexport interface CustomNode extends BaseComponentNode {\n type: string;\n properties: CustomNodeProperties;\n}\n\n/**\n * The complete discriminated union of all possible resolved component nodes.\n * A renderer would use this type for any given node in the component tree.\n */\nexport type AnyComponentNode =\n | TextNode\n | IconNode\n | ImageNode\n | VideoNode\n | AudioPlayerNode\n | RowNode\n | ColumnNode\n | ListNode\n | CardNode\n | TabsNode\n | DividerNode\n | ModalNode\n | ButtonNode\n | CheckboxNode\n | TextFieldNode\n | DateTimeInputNode\n | MultipleChoiceNode\n | SliderNode\n | CustomNode;\n\nexport interface ResolvedRow {\n children: AnyComponentNode[];\n distribution?: \"start\" | \"center\" | \"end\" | \"spaceBetween\" | \"spaceAround\" | \"spaceEvenly\";\n alignment?: \"start\" | \"center\" | \"end\" | \"stretch\";\n}\n\nexport interface ResolvedColumn {\n children: AnyComponentNode[];\n distribution?: \"start\" | \"center\" | \"end\" | \"spaceBetween\" | \"spaceAround\" | \"spaceEvenly\";\n alignment?: \"start\" | \"center\" | \"end\" | \"stretch\";\n}\n\nexport interface ResolvedButton {\n child: AnyComponentNode;\n action: Button[\"action\"];\n}\n\nexport interface ResolvedList {\n children: AnyComponentNode[];\n direction?: \"vertical\" | \"horizontal\";\n alignment?: \"start\" | \"center\" | \"end\" | \"stretch\";\n}\n\nexport interface ResolvedCard {\n child: AnyComponentNode;\n children: AnyComponentNode[];\n}\n\nexport interface ResolvedTabItem {\n title: StringValue;\n child: AnyComponentNode;\n}\n\nexport interface ResolvedTabs {\n tabItems: ResolvedTabItem[];\n}\n\nexport interface ResolvedModal {\n entryPointChild: AnyComponentNode;\n contentChild: AnyComponentNode;\n}\n\nexport interface CustomNodeProperties {\n [k: string]: ResolvedValue;\n}\n\nexport type SurfaceID = string;\n\n/** The complete state of a single UI surface. */\nexport interface Surface {\n rootComponentId: string | null;\n componentTree: AnyComponentNode | null;\n dataModel: DataMap;\n components: Map<string, ComponentInstance>;\n styles: Record<string, string>;\n}\n\n// ============ MessageProcessor Interface ============\n\nexport interface MessageProcessor {\n getSurfaces(): ReadonlyMap<string, Surface>;\n clearSurfaces(): void;\n processMessages(messages: ServerToClientMessage[]): void;\n /**\n * Retrieves the data for a given component node and a relative path string.\n * This correctly handles the special `.` path, which refers to the node's\n * own data context.\n */\n getData(node: AnyComponentNode, relativePath: string, surfaceId: string): DataValue | null;\n setData(\n node: AnyComponentNode | null,\n relativePath: string,\n value: DataValue,\n surfaceId: string\n ): void;\n resolvePath(path: string, dataContextPath?: string): string;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amaster.ai/copilot-client",
3
- "version": "1.1.0-beta.4",
3
+ "version": "1.1.0-beta.41",
4
4
  "description": "AI copilot chat client with streaming support",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -32,7 +32,9 @@
32
32
  },
33
33
  "dependencies": {
34
34
  "eventsource-parser": "^3.0.6",
35
- "@amaster.ai/http-client": "1.1.0-beta.4"
35
+ "miniprogram-text-decoder": "^2.0.0",
36
+ "miniprogram-text-encoder": "^2.0.0",
37
+ "@amaster.ai/http-client": "1.1.0-beta.41"
36
38
  },
37
39
  "peerDependencies": {
38
40
  "@a2a-js/sdk": "^0.3.7"