@qfei-design/make-ai-assistant 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ "use strict";const $=(t,e)=>{let r=0;for(const a of t)if(r+=1,r>e)break;return r};const o={actions:10,comparisonItems:24,jsonCharacters:1e6,jsonDepth:64,jsonNodes:1e4,rankingItems:50,recordColumns:20,recordListRecords:100,recordValues:100,textCharacters:2e4,trendPointsPerSeries:120,trendSeries:8,validationIssues:100},l={artifactsPerRun:50,assistantMessagesPerRun:20,historyArtifacts:500,historyCharacters:1e6,historyMessages:200,identifierCharacters:1e3,messageCharacters:1e5},K=["metric","comparison","trend","ranking","record-list","notice"],C=()=>({success:!1,issues:[{path:"",message:"could not be safely inspected"}]}),D=new Set(["navigate","open-record","open-list","invoke"]),F=new Set(["decimal","currency","percent"]);class M extends Array{push(...e){const r=o.validationIssues-this.length;return r>0?super.push(...e.slice(0,r)):this.length}}const c=t=>(()=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null})(),x=t=>typeof t=="string"&&t.trim().length>0,T=(t,e)=>{let r=0;for(const a of t)if(r+=1,r>e)return r;return r},u=t=>typeof t=="string"&&T(t,o.textCharacters)<=o.textCharacters,b=t=>typeof t=="number"&&Number.isFinite(t),L=t=>t.length<=120?t:`${t.slice(0,117)}...`,m=(t,e,r)=>{x(t)?u(t)||r.push({path:e,message:`must contain at most ${o.textCharacters} characters`}):r.push({path:e,message:"must be a non-empty string"})},I=(t,e,r)=>{t!==void 0&&typeof t!="string"?r.push({path:e,message:"must be a string"}):typeof t=="string"&&!u(t)&&r.push({path:e,message:`must contain at most ${o.textCharacters} characters`})},d=(t,e,r,a)=>{for(const s in t)if(Object.prototype.hasOwnProperty.call(t,s)){if(a.length>=o.validationIssues)break;e.has(s)||a.push({path:L(r?`${r}.${s}`:s),message:"is not supported"})}},A=(t,e,r,a)=>t.length>e?(a.push({path:r,message:`must contain at most ${e} items`}),!0):!1,E=(t,e,r)=>{for(let a=0;a<t.length;a+=1)if(!Object.prototype.hasOwnProperty.call(t,a))return r.push({path:e,message:"must not contain empty array slots"}),!0;return!1},S=(t,e,r,a)=>{const s=new Set;t.forEach((n,f)=>{if(!c(n)||typeof n[e]!="string")return;const i=n[e];s.has(i)?a.push({path:`${r}[${f}].${e}`,message:"must be unique within the collection"}):s.add(i)})},q=new Set(["schemaVersion","id","kind","title","summary","presentation","actions","meta","data"]),U=new Set(["template","density"]),z=new Set(["style","currency","precision","unit"]),J=new Set(["id","label","intent","target","appearance"]),H=new Set(["value","format","delta","context"]),B=new Set(["value","format","direction","label"]),P=new Set(["items"]),W=new Set(["id","label","value","format","hint"]),G=new Set(["series"]),Q=new Set(["id","label","points","format"]),X=new Set(["x","y"]),Z=new Set(["id","label","value","format","description"]),tt=new Set(["entity","columns","records","total"]),et=new Set(["key","label"]),rt=new Set(["key","label","format"]),nt=new Set(["id","title","values","action"]),at=new Set(["tone","body"]),w=(t,e,r)=>c(t)?(d(t,z,e,r),t.style!==void 0&&(typeof t.style!="string"||!F.has(t.style))&&r.push({path:`${e}.style`,message:"is not supported"}),t.currency!==void 0&&m(t.currency,`${e}.currency`,r),t.precision!==void 0&&(!Number.isInteger(t.precision)||Number(t.precision)<0||Number(t.precision)>20)&&r.push({path:`${e}.precision`,message:"must be an integer between 0 and 20"}),I(t.unit,`${e}.unit`,r),!0):(r.push({path:e,message:"must be an object"}),!1),R=t=>{const e=[{kind:"visit",depth:0,value:t}],r=new WeakSet;let a=0,s=0;try{for(;e.length>0;){const n=e.pop();if(!n)break;if(n.kind==="leave"){r.delete(n.value);continue}if(s+=1,s>o.jsonNodes||n.depth>o.jsonDepth)return!1;if(n.value===null||typeof n.value=="boolean")continue;if(typeof n.value=="string"){if(a+=T(n.value,o.textCharacters),!u(n.value)||a>o.jsonCharacters)return!1;continue}if(typeof n.value=="number"){if(!Number.isFinite(n.value))return!1;continue}if(!Array.isArray(n.value)&&!c(n.value)||r.has(n.value))return!1;r.add(n.value),e.push({kind:"leave",value:n.value});const f=o.jsonNodes-s;if(Array.isArray(n.value)){if(n.value.length>f)return!1;for(let i=n.value.length-1;i>=0;i-=1)e.push({kind:"visit",depth:n.depth+1,value:n.value[i]})}else{const i=[];for(const h in n.value)if(Object.prototype.hasOwnProperty.call(n.value,h)){if(!u(h)||(a+=T(h,o.textCharacters),a>o.jsonCharacters)||i.length>=f)return!1;i.push(h)}for(let h=i.length-1;h>=0;h-=1){const y=i[h];e.push({kind:"visit",depth:n.depth+1,value:n.value[y]})}}}return!0}catch{return!1}},st=t=>t===null||typeof t=="boolean"||u(t)||b(t),Y=(t,e,r)=>c(t)?(d(t,J,e,r),m(t.id,`${e}.id`,r),m(t.label,`${e}.label`,r),(typeof t.intent!="string"||!D.has(t.intent))&&r.push({path:`${e}.intent`,message:"is not supported"}),(!c(t.target)||!R(t.target))&&r.push({path:`${e}.target`,message:"must be a JSON object"}),t.appearance!==void 0&&(typeof t.appearance!="string"||!["primary","secondary","link"].includes(t.appearance))&&r.push({path:`${e}.appearance`,message:"is not supported"}),!0):(r.push({path:e,message:"must be an object"}),!1),ot=(t,e)=>{if(d(t,q,"",e),t.schemaVersion!=="1.0"&&e.push({path:"schemaVersion",message:"must equal 1.0"}),m(t.id,"id",e),K.includes(t.kind)||e.push({path:"kind",message:"is not a supported Artifact kind"}),I(t.title,"title",e),I(t.summary,"summary",e),t.presentation!==void 0&&(c(t.presentation)?(d(t.presentation,U,"presentation",e),t.presentation.template!==void 0&&!x(t.presentation.template)?e.push({path:"presentation.template",message:"must be a non-empty string"}):t.presentation.template!==void 0&&!u(t.presentation.template)&&e.push({path:"presentation.template",message:`must contain at most ${o.textCharacters} characters`}),t.presentation.density!==void 0&&(typeof t.presentation.density!="string"||!["compact","comfortable"].includes(t.presentation.density))&&e.push({path:"presentation.density",message:"is not supported"})):e.push({path:"presentation",message:"must be an object"})),t.actions!==void 0){if(!Array.isArray(t.actions))e.push({path:"actions",message:"must be an array"});else if(!A(t.actions,o.actions,"actions",e)){if(E(t.actions,"actions",e))return;S(t.actions,"id","actions",e),t.actions.forEach((a,s)=>Y(a,`actions[${s}]`,e))}}t.meta!==void 0&&(!c(t.meta)||!R(t.meta))&&e.push({path:"meta",message:"must be a JSON object"})},it=(t,e)=>{d(t,H,"data",e),!b(t.value)&&!u(t.value)&&e.push({path:"data.value",message:"must be a finite number or string"}),t.format!==void 0&&w(t.format,"data.format",e),t.delta!==void 0&&(c(t.delta)?(d(t.delta,B,"data.delta",e),b(t.delta.value)||e.push({path:"data.delta.value",message:"must be a finite number"}),t.delta.direction!==void 0&&(typeof t.delta.direction!="string"||!["up","down","flat"].includes(t.delta.direction))&&e.push({path:"data.delta.direction",message:"is not supported"}),t.delta.format!==void 0&&(typeof t.delta.format!="string"||!["decimal","percent"].includes(t.delta.format))&&e.push({path:"data.delta.format",message:"is not supported"}),I(t.delta.label,"data.delta.label",e)):e.push({path:"data.delta",message:"must be an object"})),I(t.context,"data.context",e)},ct=(t,e)=>{if(d(t,P,"data",e),!Array.isArray(t.items)||t.items.length===0){e.push({path:"data.items",message:"must be a non-empty array"});return}A(t.items,o.comparisonItems,"data.items",e)||E(t.items,"data.items",e)||(S(t.items,"id","data.items",e),t.items.forEach((r,a)=>{const s=`data.items[${a}]`;if(!c(r)){e.push({path:s,message:"must be an object"});return}d(r,W,s,e),m(r.id,`${s}.id`,e),m(r.label,`${s}.label`,e),!b(r.value)&&!u(r.value)&&e.push({path:`${s}.value`,message:"must be a finite number or string"}),r.format!==void 0&&w(r.format,`${s}.format`,e),I(r.hint,`${s}.hint`,e)}))},dt=(t,e)=>{if(d(t,G,"data",e),!Array.isArray(t.series)||t.series.length===0){e.push({path:"data.series",message:"must be a non-empty array"});return}A(t.series,o.trendSeries,"data.series",e)||E(t.series,"data.series",e)||(S(t.series,"id","data.series",e),t.series.forEach((r,a)=>{const s=`data.series[${a}]`;if(!c(r)){e.push({path:s,message:"must be an object"});return}if(d(r,Q,s,e),m(r.id,`${s}.id`,e),m(r.label,`${s}.label`,e),r.format!==void 0&&w(r.format,`${s}.format`,e),!Array.isArray(r.points)||r.points.length===0){e.push({path:`${s}.points`,message:"must be a non-empty array"});return}A(r.points,o.trendPointsPerSeries,`${s}.points`,e)||E(r.points,`${s}.points`,e)||r.points.forEach((n,f)=>{const i=`${s}.points[${f}]`;if(!c(n)){e.push({path:i,message:"must be an object"});return}d(n,X,i,e),!b(n.x)&&!u(n.x)&&e.push({path:`${i}.x`,message:"must be a finite number or string"}),b(n.y)||e.push({path:`${i}.y`,message:"must be a finite number"})})}))},pt=(t,e)=>{if(d(t,P,"data",e),!Array.isArray(t.items)||t.items.length===0){e.push({path:"data.items",message:"must be a non-empty array"});return}A(t.items,o.rankingItems,"data.items",e)||E(t.items,"data.items",e)||(S(t.items,"id","data.items",e),t.items.forEach((r,a)=>{const s=`data.items[${a}]`;if(!c(r)){e.push({path:s,message:"must be an object"});return}d(r,Z,s,e),m(r.id,`${s}.id`,e),m(r.label,`${s}.label`,e),b(r.value)||e.push({path:`${s}.value`,message:"must be a finite number"}),r.format!==void 0&&w(r.format,`${s}.format`,e),I(r.description,`${s}.description`,e)}))},mt=(t,e)=>{if(d(t,tt,"data",e),c(t.entity)?(d(t.entity,et,"data.entity",e),m(t.entity.key,"data.entity.key",e),I(t.entity.label,"data.entity.label",e)):e.push({path:"data.entity",message:"must be an object"}),!Array.isArray(t.columns)||t.columns.length===0)e.push({path:"data.columns",message:"must be a non-empty array"});else if(!A(t.columns,o.recordColumns,"data.columns",e)){if(E(t.columns,"data.columns",e))return;S(t.columns,"key","data.columns",e),t.columns.forEach((a,s)=>{const n=`data.columns[${s}]`;if(!c(a)){e.push({path:n,message:"must be an object"});return}d(a,rt,n,e),m(a.key,`${n}.key`,e),m(a.label,`${n}.label`,e),a.format!==void 0&&w(a.format,`${n}.format`,e)})}if(!Array.isArray(t.records))e.push({path:"data.records",message:"must be an array"});else if(!A(t.records,o.recordListRecords,"data.records",e)){if(E(t.records,"data.records",e))return;S(t.records,"id","data.records",e),t.records.forEach((a,s)=>{const n=`data.records[${s}]`;if(!c(a)){e.push({path:n,message:"must be an object"});return}if(d(a,nt,n,e),m(a.id,`${n}.id`,e),I(a.title,`${n}.title`,e),!c(a.values))e.push({path:`${n}.values`,message:"must contain only JSON primitive display values"});else{const f=a.values;let i=!1,h=0;for(const y in f)if(Object.prototype.hasOwnProperty.call(f,y)){if(h+=1,h>o.recordValues)break;i||=!u(y)||!st(f[y])}h>o.recordValues?e.push({path:`${n}.values`,message:`must contain at most ${o.recordValues} values`}):i&&e.push({path:`${n}.values`,message:"must contain only JSON primitive display values"})}a.action!==void 0&&Y(a.action,`${n}.action`,e)})}t.total!==void 0&&(!Number.isInteger(t.total)||Number(t.total)<0)&&e.push({path:"data.total",message:"must be a non-negative integer"})},ft=(t,e)=>{d(t,at,"data",e),(typeof t.tone!="string"||!["info","success","warning","danger"].includes(t.tone))&&e.push({path:"data.tone",message:"is not supported"}),m(t.body,"data.body",e)},j=(t,e)=>{if(ot(t,e),!c(t.data)){e.push({path:"data",message:"must be an object"});return}switch(t.kind){case"metric":it(t.data,e);break;case"comparison":ct(t.data,e);break;case"trend":dt(t.data,e);break;case"ranking":pt(t.data,e);break;case"record-list":mt(t.data,e);break;case"notice":ft(t.data,e);break}},V=t=>{const e=new M;try{if(!c(t))return{success:!1,issues:[{path:"",message:"must be an object"}]};j(t,e)}catch{return C()}if(e.length>0)return{success:!1,issues:e};if(!R(t))return{success:!1,issues:[{path:"",message:"exceeds the Artifact resource budget"}]};let r;try{r=structuredClone(t)}catch{return C()}const a=new M;try{if(!c(r))return C();j(r,a)}catch{return C()}return a.length===0&&!R(r)&&a.push({path:"",message:"exceeds the Artifact resource budget"}),a.length===0?{success:!0,artifact:r}:{success:!1,issues:a}},k=t=>{const e=V(t);if(e.success)return e.artifact;const r=e.issues.map(a=>`${a.path||"artifact"} ${a.message}`).join(", ");throw new Error(`Invalid Make AI Artifact: ${r}`)},N=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),g=(t,e)=>{if(Object.keys(t).some(r=>!e.has(r)))throw new Error("Invalid assistant event: unsupported field")},p=(t,e,r=l.identifierCharacters)=>{const a=typeof t=="string"?$(t,r):0;if(typeof t!="string"||!t.trim()||a>r)throw new Error(`Invalid assistant event: ${e}`);return t},ht=t=>{if(!N(t)||typeof t.type!="string")throw new Error("Invalid assistant event: data");switch(t.type){case"message.start":return g(t,new Set(["type","runId","messageId"])),{type:t.type,runId:p(t.runId,"runId"),messageId:p(t.messageId,"messageId")};case"message.delta":if(g(t,new Set(["type","messageId","delta"])),typeof t.delta!="string")throw new Error("Invalid assistant event: delta");return{type:t.type,messageId:p(t.messageId,"messageId"),delta:t.delta};case"message.replace":return g(t,new Set(["type","messageId","content"])),{type:t.type,messageId:p(t.messageId,"messageId"),content:p(t.content,"content",l.messageCharacters)};case"message.complete":return g(t,new Set(["type","messageId"])),{type:t.type,messageId:p(t.messageId,"messageId")};case"artifact":return g(t,new Set(["type","messageId","artifact"])),{type:t.type,messageId:p(t.messageId,"messageId"),artifact:k(t.artifact)};case"run.progress":return g(t,new Set(["type","runId","message"])),{type:t.type,runId:p(t.runId,"runId"),message:p(t.message,"message",l.messageCharacters)};case"error":if(g(t,new Set(["type","code","message","retryable","requestId"])),typeof t.retryable!="boolean")throw new Error("Invalid assistant event: retryable");return{type:t.type,code:p(t.code,"code"),message:p(t.message,"message",l.messageCharacters),retryable:t.retryable,requestId:t.requestId===void 0?void 0:p(t.requestId,"requestId")};case"run.cancelled":return g(t,new Set(["type","runId"])),{type:t.type,runId:t.runId===void 0?void 0:p(t.runId,"runId")};case"run.complete":return g(t,new Set(["type","runId","threadId"])),{type:t.type,runId:p(t.runId,"runId"),threadId:p(t.threadId,"threadId")};default:throw new Error("Invalid assistant event: unsupported type")}},lt=t=>{try{return ht(t)}catch(e){throw e instanceof Error&&(e.message.startsWith("Invalid assistant event:")||e.message.startsWith("Invalid Make AI Artifact:"))?e:new Error("Invalid assistant event: data")}},gt=t=>{if(!N(t))throw new Error("Invalid assistant conversation snapshot: data");if(g(t,new Set(["threadId","messages"])),!Array.isArray(t.messages)||t.messages.length>l.historyMessages)throw new Error("Invalid assistant conversation snapshot: messages");const e=new Set;let r=0,a=0;return{messages:t.messages.map(n=>{if(!N(n))throw new Error("Invalid assistant conversation snapshot: message");g(n,new Set(["id","role","content","artifacts"]));const f=p(n.id,"messageId");if(e.has(f))throw new Error("Invalid assistant conversation snapshot: duplicate message id");if(e.add(f),n.role!=="assistant"&&n.role!=="user")throw new Error("Invalid assistant conversation snapshot: role");const i=n.role,h=typeof n.content=="string"?$(n.content,l.messageCharacters):0;if(typeof n.content!="string"||h>l.messageCharacters)throw new Error("Invalid assistant conversation snapshot: content");if(r+=$(n.content,l.historyCharacters-r),r>l.historyCharacters)throw new Error("Invalid assistant conversation snapshot: content budget");if(n.artifacts!==void 0&&(!Array.isArray(n.artifacts)||n.artifacts.length>l.artifactsPerRun))throw new Error("Invalid assistant conversation snapshot: artifacts");const y=(n.artifacts??[]).map(k),O=new Set;for(const v of y){if(O.has(v.id))throw new Error("Invalid assistant conversation snapshot: duplicate artifact id");O.add(v.id)}if(a+=y.length,a>l.historyArtifacts)throw new Error("Invalid assistant conversation snapshot: artifact budget");return{id:f,role:i,content:n.content,artifacts:y,status:"complete"}}),status:"idle",threadId:t.threadId===void 0?void 0:p(t.threadId,"threadId")}},ut=t=>t===void 0?{messages:[],status:"idle"}:gt(t),yt=(t,e)=>({...t,error:void 0,progress:void 0,status:"streaming",messages:[...t.messages,{id:e.id,role:"user",content:e.content,artifacts:[],status:"complete"}]}),_=(t,e,r)=>({...t,messages:t.messages.map(a=>a.id===e?r(a):a)}),It=(t,e)=>{switch(e.type){case"message.start":return{...t,activeRunId:e.runId,error:void 0,progress:void 0,status:"streaming",messages:[...t.messages,{id:e.messageId,role:"assistant",content:"",artifacts:[],status:"streaming"}]};case"message.delta":return _(t,e.messageId,r=>({...r,content:`${r.content}${e.delta}`}));case"message.replace":return _(t,e.messageId,r=>({...r,content:e.content}));case"artifact":return _(t,e.messageId,r=>({...r,artifacts:[...r.artifacts,e.artifact]}));case"message.complete":return _(t,e.messageId,r=>({...r,status:"complete"}));case"run.progress":return{...t,progress:{runId:e.runId,message:e.message}};case"error":return{...t,activeRunId:void 0,error:{code:e.code,message:e.message,retryable:e.retryable,requestId:e.requestId},progress:void 0,messages:t.messages.map(r=>r.status==="streaming"?{...r,status:"complete"}:r),status:"error"};case"run.cancelled":return{...t,activeRunId:void 0,progress:void 0,status:"idle",messages:t.messages.map(r=>r.status==="streaming"?{...r,status:"complete"}:r)};case"run.complete":return{...t,activeRunId:void 0,error:void 0,progress:void 0,messages:t.messages.map(r=>r.status==="streaming"?{...r,status:"complete"}:r),status:"idle",threadId:e.threadId}}};exports.MAKE_AI_ARTIFACT_KINDS=K;exports.MAKE_AI_ARTIFACT_LIMITS=o;exports.MAKE_AI_ARTIFACT_SCHEMA_VERSION="1.0";exports.MAKE_AI_CONVERSATION_LIMITS=l;exports.appendUserMessage=yt;exports.countCodePointsUpTo=$;exports.createAssistantConversationState=ut;exports.parseArtifact=k;exports.parseAssistantEvent=lt;exports.reduceAssistantEvent=It;exports.validateArtifact=V;
@@ -11,7 +11,24 @@ export interface AssistantRunRequest {
11
11
  export interface AssistantTransportOptions {
12
12
  signal?: AbortSignal;
13
13
  }
14
+ export interface AssistantTransportFeatures {
15
+ history: boolean;
16
+ newConversation: boolean;
17
+ remoteCancellation: boolean;
18
+ }
19
+ export interface AssistantConversationSnapshotMessage {
20
+ id: string;
21
+ role: "assistant" | "user";
22
+ content: string;
23
+ artifacts?: ReadonlyArray<MakeAiArtifact>;
24
+ }
25
+ export interface AssistantConversationSnapshot {
26
+ threadId?: string;
27
+ messages: ReadonlyArray<AssistantConversationSnapshotMessage>;
28
+ }
14
29
  export interface AssistantTransport {
30
+ readonly features?: Partial<AssistantTransportFeatures>;
31
+ loadConversation?(context: MakeAssistantHostContext, options?: AssistantTransportOptions): Promise<AssistantConversationSnapshot>;
15
32
  run(request: AssistantRunRequest, options?: AssistantTransportOptions): AsyncIterable<AssistantEvent>;
16
33
  }
17
34
  export type AssistantEvent = {
@@ -22,6 +39,10 @@ export type AssistantEvent = {
22
39
  type: "message.delta";
23
40
  messageId: string;
24
41
  delta: string;
42
+ } | {
43
+ type: "message.replace";
44
+ messageId: string;
45
+ content: string;
25
46
  } | {
26
47
  type: "artifact";
27
48
  messageId: string;
@@ -29,6 +50,10 @@ export type AssistantEvent = {
29
50
  } | {
30
51
  type: "message.complete";
31
52
  messageId: string;
53
+ } | {
54
+ type: "run.progress";
55
+ runId: string;
56
+ message: string;
32
57
  } | {
33
58
  type: "error";
34
59
  code: string;
@@ -61,10 +86,14 @@ export interface AssistantConversationState {
61
86
  activeRunId?: string;
62
87
  error?: AssistantConversationError;
63
88
  messages: AssistantMessage[];
89
+ progress?: {
90
+ runId: string;
91
+ message: string;
92
+ };
64
93
  status: "idle" | "streaming" | "error";
65
94
  threadId?: string;
66
95
  }
67
- export declare const createAssistantConversationState: () => AssistantConversationState;
96
+ export declare const createAssistantConversationState: (snapshot?: AssistantConversationSnapshot) => AssistantConversationState;
68
97
  export declare const appendUserMessage: (state: AssistantConversationState, message: {
69
98
  id: string;
70
99
  content: string;
@@ -21,6 +21,9 @@ export declare const MAKE_AI_ARTIFACT_LIMITS: {
21
21
  export declare const MAKE_AI_CONVERSATION_LIMITS: {
22
22
  readonly artifactsPerRun: 50;
23
23
  readonly assistantMessagesPerRun: 20;
24
+ readonly historyArtifacts: 500;
25
+ readonly historyCharacters: 1000000;
26
+ readonly historyMessages: 200;
24
27
  readonly identifierCharacters: 1000;
25
28
  readonly messageCharacters: 100000;
26
29
  };
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("./conversation-DpYszfVd.cjs"),p=r=>{const e=new Set;for(const t of r){if(!t.id.trim())throw new Error("Artifact template id must not be empty");if(e.has(t.id))throw new Error(`Duplicate artifact template id: ${t.id}`);if(t.kinds.length===0)throw new Error(`Artifact template must support at least one kind: ${t.id}`);if(t.kinds.some(n=>!i.MAKE_AI_ARTIFACT_KINDS.includes(n)))throw new Error(`Unsupported Artifact template kind: ${t.id}`);if(t.priority!==void 0&&!Number.isFinite(t.priority))throw new Error(`Artifact template priority must be finite: ${t.id}`);if(typeof t.render!="function")throw new Error(`Artifact template render must be a function: ${t.id}`);if(t.canRender!==void 0&&typeof t.canRender!="function")throw new Error(`Artifact template canRender must be a function: ${t.id}`);e.add(t.id)}},c=(r=[])=>{p(r);const e=r.map(t=>Object.freeze({...t,kinds:Object.freeze([...t.kinds])}));return Object.freeze({templates:Object.freeze(e)})},d=(r,e)=>c([...r.templates,...e]),A=(r,e,t)=>r.kinds.includes(e.kind)&&(r.canRender?.(e,t)??!0),f=(r,e,t)=>{const n=e.presentation?.template;if(n){const a=r.templates.find(s=>s.id===n&&A(s,e,t));if(a)return{template:a,reason:"requested"}}const o=r.templates.map((a,s)=>({template:a,registrationIndex:s})).filter(({template:a})=>A(a,e,t)).sort((a,s)=>(s.template.priority??0)-(a.template.priority??0)||a.registrationIndex-s.registrationIndex);return o[0]?{template:o[0].template,reason:"priority"}:void 0},l=r=>({artifactSchemaVersions:[i.MAKE_AI_ARTIFACT_SCHEMA_VERSION],artifactKinds:Array.from(new Set(r.templates.flatMap(e=>e.kinds))).sort(),templates:r.templates.map(e=>e.id).sort()});exports.MAKE_AI_ARTIFACT_KINDS=i.MAKE_AI_ARTIFACT_KINDS;exports.MAKE_AI_ARTIFACT_LIMITS=i.MAKE_AI_ARTIFACT_LIMITS;exports.MAKE_AI_ARTIFACT_SCHEMA_VERSION=i.MAKE_AI_ARTIFACT_SCHEMA_VERSION;exports.MAKE_AI_CONVERSATION_LIMITS=i.MAKE_AI_CONVERSATION_LIMITS;exports.appendUserMessage=i.appendUserMessage;exports.createAssistantConversationState=i.createAssistantConversationState;exports.parseArtifact=i.parseArtifact;exports.parseAssistantEvent=i.parseAssistantEvent;exports.reduceAssistantEvent=i.reduceAssistantEvent;exports.validateArtifact=i.validateArtifact;exports.createArtifactCapabilities=l;exports.createArtifactTemplateRegistry=c;exports.extendArtifactTemplateRegistry=d;exports.resolveArtifactTemplate=f;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("./conversation-Yku9Lzj_.cjs"),p=r=>{const e=new Set;for(const t of r){if(!t.id.trim())throw new Error("Artifact template id must not be empty");if(e.has(t.id))throw new Error(`Duplicate artifact template id: ${t.id}`);if(t.kinds.length===0)throw new Error(`Artifact template must support at least one kind: ${t.id}`);if(t.kinds.some(n=>!i.MAKE_AI_ARTIFACT_KINDS.includes(n)))throw new Error(`Unsupported Artifact template kind: ${t.id}`);if(t.priority!==void 0&&!Number.isFinite(t.priority))throw new Error(`Artifact template priority must be finite: ${t.id}`);if(typeof t.render!="function")throw new Error(`Artifact template render must be a function: ${t.id}`);if(t.canRender!==void 0&&typeof t.canRender!="function")throw new Error(`Artifact template canRender must be a function: ${t.id}`);e.add(t.id)}},c=(r=[])=>{p(r);const e=r.map(t=>Object.freeze({...t,kinds:Object.freeze([...t.kinds])}));return Object.freeze({templates:Object.freeze(e)})},d=(r,e)=>c([...r.templates,...e]),A=(r,e,t)=>r.kinds.includes(e.kind)&&(r.canRender?.(e,t)??!0),f=(r,e,t)=>{const n=e.presentation?.template;if(n){const a=r.templates.find(s=>s.id===n&&A(s,e,t));if(a)return{template:a,reason:"requested"}}const o=r.templates.map((a,s)=>({template:a,registrationIndex:s})).filter(({template:a})=>A(a,e,t)).sort((a,s)=>(s.template.priority??0)-(a.template.priority??0)||a.registrationIndex-s.registrationIndex);return o[0]?{template:o[0].template,reason:"priority"}:void 0},l=r=>({artifactSchemaVersions:[i.MAKE_AI_ARTIFACT_SCHEMA_VERSION],artifactKinds:Array.from(new Set(r.templates.flatMap(e=>e.kinds))).sort(),templates:r.templates.map(e=>e.id).sort()});exports.MAKE_AI_ARTIFACT_KINDS=i.MAKE_AI_ARTIFACT_KINDS;exports.MAKE_AI_ARTIFACT_LIMITS=i.MAKE_AI_ARTIFACT_LIMITS;exports.MAKE_AI_ARTIFACT_SCHEMA_VERSION=i.MAKE_AI_ARTIFACT_SCHEMA_VERSION;exports.MAKE_AI_CONVERSATION_LIMITS=i.MAKE_AI_CONVERSATION_LIMITS;exports.appendUserMessage=i.appendUserMessage;exports.createAssistantConversationState=i.createAssistantConversationState;exports.parseArtifact=i.parseArtifact;exports.parseAssistantEvent=i.parseAssistantEvent;exports.reduceAssistantEvent=i.reduceAssistantEvent;exports.validateArtifact=i.validateArtifact;exports.createArtifactCapabilities=l;exports.createArtifactTemplateRegistry=c;exports.extendArtifactTemplateRegistry=d;exports.resolveArtifactTemplate=f;
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { f as p, d } from "./conversation-B5kECJz8.js";
2
- import { e as E, M as T, b, c as _, g as R, p as y, r as M, v as S } from "./conversation-B5kECJz8.js";
1
+ import { f as p, d } from "./conversation-Dy2Sghjv.js";
2
+ import { e as E, M as T, b, a as _, g as R, p as y, r as M, v as S } from "./conversation-Dy2Sghjv.js";
3
3
  const c = (r) => {
4
4
  const e = /* @__PURE__ */ new Set();
5
5
  for (const t of r) {
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("./sse.cjs"),I=require("./conversation-Yku9Lzj_.cjs"),m=100,M={AI_AGENT_UNAVAILABLE:"当前 App 尚未配置可用的 AI 助手。",AI_APP_UNAVAILABLE:"当前 App 暂不可用。",AI_AUTH_EXPIRED:"登录已失效,请重新登录。",AI_AUTH_REQUIRED:"登录已失效,请重新登录。",AI_FORBIDDEN:"当前账号无权使用该 AI 助手。",AI_RUN_FAILED:"本次 AI 处理失败,请重试。",AI_UPSTREAM_ERROR:"AI 服务暂时不可用,请稍后重试。"},u=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),h=(e,a,i=I.MAKE_AI_CONVERSATION_LIMITS.identifierCharacters)=>{if(typeof e!="string"||!e.trim()||I.countCodePointsUpTo(e,i)>i)throw new Error(`Invalid Make App assistant response: ${a}`);return e},_=e=>{if(!u(e))throw new Error("Invalid Make App assistant response: locate");return{chatId:h(e.chatId,"chatId")}},v=e=>{if(!u(e))throw new Error("Invalid Make App assistant response: send");const a=e.acceptedCursor;if(!Number.isSafeInteger(a)||Number(a)<0)throw new Error("Invalid Make App assistant response: acceptedCursor");return{acceptedCursor:a,chatId:h(e.chatId,"chatId"),responseId:h(e.responseId,"responseId")}},S=(e,a,i)=>{if(!u(e)||!Array.isArray(e.messages)||e.messages.length>i)throw new Error("Invalid Make App assistant response: history");const c=new Set;let o=0;const t=e.messages.map(s=>{if(!u(s))throw new Error("Invalid Make App assistant response: history message");if(s.role!=="user"&&s.role!=="assistant")throw new Error("Invalid Make App assistant response: history role");const r=s.role;if(!Number.isSafeInteger(s.cursor)||Number(s.cursor)<0)throw new Error("Invalid Make App assistant response: history cursor");const p=`history-${a}-${String(s.cursor)}`;if(c.has(p))throw new Error("Invalid Make App assistant response: duplicate history cursor");c.add(p);const d=h(s.text,"history text",I.MAKE_AI_CONVERSATION_LIMITS.messageCharacters);if(o+=I.countCodePointsUpTo(d,I.MAKE_AI_CONVERSATION_LIMITS.historyCharacters-o),o>I.MAKE_AI_CONVERSATION_LIMITS.historyCharacters)throw new Error("Invalid Make App assistant response: history text budget");return{id:p,role:r,content:d,artifacts:[]}});return{threadId:a,messages:t}},k=()=>{const e=[],a=[];return{next:()=>{const o=e.shift();return o?Promise.resolve(o):new Promise(t=>a.push(t))},push:o=>{const t=a.shift();t?t(o):e.push(o)}}},T=(e,a)=>{if(I.countCodePointsUpTo(e.data,a)>a)throw new Error("Make App assistant SSE event exceeds maxEventCharacters");try{const i=JSON.parse(e.data);if(!u(i))throw new Error("invalid data");return i}catch{throw new Error("Invalid Make App assistant SSE JSON")}},E=()=>new DOMException("Aborted","AbortError"),A=e=>{if(e?.aborted)throw E()},C=async function*(e,a){const i=`assistant:${e.responseId}`;A(a?.signal),yield{type:"message.start",runId:e.responseId,messageId:i};const c=k(),o=e.eventSourceFactory({chatId:e.chatId,responseId:e.responseId,cursor:"0-0"},{withCredentials:!0});let t=!1;const s=n=>{t||(t=!0,c.push(n))},r=new Map,p=(n,l)=>{const y=g=>{if(!t)try{l(T(g,e.maxEventCharacters))}catch(f){s({type:"error",error:f})}};r.set(n,y),o.addEventListener(n,y)};p("run.started",()=>{c.push({type:"event",event:{type:"run.progress",runId:e.responseId,message:"正在分析"}})}),p("response.progress",n=>{c.push({type:"event",event:{type:"run.progress",runId:e.responseId,message:h(n.message,"progress message",I.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)}})}),p("response.delta",n=>{if(typeof n.text!="string")throw new Error("Invalid Make App assistant response: delta text");c.push({type:"event",event:{type:"message.delta",messageId:i,delta:n.text}})}),p("response.message",n=>{c.push({type:"event",event:{type:"message.replace",messageId:i,content:h(n.text,"message text",I.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)}})}),p("response.completed",()=>{c.push({type:"event",event:{type:"message.complete",messageId:i}}),c.push({type:"event",event:{type:"run.complete",runId:e.responseId,threadId:e.chatId}}),s({type:"done"})}),p("response.failed",n=>{const l=h(n.code,"failure code");s({type:"event",event:{type:"error",code:l,message:M[l]??"本次 AI 处理失败,请重试。",retryable:!["AI_AUTH_REQUIRED","AI_AUTH_EXPIRED","AI_FORBIDDEN","AI_APP_UNAVAILABLE","AI_AGENT_UNAVAILABLE"].includes(l),requestId:e.responseId}})}),o.onerror=()=>{t||o.readyState!==void 0&&o.readyState!==2||s({type:"error",error:new Error("Make App assistant SSE disconnected")})};const d=()=>s({type:"error",error:E()});a?.signal?.addEventListener("abort",d,{once:!0}),a?.signal?.aborted&&d();try{for(;;){const n=await c.next();if(n.type==="done")return;if(n.type==="error")throw n.error;if(yield n.event,n.event.type==="error")return}}finally{t=!0,a?.signal?.removeEventListener("abort",d),o.onerror=null;for(const[n,l]of r)o.removeEventListener(n,l);o.close()}},N=e=>{const a=e.eventSourceFactory,i=e.historyLimit??m,c=e.maxEventCharacters??w.DEFAULT_MAX_SSE_EVENT_CHARACTERS;if(!Number.isInteger(i)||i<1||i>100)throw new Error("historyLimit must be an integer between 1 and 100");if(!Number.isInteger(c)||c<=0)throw new Error("maxEventCharacters must be a positive integer");const o=async(t,s)=>{A(s?.signal),console.info("[make-ai-assistant] Make App chat locate start",{appId:t.app.id});const{chatId:r}=_(await e.locateChat(t,{signal:s?.signal}));return A(s?.signal),console.info("[make-ai-assistant] Make App chat locate success",{appId:t.app.id}),r};return{features:{history:!0,newConversation:!1,remoteCancellation:!1},async loadConversation(t,s){console.info("[make-ai-assistant] Make App history load start",{appId:t.app.id});try{A(s?.signal);const r=await o(t,s),p=await e.loadHistory({chatId:r,cursor:-1,limit:i},{signal:s?.signal});A(s?.signal);const d=S(p,r,i);return console.info("[make-ai-assistant] Make App history load success",{appId:t.app.id,messageCount:d.messages.length}),d}catch(r){throw(s?.signal?.aborted?console.info:console.error)(s?.signal?.aborted?"[make-ai-assistant] Make App history load cancelled":"[make-ai-assistant] Make App history load failed",{appId:t.app.id,errorType:r instanceof Error?r.name:typeof r}),r}},async*run(t,s){console.info("[make-ai-assistant] Make App run start",{appId:t.context.app.id});try{A(s?.signal);const r=await o(t.context,s),p=v(await e.sendMessage({chatId:r,messageId:t.message.id,text:t.message.content},{signal:s?.signal}));if(A(s?.signal),p.chatId!==r)throw new Error("Invalid Make App assistant response: chatId mismatch");for await(const d of C({chatId:r,responseId:p.responseId,eventSourceFactory:a,maxEventCharacters:c},s))yield d;console.info("[make-ai-assistant] Make App run complete",{appId:t.context.app.id})}catch(r){throw s?.signal?.aborted?console.info("[make-ai-assistant] Make App run cancelled",{appId:t.context.app.id}):console.error("[make-ai-assistant] Make App run failed",{appId:t.context.app.id,errorType:r instanceof Error?r.name:typeof r}),r}}}};exports.createMakeAppAssistantTransport=N;
@@ -0,0 +1,36 @@
1
+ import type { AssistantTransport, AssistantTransportOptions, MakeAssistantHostContext } from "./core/index.js";
2
+ export interface MakeAppAssistantEventSourceEvent {
3
+ data: string;
4
+ lastEventId: string;
5
+ }
6
+ export interface MakeAppAssistantEventSource {
7
+ readonly readyState?: number;
8
+ onerror: ((event: unknown) => void) | null;
9
+ addEventListener(type: string, listener: (event: MakeAppAssistantEventSourceEvent) => void): void;
10
+ removeEventListener(type: string, listener: (event: MakeAppAssistantEventSourceEvent) => void): void;
11
+ close(): void;
12
+ }
13
+ export type MakeAppAssistantEventSourceFactory = (subscription: {
14
+ chatId: string;
15
+ cursor: string;
16
+ responseId: string;
17
+ }, init: {
18
+ withCredentials: true;
19
+ }) => MakeAppAssistantEventSource;
20
+ export interface MakeAppAssistantTransportOptions {
21
+ eventSourceFactory: MakeAppAssistantEventSourceFactory;
22
+ historyLimit?: number;
23
+ maxEventCharacters?: number;
24
+ loadHistory(request: {
25
+ chatId: string;
26
+ cursor: -1;
27
+ limit: number;
28
+ }, options: AssistantTransportOptions): Promise<unknown>;
29
+ locateChat(context: MakeAssistantHostContext, options: AssistantTransportOptions): Promise<unknown>;
30
+ sendMessage(request: {
31
+ chatId: string;
32
+ messageId: string;
33
+ text: string;
34
+ }, options: AssistantTransportOptions): Promise<unknown>;
35
+ }
36
+ export declare const createMakeAppAssistantTransport: (options: MakeAppAssistantTransportOptions) => AssistantTransport;
@@ -0,0 +1,287 @@
1
+ import { DEFAULT_MAX_SSE_EVENT_CHARACTERS as m } from "./sse.mjs";
2
+ import { M as A, c as u } from "./conversation-Dy2Sghjv.js";
3
+ const v = 100, k = {
4
+ AI_AGENT_UNAVAILABLE: "当前 App 尚未配置可用的 AI 助手。",
5
+ AI_APP_UNAVAILABLE: "当前 App 暂不可用。",
6
+ AI_AUTH_EXPIRED: "登录已失效,请重新登录。",
7
+ AI_AUTH_REQUIRED: "登录已失效,请重新登录。",
8
+ AI_FORBIDDEN: "当前账号无权使用该 AI 助手。",
9
+ AI_RUN_FAILED: "本次 AI 处理失败,请重试。",
10
+ AI_UPSTREAM_ERROR: "AI 服务暂时不可用,请稍后重试。"
11
+ }, y = (e) => typeof e == "object" && e !== null && !Array.isArray(e), h = (e, a, i = A.identifierCharacters) => {
12
+ if (typeof e != "string" || !e.trim() || u(e, i) > i)
13
+ throw new Error(`Invalid Make App assistant response: ${a}`);
14
+ return e;
15
+ }, M = (e) => {
16
+ if (!y(e))
17
+ throw new Error("Invalid Make App assistant response: locate");
18
+ return { chatId: h(e.chatId, "chatId") };
19
+ }, _ = (e) => {
20
+ if (!y(e))
21
+ throw new Error("Invalid Make App assistant response: send");
22
+ const a = e.acceptedCursor;
23
+ if (!Number.isSafeInteger(a) || Number(a) < 0)
24
+ throw new Error("Invalid Make App assistant response: acceptedCursor");
25
+ return {
26
+ acceptedCursor: a,
27
+ chatId: h(e.chatId, "chatId"),
28
+ responseId: h(e.responseId, "responseId")
29
+ };
30
+ }, S = (e, a, i) => {
31
+ if (!y(e) || !Array.isArray(e.messages) || e.messages.length > i)
32
+ throw new Error("Invalid Make App assistant response: history");
33
+ const c = /* @__PURE__ */ new Set();
34
+ let o = 0;
35
+ const t = e.messages.map((s) => {
36
+ if (!y(s))
37
+ throw new Error("Invalid Make App assistant response: history message");
38
+ if (s.role !== "user" && s.role !== "assistant")
39
+ throw new Error("Invalid Make App assistant response: history role");
40
+ const r = s.role;
41
+ if (!Number.isSafeInteger(s.cursor) || Number(s.cursor) < 0)
42
+ throw new Error("Invalid Make App assistant response: history cursor");
43
+ const p = `history-${a}-${String(s.cursor)}`;
44
+ if (c.has(p))
45
+ throw new Error("Invalid Make App assistant response: duplicate history cursor");
46
+ c.add(p);
47
+ const d = h(
48
+ s.text,
49
+ "history text",
50
+ A.messageCharacters
51
+ );
52
+ if (o += u(
53
+ d,
54
+ A.historyCharacters - o
55
+ ), o > A.historyCharacters)
56
+ throw new Error("Invalid Make App assistant response: history text budget");
57
+ return {
58
+ id: p,
59
+ role: r,
60
+ content: d,
61
+ artifacts: []
62
+ };
63
+ });
64
+ return { threadId: a, messages: t };
65
+ }, R = () => {
66
+ const e = [], a = [];
67
+ return { next: () => {
68
+ const o = e.shift();
69
+ return o ? Promise.resolve(o) : new Promise((t) => a.push(t));
70
+ }, push: (o) => {
71
+ const t = a.shift();
72
+ t ? t(o) : e.push(o);
73
+ } };
74
+ }, b = (e, a) => {
75
+ if (u(e.data, a) > a)
76
+ throw new Error("Make App assistant SSE event exceeds maxEventCharacters");
77
+ try {
78
+ const i = JSON.parse(e.data);
79
+ if (!y(i)) throw new Error("invalid data");
80
+ return i;
81
+ } catch {
82
+ throw new Error("Invalid Make App assistant SSE JSON");
83
+ }
84
+ }, E = () => new DOMException("Aborted", "AbortError"), I = (e) => {
85
+ if (e?.aborted) throw E();
86
+ }, C = async function* (e, a) {
87
+ const i = `assistant:${e.responseId}`;
88
+ I(a?.signal), yield {
89
+ type: "message.start",
90
+ runId: e.responseId,
91
+ messageId: i
92
+ };
93
+ const c = R(), o = e.eventSourceFactory({
94
+ chatId: e.chatId,
95
+ responseId: e.responseId,
96
+ cursor: "0-0"
97
+ }, { withCredentials: !0 });
98
+ let t = !1;
99
+ const s = (n) => {
100
+ t || (t = !0, c.push(n));
101
+ }, r = /* @__PURE__ */ new Map(), p = (n, l) => {
102
+ const f = (g) => {
103
+ if (!t)
104
+ try {
105
+ l(b(g, e.maxEventCharacters));
106
+ } catch (w) {
107
+ s({ type: "error", error: w });
108
+ }
109
+ };
110
+ r.set(n, f), o.addEventListener(n, f);
111
+ };
112
+ p("run.started", () => {
113
+ c.push({
114
+ type: "event",
115
+ event: {
116
+ type: "run.progress",
117
+ runId: e.responseId,
118
+ message: "正在分析"
119
+ }
120
+ });
121
+ }), p("response.progress", (n) => {
122
+ c.push({
123
+ type: "event",
124
+ event: {
125
+ type: "run.progress",
126
+ runId: e.responseId,
127
+ message: h(
128
+ n.message,
129
+ "progress message",
130
+ A.messageCharacters
131
+ )
132
+ }
133
+ });
134
+ }), p("response.delta", (n) => {
135
+ if (typeof n.text != "string")
136
+ throw new Error("Invalid Make App assistant response: delta text");
137
+ c.push({
138
+ type: "event",
139
+ event: { type: "message.delta", messageId: i, delta: n.text }
140
+ });
141
+ }), p("response.message", (n) => {
142
+ c.push({
143
+ type: "event",
144
+ event: {
145
+ type: "message.replace",
146
+ messageId: i,
147
+ content: h(
148
+ n.text,
149
+ "message text",
150
+ A.messageCharacters
151
+ )
152
+ }
153
+ });
154
+ }), p("response.completed", () => {
155
+ c.push({
156
+ type: "event",
157
+ event: { type: "message.complete", messageId: i }
158
+ }), c.push({
159
+ type: "event",
160
+ event: {
161
+ type: "run.complete",
162
+ runId: e.responseId,
163
+ threadId: e.chatId
164
+ }
165
+ }), s({ type: "done" });
166
+ }), p("response.failed", (n) => {
167
+ const l = h(n.code, "failure code");
168
+ s({
169
+ type: "event",
170
+ event: {
171
+ type: "error",
172
+ code: l,
173
+ message: k[l] ?? "本次 AI 处理失败,请重试。",
174
+ retryable: ![
175
+ "AI_AUTH_REQUIRED",
176
+ "AI_AUTH_EXPIRED",
177
+ "AI_FORBIDDEN",
178
+ "AI_APP_UNAVAILABLE",
179
+ "AI_AGENT_UNAVAILABLE"
180
+ ].includes(l),
181
+ requestId: e.responseId
182
+ }
183
+ });
184
+ }), o.onerror = () => {
185
+ t || o.readyState !== void 0 && o.readyState !== 2 || s({ type: "error", error: new Error("Make App assistant SSE disconnected") });
186
+ };
187
+ const d = () => s({ type: "error", error: E() });
188
+ a?.signal?.addEventListener("abort", d, { once: !0 }), a?.signal?.aborted && d();
189
+ try {
190
+ for (; ; ) {
191
+ const n = await c.next();
192
+ if (n.type === "done") return;
193
+ if (n.type === "error") throw n.error;
194
+ if (yield n.event, n.event.type === "error") return;
195
+ }
196
+ } finally {
197
+ t = !0, a?.signal?.removeEventListener("abort", d), o.onerror = null;
198
+ for (const [n, l] of r)
199
+ o.removeEventListener(n, l);
200
+ o.close();
201
+ }
202
+ }, T = (e) => {
203
+ const a = e.eventSourceFactory, i = e.historyLimit ?? v, c = e.maxEventCharacters ?? m;
204
+ if (!Number.isInteger(i) || i < 1 || i > 100)
205
+ throw new Error("historyLimit must be an integer between 1 and 100");
206
+ if (!Number.isInteger(c) || c <= 0)
207
+ throw new Error("maxEventCharacters must be a positive integer");
208
+ const o = async (t, s) => {
209
+ I(s?.signal), console.info("[make-ai-assistant] Make App chat locate start", {
210
+ appId: t.app.id
211
+ });
212
+ const { chatId: r } = M(await e.locateChat(t, {
213
+ signal: s?.signal
214
+ }));
215
+ return I(s?.signal), console.info("[make-ai-assistant] Make App chat locate success", {
216
+ appId: t.app.id
217
+ }), r;
218
+ };
219
+ return {
220
+ features: {
221
+ history: !0,
222
+ newConversation: !1,
223
+ remoteCancellation: !1
224
+ },
225
+ async loadConversation(t, s) {
226
+ console.info("[make-ai-assistant] Make App history load start", {
227
+ appId: t.app.id
228
+ });
229
+ try {
230
+ I(s?.signal);
231
+ const r = await o(t, s), p = await e.loadHistory(
232
+ { chatId: r, cursor: -1, limit: i },
233
+ { signal: s?.signal }
234
+ );
235
+ I(s?.signal);
236
+ const d = S(p, r, i);
237
+ return console.info("[make-ai-assistant] Make App history load success", {
238
+ appId: t.app.id,
239
+ messageCount: d.messages.length
240
+ }), d;
241
+ } catch (r) {
242
+ throw (s?.signal?.aborted ? console.info : console.error)(
243
+ s?.signal?.aborted ? "[make-ai-assistant] Make App history load cancelled" : "[make-ai-assistant] Make App history load failed",
244
+ {
245
+ appId: t.app.id,
246
+ errorType: r instanceof Error ? r.name : typeof r
247
+ }
248
+ ), r;
249
+ }
250
+ },
251
+ async *run(t, s) {
252
+ console.info("[make-ai-assistant] Make App run start", {
253
+ appId: t.context.app.id
254
+ });
255
+ try {
256
+ I(s?.signal);
257
+ const r = await o(t.context, s), p = _(await e.sendMessage({
258
+ chatId: r,
259
+ messageId: t.message.id,
260
+ text: t.message.content
261
+ }, { signal: s?.signal }));
262
+ if (I(s?.signal), p.chatId !== r)
263
+ throw new Error("Invalid Make App assistant response: chatId mismatch");
264
+ for await (const d of C({
265
+ chatId: r,
266
+ responseId: p.responseId,
267
+ eventSourceFactory: a,
268
+ maxEventCharacters: c
269
+ }, s))
270
+ yield d;
271
+ console.info("[make-ai-assistant] Make App run complete", {
272
+ appId: t.context.app.id
273
+ });
274
+ } catch (r) {
275
+ throw s?.signal?.aborted ? console.info("[make-ai-assistant] Make App run cancelled", {
276
+ appId: t.context.app.id
277
+ }) : console.error("[make-ai-assistant] Make App run failed", {
278
+ appId: t.context.app.id,
279
+ errorType: r instanceof Error ? r.name : typeof r
280
+ }), r;
281
+ }
282
+ }
283
+ };
284
+ };
285
+ export {
286
+ T as createMakeAppAssistantTransport
287
+ };
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const N=require("./sse.cjs"),E=require("./conversation-Yku9Lzj_.cjs"),M=4e3,x=200,U=30,P=1e3,K={AI_AGENT_UNAVAILABLE:"当前应用没有可用 Agent。",AI_AUTH_EXPIRED:"登录已失效,请重新登录。",AI_AUTH_REQUIRED:"登录已失效,请重新登录。",AI_FORBIDDEN:"当前账号无权使用该 AI 助手。",AI_RUN_FAILED:"本次 AI 处理失败,请重试。",AI_UPSTREAM_ERROR:"AI 服务暂时不可用,请稍后重试。"},O=new Set(["AI_AGENT_UNAVAILABLE","AI_AUTH_EXPIRED","AI_AUTH_REQUIRED","AI_FORBIDDEN"]),y=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),A=(e,t,n=E.MAKE_AI_CONVERSATION_LIMITS.identifierCharacters)=>{if(typeof e!="string"||!e.trim()||E.countCodePointsUpTo(e,n)>n)throw new Error(`Invalid Make Console assistant response: ${t}`);return e},S=(e,t)=>{if(!(e==null||e===""))return A(e,t)},m=(e,t)=>{if(!Number.isSafeInteger(e)||Number(e)<0)throw new Error(`Invalid Make Console assistant response: ${t}`);return Number(e)},k=()=>new DOMException("Aborted","AbortError"),u=e=>{if(e?.aborted)throw k()},q=(e,t)=>(u(t),e===0?Promise.resolve():new Promise((n,i)=>{const f=setTimeout(()=>{t?.removeEventListener("abort",I),n()},e),I=()=>{clearTimeout(f),t?.removeEventListener("abort",I),i(k())};t?.addEventListener("abort",I,{once:!0})})),F=e=>{if(!y(e)||!Array.isArray(e.agents)||e.agents.length>1e3)throw new Error("Invalid Make Console assistant response: agents");const t=new Set;return e.agents.map(n=>{if(!y(n))throw new Error("Invalid Make Console assistant response: agent");const i=A(n.agentID,"agentID");if(t.has(i))throw new Error("Invalid Make Console assistant response: duplicate agentID");return t.add(i),{agentID:i,...typeof n.name=="string"&&n.name.trim()?{name:A(n.name,"agent name")}:{},status:A(n.status,"agent status")}})},V=e=>{if(!y(e))throw new Error("Invalid Make Console assistant response: session");return{nextSeq:m(e.nextSeq,"nextSeq"),sessionID:A(e.sessionID,"sessionID")}},H=e=>{if(!y(e))throw new Error("Invalid Make Console assistant response: sent message");const t=S(e.runID,"runID"),n=S(e.mergedInto,"mergedInto");if(t&&n)throw new Error("Invalid Make Console assistant response: multiple Run IDs");return{effectiveRunID:t??n,seq:m(e.seq,"seq"),sessionID:A(e.sessionID,"sessionID")}},$=e=>{if(!y(e)||!Array.isArray(e.blocks)||e.blocks.length>1e3)throw new Error("Invalid Make Console assistant response: payload blocks");let t="";for(const n of e.blocks)if(!(!y(n)||n.kind!=="text"||typeof n.text!="string")&&(t+=n.text,E.countCodePointsUpTo(t,E.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)>E.MAKE_AI_CONVERSATION_LIMITS.messageCharacters))throw new Error("Invalid Make Console assistant response: message text budget");return A(t,"message text",E.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)},T=(e,t)=>{if(!Array.isArray(e)||e.length>t)throw new Error("Invalid Make Console assistant response: durable events");const n=new Set;return e.flatMap(i=>{if(!y(i))throw new Error("Invalid Make Console assistant response: durable event");const c=m(i.seq,"event seq");if(n.has(c))throw new Error("Invalid Make Console assistant response: duplicate event seq");n.add(c);const f=typeof i.type=="string"?i.type:"",I=y(i.actor)&&typeof i.actor.kind=="string"?i.actor.kind:"";return!(f==="user_message")&&!(f==="message"&&I==="agent")?[]:[{actorKind:I,content:$(i.payload),runID:S(i.runID,"event runID"),seq:c,type:f}]})},G=(e,t,n)=>{const i=T(e,n);let c=0;return{messages:i.map(I=>{if(c+=E.countCodePointsUpTo(I.content,E.MAKE_AI_CONVERSATION_LIMITS.historyCharacters-c),c>E.MAKE_AI_CONVERSATION_LIMITS.historyCharacters)throw new Error("Invalid Make Console assistant response: history text budget");return{artifacts:[],content:I.content,id:`console-${t}-${String(I.seq)}`,role:I.type==="user_message"?"user":"assistant"}}),threadId:t}},B=()=>{const e=[],t=[];return{next:()=>{const c=e.shift();return c?Promise.resolve(c):new Promise(f=>t.push(f))},push:c=>{const f=t.shift();f?f(c):e.push(c)}}},X=(e,t)=>{if(E.countCodePointsUpTo(e.data,t)>t)throw new Error("Make Console assistant SSE event exceeds maxEventCharacters");try{const n=JSON.parse(e.data);if(!y(n))throw new Error("invalid data");return n}catch{throw new Error("Invalid Make Console assistant SSE JSON")}},b=(e,t)=>{if(!Number.isInteger(e)||e<1)throw new Error(`${t} must be a positive integer`)},Q=(e,t,n)=>T(e,t).find(c=>c.type==="message"&&c.actorKind==="agent"&&(n===void 0||c.runID===n)),j=e=>{const t=e.historyLimit??x,n=e.maxEventCharacters??N.DEFAULT_MAX_SSE_EVENT_CHARACTERS,i=e.maxPollingAttempts??U,c=e.pollIntervalMs??P,f=e.wait??q;if(!Number.isInteger(t)||t<1||t>200)throw new Error("historyLimit must be an integer between 1 and 200");if(b(n,"maxEventCharacters"),b(i,"maxPollingAttempts"),!Number.isInteger(c)||c<0)throw new Error("pollIntervalMs must be a non-negative integer");const I=async(s,r)=>{u(r?.signal),console.info("[make-ai-assistant] Make Console Agent lookup start",{appId:s.app.id});const o=F(await e.listAgents({appKey:s.app.id},{signal:r?.signal}));u(r?.signal);const l=o.filter(g=>g.status==="enabled"),p=e.selectAgent?e.selectAgent(l,s):l[0]?.agentID,d=l.find(g=>g.agentID===p);if(!d)throw new Error("当前应用没有可用 Agent");return console.info("[make-ai-assistant] Make Console Agent lookup success",{appId:s.app.id,enabledAgentCount:l.length}),d},C=async(s,r,o)=>(u(o?.signal),V(await e.getOrCreateSession({agentID:r,appKey:s.app.id},{signal:o?.signal}))),_=async s=>{for(let r=1;r<=i;r+=1){u(s.signal);const o=await e.loadEvents({agentID:s.agentID,appKey:s.appKey,from:s.from,limit:t,sessionID:s.sessionID},{signal:s.signal});u(s.signal);const l=Q(o,t,s.effectiveRunID);if(l)return l;r<i&&await f(c,s.signal)}throw new Error("Make Console assistant durable response unavailable")},L=async function*(s){u(s.signal);const r=B(),o=e.eventSourceFactory({agentID:s.agentID,appKey:s.appKey,cursor:"0-0",runID:s.effectiveRunID,sessionID:s.sessionID},{withCredentials:!0});let l=!1;const p=a=>{l||(l=!0,r.push(a))},d=new Map,g=(a,h)=>{const D=v=>{if(!l)try{h(X(v,n),v)}catch(R){p({type:"error",error:R})}};d.set(a,D),o.addEventListener(a,D)};g("ready",a=>{if(typeof a.after!="string")throw new Error("Invalid Make Console assistant response: ready cursor")}),g("run-output",a=>{if(A(a.runID,"SSE runID")!==s.effectiveRunID)throw new Error("Invalid Make Console assistant response: SSE runID mismatch");m(a.sequence,"SSE sequence");const h=A(a.type,"SSE output type");if(h==="output_text.delta"){if(typeof a.delta!="string")throw new Error("Invalid Make Console assistant response: SSE delta");r.push({type:"event",event:{type:"message.delta",messageId:s.messageId,delta:a.delta}})}else h==="response.completed"?p({type:"completed"}):h==="response.failed"&&p({type:"failed",code:A(a.failureCode,"failureCode")})}),g("fallback",a=>{if(a.reason!=="stream_unavailable")throw new Error("Invalid Make Console assistant response: fallback reason");p({type:"fallback"})}),o.onerror=()=>{l||o.readyState!==void 0&&o.readyState!==2||p({type:"error",error:new Error("Make Console assistant SSE disconnected")})};const w=()=>p({type:"error",error:k()});s.signal?.addEventListener("abort",w,{once:!0}),s.signal?.aborted&&w();try{for(;;){const a=await r.next();if(a.type==="event")yield a.event;else{if(a.type==="completed"||a.type==="fallback")return a.type;if(a.type==="failed")return yield{type:"error",code:a.code,message:K[a.code]??"本次 AI 处理失败,请重试。",retryable:!O.has(a.code),requestId:s.effectiveRunID},"failed";throw a.error}}}finally{l=!0,s.signal?.removeEventListener("abort",w),o.onerror=null;for(const[a,h]of d)o.removeEventListener(a,h);o.close()}};return{features:{history:!0,newConversation:!1,remoteCancellation:!1},async loadConversation(s,r){console.info("[make-ai-assistant] Make Console history load start",{appId:s.app.id});try{const o=await I(s,r),l=await C(s,o.agentID,r),p=Math.max(0,l.nextSeq-t),d=await e.loadEvents({agentID:o.agentID,appKey:s.app.id,from:p,limit:t,sessionID:l.sessionID},{signal:r?.signal});u(r?.signal);const g=G(d,l.sessionID,t);return console.info("[make-ai-assistant] Make Console history load success",{appId:s.app.id,messageCount:g.messages.length}),g}catch(o){throw(r?.signal?.aborted?console.info:console.error)(r?.signal?.aborted?"[make-ai-assistant] Make Console history load cancelled":"[make-ai-assistant] Make Console history load failed",{appId:s.app.id,errorType:o instanceof Error?o.name:typeof o}),o}},async*run(s,r){console.info("[make-ai-assistant] Make Console run start",{appId:s.context.app.id});try{const o=s.message.content.trim();if(!o||E.countCodePointsUpTo(o,M)>M)throw new Error(o?"Console 消息不能超过 4000 个字符":"Console 消息不能为空");const l=await I(s.context,r),p=await C(s.context,l.agentID,r);u(r?.signal);const d=H(await e.sendMessage({agentID:l.agentID,appKey:s.context.app.id,text:o},{signal:r?.signal}));if(u(r?.signal),d.sessionID!==p.sessionID)throw new Error("Invalid Make Console assistant response: sessionID mismatch");const g=d.effectiveRunID??`${d.sessionID}:${String(d.seq)}`,w=`assistant:${g}`;if(yield{type:"message.start",runId:g,messageId:w},d.effectiveRunID){const D=yield*L({agentID:l.agentID,appKey:s.context.app.id,effectiveRunID:d.effectiveRunID,messageId:w,sessionID:d.sessionID,signal:r?.signal});if(D==="failed")return;D==="fallback"&&console.info("[make-ai-assistant] Make Console SSE fallback",{appId:s.context.app.id})}const a=await _({agentID:l.agentID,appKey:s.context.app.id,effectiveRunID:d.effectiveRunID,from:d.seq+1,sessionID:d.sessionID,signal:r?.signal});yield{type:"message.replace",messageId:w,content:a.content},yield{type:"message.complete",messageId:w},yield{type:"run.complete",runId:g,threadId:d.sessionID},console.info("[make-ai-assistant] Make Console run complete",{appId:s.context.app.id})}catch(o){throw r?.signal?.aborted?console.info("[make-ai-assistant] Make Console run cancelled",{appId:s.context.app.id}):console.error("[make-ai-assistant] Make Console run failed",{appId:s.context.app.id,errorType:o instanceof Error?o.name:typeof o}),o}}}};exports.MAKE_CONSOLE_MESSAGE_CHARACTERS=M;exports.createMakeConsoleAssistantTransport=j;
@@ -0,0 +1,58 @@
1
+ import type { AssistantTransport, AssistantTransportOptions, MakeAssistantHostContext } from "./core/index.js";
2
+ export declare const MAKE_CONSOLE_MESSAGE_CHARACTERS = 4000;
3
+ export interface MakeConsoleAgentSummary {
4
+ agentID: string;
5
+ name?: string;
6
+ status: string;
7
+ }
8
+ export interface MakeConsoleAssistantEventSourceEvent {
9
+ data: string;
10
+ lastEventId: string;
11
+ }
12
+ export interface MakeConsoleAssistantEventSource {
13
+ readonly readyState?: number;
14
+ onerror: ((event: unknown) => void) | null;
15
+ addEventListener(type: string, listener: (event: MakeConsoleAssistantEventSourceEvent) => void): void;
16
+ removeEventListener(type: string, listener: (event: MakeConsoleAssistantEventSourceEvent) => void): void;
17
+ close(): void;
18
+ }
19
+ export type MakeConsoleAssistantEventSourceFactory = (subscription: {
20
+ agentID: string;
21
+ appKey: string;
22
+ cursor: string;
23
+ runID: string;
24
+ sessionID: string;
25
+ }, init: {
26
+ withCredentials: true;
27
+ }) => MakeConsoleAssistantEventSource;
28
+ type MakeConsoleRequestOptions = AssistantTransportOptions;
29
+ export interface MakeConsoleAssistantTransportOptions {
30
+ eventSourceFactory: MakeConsoleAssistantEventSourceFactory;
31
+ getOrCreateSession(request: {
32
+ agentID: string;
33
+ appKey: string;
34
+ }, options: MakeConsoleRequestOptions): Promise<unknown>;
35
+ historyLimit?: number;
36
+ listAgents(request: {
37
+ appKey: string;
38
+ }, options: MakeConsoleRequestOptions): Promise<unknown>;
39
+ loadEvents(request: {
40
+ agentID: string;
41
+ appKey: string;
42
+ from: number;
43
+ limit: number;
44
+ sessionID: string;
45
+ }, options: MakeConsoleRequestOptions): Promise<unknown>;
46
+ maxEventCharacters?: number;
47
+ maxPollingAttempts?: number;
48
+ pollIntervalMs?: number;
49
+ selectAgent?(agents: ReadonlyArray<MakeConsoleAgentSummary>, context: MakeAssistantHostContext): string | undefined;
50
+ sendMessage(request: {
51
+ agentID: string;
52
+ appKey: string;
53
+ text: string;
54
+ }, options: MakeConsoleRequestOptions): Promise<unknown>;
55
+ wait?: (milliseconds: number, signal?: AbortSignal) => Promise<void>;
56
+ }
57
+ export declare const createMakeConsoleAssistantTransport: (options: MakeConsoleAssistantTransportOptions) => AssistantTransport;
58
+ export {};