@qfei-design/make-ai-assistant 0.2.12 → 0.2.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/PUBLIC_API.md +20 -20
  2. package/README.md +19 -13
  3. package/capabilities.json +2 -1
  4. package/dist/client-protocol.d.ts +24 -0
  5. package/dist/client-types.d.ts +420 -0
  6. package/dist/client.cjs +2 -0
  7. package/dist/client.d.ts +18 -0
  8. package/dist/client.mjs +1154 -0
  9. package/dist/conversation-BpmWa2VL.cjs +1 -0
  10. package/dist/conversation-DuqMadaQ.js +888 -0
  11. package/dist/conversation-management-DZROhXyK.js +229 -0
  12. package/dist/conversation-management-f1y0yRvt.cjs +1 -0
  13. package/dist/core/conversation-management.d.ts +15 -5
  14. package/dist/core/conversation.d.ts +6 -5
  15. package/dist/index.cjs +1 -1
  16. package/dist/index.mjs +4 -4
  17. package/dist/make-app.cjs +1 -1
  18. package/dist/make-app.d.ts +8 -69
  19. package/dist/make-app.mjs +236 -703
  20. package/dist/make-console.cjs +1 -1
  21. package/dist/make-console.mjs +1 -1
  22. package/dist/react/conversation-controls.d.ts +1 -1
  23. package/dist/react/make-ai-assistant.d.ts +1 -2
  24. package/dist/react/use-attachments.d.ts +3 -1
  25. package/dist/react/use-conversation-manager.d.ts +3 -2
  26. package/dist/react.cjs +62 -4
  27. package/dist/react.mjs +3268 -1794
  28. package/dist/sse.cjs +1 -1
  29. package/dist/sse.mjs +1 -1
  30. package/dist/styles.css +625 -137
  31. package/docs/backend-contract.md +3 -7
  32. package/docs/make-app-integration.md +23 -68
  33. package/examples/make-app/main.tsx +1 -1
  34. package/examples/make-app/transport.ts +36 -146
  35. package/package.ai.json +9 -6
  36. package/package.json +11 -3
  37. package/recipes.json +4 -3
  38. package/dist/conversation-CZfbgCXd.js +0 -1111
  39. package/dist/conversation-Cvh-IVRV.cjs +0 -1
  40. package/dist/make-app/protocol.d.ts +0 -27
  41. package/dist/make-app/stream.d.ts +0 -20
@@ -0,0 +1,229 @@
1
+ const k = (e) => {
2
+ const t = typeof e == "string" ? e : e.status;
3
+ return typeof e != "string" && e.terminal !== void 0 ? e.terminal : t === "completed" || t === "failed" || t === "cancelled";
4
+ }, w = (e) => typeof e == "string" ? a(e, 8192, !0) : u(e), c = (e) => {
5
+ if (!e || typeof e != "object" || Array.isArray(e))
6
+ throw new Error("Invalid assistant data: object");
7
+ return e;
8
+ }, a = (e, t = 256, s = !1) => {
9
+ if (typeof e != "string" || e.length > t * 2 || !s && !e.trim() || e.includes("\0") || [...e].length > t)
10
+ throw new Error("Invalid assistant data: text");
11
+ return e;
12
+ }, n = (e) => {
13
+ const t = a(e);
14
+ if (["__proto__", "constructor", "prototype"].includes(t))
15
+ throw new Error("Invalid assistant data: identifier");
16
+ return t;
17
+ }, u = (e, t = 0, s = Number.MAX_SAFE_INTEGER) => {
18
+ if (!Number.isSafeInteger(e) || Number(e) < t || Number(e) > s)
19
+ throw new Error("Invalid assistant data: integer");
20
+ return e;
21
+ }, I = (e) => {
22
+ if (typeof e != "boolean")
23
+ throw new Error("Invalid assistant data: boolean");
24
+ return e;
25
+ }, g = (e, t) => {
26
+ if (!Array.isArray(e) || e.length > t)
27
+ throw new Error("Invalid assistant data: array");
28
+ return e;
29
+ }, o = (e, t) => {
30
+ if (Object.keys(e).some((s) => !t.includes(s)))
31
+ throw new Error("Invalid assistant data: unknown field");
32
+ }, h = (e) => a(e, 64), y = (e) => g(e, 32).map((t) => {
33
+ const s = c(t), r = s.id === void 0 ? {} : { id: n(s.id) };
34
+ if (s.kind === "unknown")
35
+ return {
36
+ ...r,
37
+ kind: "unknown",
38
+ originalKind: a(s.originalKind, 128),
39
+ ...s.textFallback === void 0 ? {} : { textFallback: a(s.textFallback, 1e5, !0) }
40
+ };
41
+ if (s.kind === "text")
42
+ return o(s, ["id", "kind", "text"]), {
43
+ ...r,
44
+ kind: "text",
45
+ text: a(s.text, 1e5, !0)
46
+ };
47
+ if (!["image", "file", "audio", "video"].includes(String(s.kind)))
48
+ throw new Error("Invalid assistant data: part kind");
49
+ o(s, ["id", "kind", "name", "media"]);
50
+ const i = c(s.media);
51
+ o(i, [
52
+ "contentRef",
53
+ "contentType",
54
+ "sizeBytes",
55
+ "digestSha256"
56
+ ]);
57
+ const p = a(i.digestSha256, 64);
58
+ if (!/^[0-9a-f]{64}$/.test(p))
59
+ throw new Error("Invalid assistant data: digest");
60
+ return {
61
+ ...r,
62
+ kind: s.kind,
63
+ ...s.name === void 0 ? {} : { name: a(s.name, 512, !0) },
64
+ media: {
65
+ contentRef: n(i.contentRef),
66
+ contentType: a(i.contentType, 256),
67
+ sizeBytes: u(i.sizeBytes),
68
+ digestSha256: p
69
+ }
70
+ };
71
+ }), b = (e) => {
72
+ const t = c(e);
73
+ if (o(t, ["id", "rating", "revision", "reason", "comment"]), !["like", "dislike", "none"].includes(String(t.rating)))
74
+ throw new Error("Invalid assistant data: rating");
75
+ return {
76
+ id: n(t.id),
77
+ rating: t.rating,
78
+ revision: u(t.revision, 1),
79
+ ...t.reason === void 0 ? {} : { reason: a(t.reason, 128, !0) },
80
+ ...t.comment === void 0 ? {} : { comment: a(t.comment, 4e3, !0) }
81
+ };
82
+ }, E = (e) => {
83
+ const t = c(e);
84
+ return o(t, [
85
+ "itemId",
86
+ "partId",
87
+ "text",
88
+ "final",
89
+ "revision",
90
+ "parts"
91
+ ]), {
92
+ itemId: n(t.itemId),
93
+ partId: n(t.partId),
94
+ text: a(t.text, 1e5, !0),
95
+ final: I(t.final),
96
+ revision: u(t.revision, 1),
97
+ ...t.parts === void 0 ? {} : { parts: y(t.parts) }
98
+ };
99
+ }, x = (e) => {
100
+ const t = c(e);
101
+ o(t, [
102
+ "chatId",
103
+ "responseId",
104
+ "status",
105
+ "items",
106
+ "cancelRequested",
107
+ "terminal",
108
+ "snapshotRevision"
109
+ ]);
110
+ const s = g(t.items, 20).map(E);
111
+ if (new Set(s.map((r) => r.itemId)).size !== s.length || s.reduce((r, i) => r + [...i.text].length, 0) > 1e5)
112
+ throw new Error("Invalid assistant data: output budget or identity");
113
+ return {
114
+ chatId: n(t.chatId),
115
+ responseId: n(t.responseId),
116
+ status: h(t.status),
117
+ ...t.terminal === void 0 ? {} : { terminal: I(t.terminal) },
118
+ ...t.snapshotRevision === void 0 ? {} : { snapshotRevision: u(t.snapshotRevision, 1) },
119
+ items: s,
120
+ ...t.cancelRequested === void 0 ? {} : { cancelRequested: I(t.cancelRequested) }
121
+ };
122
+ }, R = (e) => {
123
+ const t = c(e);
124
+ if (o(t, [
125
+ "id",
126
+ "role",
127
+ "content",
128
+ "persistent",
129
+ "responseId",
130
+ "cursor",
131
+ "createdAt",
132
+ "parts",
133
+ "feedback"
134
+ ]), t.role !== "assistant" && t.role !== "user" || t.persistent !== !0)
135
+ throw new Error("Invalid assistant data: persisted message");
136
+ return {
137
+ id: n(t.id),
138
+ role: t.role,
139
+ content: a(t.content, 1e5, !0),
140
+ persistent: !0,
141
+ cursor: w(t.cursor),
142
+ createdAt: a(t.createdAt, 64),
143
+ ...t.responseId === void 0 ? {} : { responseId: n(t.responseId) },
144
+ ...t.parts === void 0 ? {} : { parts: y(t.parts) },
145
+ ...t.feedback === void 0 ? {} : { feedback: b(t.feedback) }
146
+ };
147
+ }, S = (e) => {
148
+ const t = c(e), s = t.type;
149
+ if (s === "response.snapshot")
150
+ return o(t, ["type", "snapshot"]), { type: s, snapshot: x(t.snapshot) };
151
+ const r = n(t.responseId);
152
+ if (s === "response.accepted")
153
+ return o(t, [
154
+ "type",
155
+ "chatId",
156
+ "responseId",
157
+ "messageId",
158
+ "acceptedCursor"
159
+ ]), {
160
+ type: s,
161
+ responseId: r,
162
+ chatId: n(t.chatId),
163
+ messageId: n(t.messageId),
164
+ ...t.acceptedCursor === void 0 ? {} : { acceptedCursor: w(t.acceptedCursor) }
165
+ };
166
+ if (s === "response.state")
167
+ return o(t, ["type", "chatId", "responseId", "status"]), {
168
+ type: s,
169
+ responseId: r,
170
+ chatId: n(t.chatId),
171
+ status: h(t.status)
172
+ };
173
+ if (s === "response.terminal") {
174
+ o(t, ["type", "chatId", "responseId", "status", "code"]);
175
+ const d = h(t.status);
176
+ if (!k(d))
177
+ throw new Error("Invalid assistant data: terminal");
178
+ return {
179
+ type: s,
180
+ responseId: r,
181
+ chatId: n(t.chatId),
182
+ status: d,
183
+ ...t.code === void 0 ? {} : { code: n(t.code) }
184
+ };
185
+ }
186
+ if (s === "response.reconciled") {
187
+ o(t, ["type", "chatId", "responseId", "messages"]);
188
+ const d = g(t.messages, 200).map(R);
189
+ if (d.some((l) => l.responseId !== r) || new Set(d.map((l) => l.id)).size !== d.length || d.reduce((l, v) => l + [...v.content].length, 0) > 1e6)
190
+ throw new Error("Invalid assistant data: response history");
191
+ return { type: s, responseId: r, chatId: n(t.chatId), messages: d };
192
+ }
193
+ const i = n(t.itemId), p = n(t.partId), m = u(t.sequence, 1), f = ["type", "responseId", "itemId", "partId", "sequence"];
194
+ if (s === "response.output_item.added")
195
+ return o(t, f), { type: s, responseId: r, itemId: i, partId: p, sequence: m };
196
+ if (s === "response.output_text.delta")
197
+ return o(t, [...f, "delta"]), {
198
+ type: s,
199
+ responseId: r,
200
+ itemId: i,
201
+ partId: p,
202
+ sequence: m,
203
+ delta: a(t.delta, 1e5, !0)
204
+ };
205
+ if (s === "response.output_item.done")
206
+ return o(t, [...f, "text", "final"]), {
207
+ type: s,
208
+ responseId: r,
209
+ itemId: i,
210
+ partId: p,
211
+ sequence: m,
212
+ text: a(t.text, 1e5, !0),
213
+ final: I(t.final)
214
+ };
215
+ throw new Error("Invalid assistant data: event type");
216
+ };
217
+ export {
218
+ u as a,
219
+ c as b,
220
+ a as c,
221
+ I as d,
222
+ g as e,
223
+ w as f,
224
+ b as g,
225
+ y as h,
226
+ k as i,
227
+ S as j,
228
+ n as p
229
+ };
@@ -0,0 +1 @@
1
+ "use strict";const v=e=>{const t=typeof e=="string"?e:e.status;return typeof e!="string"&&e.terminal!==void 0?e.terminal:t==="completed"||t==="failed"||t==="cancelled"},w=e=>typeof e=="string"?n(e,8192,!0):p(e),c=e=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid assistant data: object");return e},n=(e,t=256,s=!1)=>{if(typeof e!="string"||e.length>t*2||!s&&!e.trim()||e.includes("\0")||[...e].length>t)throw new Error("Invalid assistant data: text");return e},r=e=>{const t=n(e);if(["__proto__","constructor","prototype"].includes(t))throw new Error("Invalid assistant data: identifier");return t},p=(e,t=0,s=Number.MAX_SAFE_INTEGER)=>{if(!Number.isSafeInteger(e)||Number(e)<t||Number(e)>s)throw new Error("Invalid assistant data: integer");return e},I=e=>{if(typeof e!="boolean")throw new Error("Invalid assistant data: boolean");return e},m=(e,t)=>{if(!Array.isArray(e)||e.length>t)throw new Error("Invalid assistant data: array");return e},a=(e,t)=>{if(Object.keys(e).some(s=>!t.includes(s)))throw new Error("Invalid assistant data: unknown field")},g=e=>n(e,64),y=e=>m(e,32).map(t=>{const s=c(t),o=s.id===void 0?{}:{id:r(s.id)};if(s.kind==="unknown")return{...o,kind:"unknown",originalKind:n(s.originalKind,128),...s.textFallback===void 0?{}:{textFallback:n(s.textFallback,1e5,!0)}};if(s.kind==="text")return a(s,["id","kind","text"]),{...o,kind:"text",text:n(s.text,1e5,!0)};if(!["image","file","audio","video"].includes(String(s.kind)))throw new Error("Invalid assistant data: part kind");a(s,["id","kind","name","media"]);const i=c(s.media);a(i,["contentRef","contentType","sizeBytes","digestSha256"]);const l=n(i.digestSha256,64);if(!/^[0-9a-f]{64}$/.test(l))throw new Error("Invalid assistant data: digest");return{...o,kind:s.kind,...s.name===void 0?{}:{name:n(s.name,512,!0)},media:{contentRef:r(i.contentRef),contentType:n(i.contentType,256),sizeBytes:p(i.sizeBytes),digestSha256:l}}}),k=e=>{const t=c(e);if(a(t,["id","rating","revision","reason","comment"]),!["like","dislike","none"].includes(String(t.rating)))throw new Error("Invalid assistant data: rating");return{id:r(t.id),rating:t.rating,revision:p(t.revision,1),...t.reason===void 0?{}:{reason:n(t.reason,128,!0)},...t.comment===void 0?{}:{comment:n(t.comment,4e3,!0)}}},R=e=>{const t=c(e);return a(t,["itemId","partId","text","final","revision","parts"]),{itemId:r(t.itemId),partId:r(t.partId),text:n(t.text,1e5,!0),final:I(t.final),revision:p(t.revision,1),...t.parts===void 0?{}:{parts:y(t.parts)}}},b=e=>{const t=c(e);a(t,["chatId","responseId","status","items","cancelRequested","terminal","snapshotRevision"]);const s=m(t.items,20).map(R);if(new Set(s.map(o=>o.itemId)).size!==s.length||s.reduce((o,i)=>o+[...i.text].length,0)>1e5)throw new Error("Invalid assistant data: output budget or identity");return{chatId:r(t.chatId),responseId:r(t.responseId),status:g(t.status),...t.terminal===void 0?{}:{terminal:I(t.terminal)},...t.snapshotRevision===void 0?{}:{snapshotRevision:p(t.snapshotRevision,1)},items:s,...t.cancelRequested===void 0?{}:{cancelRequested:I(t.cancelRequested)}}},x=e=>{const t=c(e);if(a(t,["id","role","content","persistent","responseId","cursor","createdAt","parts","feedback"]),t.role!=="assistant"&&t.role!=="user"||t.persistent!==!0)throw new Error("Invalid assistant data: persisted message");return{id:r(t.id),role:t.role,content:n(t.content,1e5,!0),persistent:!0,cursor:w(t.cursor),createdAt:n(t.createdAt,64),...t.responseId===void 0?{}:{responseId:r(t.responseId)},...t.parts===void 0?{}:{parts:y(t.parts)},...t.feedback===void 0?{}:{feedback:k(t.feedback)}}},S=e=>{const t=c(e),s=t.type;if(s==="response.snapshot")return a(t,["type","snapshot"]),{type:s,snapshot:b(t.snapshot)};const o=r(t.responseId);if(s==="response.accepted")return a(t,["type","chatId","responseId","messageId","acceptedCursor"]),{type:s,responseId:o,chatId:r(t.chatId),messageId:r(t.messageId),...t.acceptedCursor===void 0?{}:{acceptedCursor:w(t.acceptedCursor)}};if(s==="response.state")return a(t,["type","chatId","responseId","status"]),{type:s,responseId:o,chatId:r(t.chatId),status:g(t.status)};if(s==="response.terminal"){a(t,["type","chatId","responseId","status","code"]);const d=g(t.status);if(!v(d))throw new Error("Invalid assistant data: terminal");return{type:s,responseId:o,chatId:r(t.chatId),status:d,...t.code===void 0?{}:{code:r(t.code)}}}if(s==="response.reconciled"){a(t,["type","chatId","responseId","messages"]);const d=m(t.messages,200).map(x);if(d.some(u=>u.responseId!==o)||new Set(d.map(u=>u.id)).size!==d.length||d.reduce((u,E)=>u+[...E.content].length,0)>1e6)throw new Error("Invalid assistant data: response history");return{type:s,responseId:o,chatId:r(t.chatId),messages:d}}const i=r(t.itemId),l=r(t.partId),f=p(t.sequence,1),h=["type","responseId","itemId","partId","sequence"];if(s==="response.output_item.added")return a(t,h),{type:s,responseId:o,itemId:i,partId:l,sequence:f};if(s==="response.output_text.delta")return a(t,[...h,"delta"]),{type:s,responseId:o,itemId:i,partId:l,sequence:f,delta:n(t.delta,1e5,!0)};if(s==="response.output_item.done")return a(t,[...h,"text","final"]),{type:s,responseId:o,itemId:i,partId:l,sequence:f,text:n(t.text,1e5,!0),final:I(t.final)};throw new Error("Invalid assistant data: event type")};exports.isResponseTerminal=v;exports.parseContentParts=y;exports.parseFeedback=k;exports.parseResponseEvent=S;exports.protocolArray=m;exports.protocolBoolean=I;exports.protocolCursor=w;exports.protocolId=r;exports.protocolInteger=p;exports.protocolRecord=c;exports.protocolText=n;
@@ -9,6 +9,11 @@ export type AssistantContentPart = {
9
9
  id?: string;
10
10
  kind: "text";
11
11
  text: string;
12
+ } | {
13
+ id?: string;
14
+ kind: "unknown";
15
+ originalKind: string;
16
+ textFallback?: string;
12
17
  } | {
13
18
  id?: string;
14
19
  kind: "image" | "file" | "audio" | "video";
@@ -27,6 +32,7 @@ export interface AssistantChat {
27
32
  appKey: string;
28
33
  agentId: string;
29
34
  title: string;
35
+ titlePending: boolean;
30
36
  status: "active" | "deleted";
31
37
  revision: number;
32
38
  pinned: boolean;
@@ -44,7 +50,7 @@ export interface AssistantAgent {
44
50
  appKey: string;
45
51
  name: string;
46
52
  }
47
- export type AssistantResponseStatus = "queued" | "dispatched" | "running" | "completed" | "failed" | "cancelled";
53
+ export type AssistantResponseStatus = "queued" | "dispatched" | "running" | "completed" | "failed" | "cancelled" | (string & {});
48
54
  export interface AssistantOutputItem {
49
55
  itemId: string;
50
56
  partId: string;
@@ -59,10 +65,13 @@ export interface AssistantResponseSnapshot {
59
65
  status: AssistantResponseStatus;
60
66
  items: AssistantOutputItem[];
61
67
  cancelRequested?: boolean;
68
+ terminal?: boolean;
69
+ snapshotRevision?: number;
62
70
  }
63
71
  export interface AssistantUpload {
64
72
  id: string;
65
- status: "uploading" | "ready" | "cancelled";
73
+ status: "uploading" | "ready" | "cancelled" | (string & {});
74
+ expiresAt?: string;
66
75
  name: string;
67
76
  contentType: string;
68
77
  sizeBytes: number;
@@ -81,7 +90,7 @@ export interface AssistantStoredMessage {
81
90
  content: string;
82
91
  persistent: true;
83
92
  responseId?: string;
84
- cursor: number;
93
+ cursor: string | number;
85
94
  createdAt: string;
86
95
  parts?: AssistantContentPart[];
87
96
  feedback?: AssistantFeedback;
@@ -153,7 +162,7 @@ export type AssistantResponseEvent = {
153
162
  chatId: string;
154
163
  responseId: string;
155
164
  messageId: string;
156
- acceptedCursor: number;
165
+ acceptedCursor?: string | number;
157
166
  } | {
158
167
  type: "response.state";
159
168
  chatId: string;
@@ -195,7 +204,8 @@ export type AssistantResponseEvent = {
195
204
  status: "completed" | "failed" | "cancelled";
196
205
  code?: string;
197
206
  };
198
- export declare const isResponseTerminal: (status: AssistantResponseStatus) => status is "completed" | "failed" | "cancelled";
207
+ export declare const isResponseTerminal: (value: AssistantResponseStatus | Pick<AssistantResponseSnapshot, "status" | "terminal">) => boolean;
208
+ export declare const protocolCursor: (value: unknown) => string | number;
199
209
  export declare const protocolRecord: (value: unknown) => Record<string, unknown>;
200
210
  export declare const protocolText: (value: unknown, maximum?: number, empty?: boolean) => string;
201
211
  export declare const protocolId: (value: unknown) => string;
@@ -20,7 +20,7 @@ export interface AssistantRegenerateRequest extends AssistantRunRequest {
20
20
  export interface AssistantTransportOptions {
21
21
  signal?: AbortSignal;
22
22
  threadId?: string;
23
- cursor?: number;
23
+ cursor?: string | number;
24
24
  }
25
25
  export interface AssistantTransportFeatures {
26
26
  history: boolean;
@@ -28,6 +28,7 @@ export interface AssistantTransportFeatures {
28
28
  regeneration?: boolean;
29
29
  remoteCancellation: boolean;
30
30
  conversationManagement?: boolean;
31
+ conversationEditing?: boolean;
31
32
  feedback?: boolean;
32
33
  attachments?: boolean;
33
34
  modelInputKinds?: ReadonlyArray<AssistantContentPart["kind"]>;
@@ -40,14 +41,14 @@ export interface AssistantConversationSnapshotMessage {
40
41
  responseId?: string;
41
42
  parts?: AssistantContentPart[];
42
43
  persistent?: boolean;
43
- cursor?: number;
44
+ cursor?: string | number;
44
45
  createdAt?: string;
45
46
  feedback?: AssistantFeedback;
46
47
  }
47
48
  export interface AssistantConversationSnapshot {
48
49
  threadId?: string;
49
50
  messages: ReadonlyArray<AssistantConversationSnapshotMessage>;
50
- nextCursor?: number;
51
+ nextCursor?: string | number;
51
52
  hasMore?: boolean;
52
53
  }
53
54
  export interface AssistantTransport extends AssistantManagementTransport {
@@ -57,7 +58,7 @@ export interface AssistantTransport extends AssistantManagementTransport {
57
58
  regenerate?(request: AssistantRegenerateRequest, options?: AssistantTransportOptions): AsyncIterable<AssistantEvent>;
58
59
  watchResponse?(context: MakeAssistantHostContext, response: AssistantResponseRef & {
59
60
  cursor?: string;
60
- historyCursor?: number;
61
+ historyCursor?: string | number;
61
62
  }, options?: AssistantTransportOptions): AsyncIterable<AssistantEvent>;
62
63
  }
63
64
  export type AssistantEvent = AssistantResponseEvent | {
@@ -111,7 +112,7 @@ export interface AssistantMessage {
111
112
  parts?: AssistantContentPart[];
112
113
  persistent?: boolean;
113
114
  intermediate?: boolean;
114
- cursor?: number;
115
+ cursor?: string | number;
115
116
  createdAt?: string;
116
117
  feedback?: AssistantFeedback;
117
118
  }
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("./conversation-Cvh-IVRV.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-BpmWa2VL.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 { t as p, q as d } from "./conversation-CZfbgCXd.js";
2
- import { s as E, M as T, o as _, n as b, u as R, l as y, r as M, v as S } from "./conversation-CZfbgCXd.js";
1
+ import { f as p, d } from "./conversation-DuqMadaQ.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-DuqMadaQ.js";
3
3
  const c = (r) => {
4
4
  const e = /* @__PURE__ */ new Set();
5
5
  for (const t of r) {
@@ -51,10 +51,10 @@ export {
51
51
  E as MAKE_AI_ARTIFACT_LIMITS,
52
52
  p as MAKE_AI_ARTIFACT_SCHEMA_VERSION,
53
53
  T as MAKE_AI_CONVERSATION_LIMITS,
54
- _ as appendUserMessage,
54
+ b as appendUserMessage,
55
55
  u as createArtifactCapabilities,
56
56
  f as createArtifactTemplateRegistry,
57
- b as createAssistantConversationState,
57
+ _ as createAssistantConversationState,
58
58
  l as extendArtifactTemplateRegistry,
59
59
  R as parseArtifact,
60
60
  y as parseAssistantEvent,
package/dist/make-app.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./conversation-Cvh-IVRV.cjs"),E=o=>{const a=r.protocolText(o,36);if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(a))throw new Error("Invalid Make App request: UUID");return a},T=o=>{const a=r.protocolText(o,512,!0);if(new TextEncoder().encode(a).length>512||/[\r\n/\\]/.test(a))throw new Error("Invalid Make App request: filename");return a},k=(o,a,n)=>{const c=r.protocolRecord(o);if(r.protocolKeys(c,["chatId","appKey","agentId","title","status","revision","pinned","pinnedAt","createdAt","lastActivityAt"]),c.appKey!==a.appKey||c.agentId!==a.agentId||n&&c.chatId!==n||!["active","deleted"].includes(String(c.status)))throw new Error("Invalid Make App response: chat scope");return{chatId:r.protocolId(c.chatId),appKey:a.appKey,agentId:a.agentId,title:r.protocolText(c.title,255,!0),status:c.status,revision:r.protocolInteger(c.revision,1),pinned:r.protocolBoolean(c.pinned),pinnedAt:c.pinnedAt==null?null:r.protocolText(c.pinnedAt,64),createdAt:r.protocolText(c.createdAt,64),lastActivityAt:r.protocolText(c.lastActivityAt,64)}},D=(o,a)=>{const n=r.protocolRecord(o),c=r.protocolArray(n.chats,100).map(g=>k(g,a));if(new Set(c.map(g=>g.chatId)).size!==c.length)throw new Error("Invalid Make App response: duplicate chat");const d=r.protocolText(n.nextCursor,8192,!0),h=r.protocolBoolean(n.hasMore);if(h!==!!d)throw new Error("Invalid Make App response: chat cursor");return{chats:c,nextCursor:d,hasMore:h}},O=(o,a,n)=>{const c=r.protocolRecord(o),d=r.protocolInteger(c.nextCursor,-1),h=r.protocolBoolean(c.hasMore);if(d<n||h&&d<=n)throw new Error("Invalid Make App response: history cursor did not advance");let g=0,p=n;const u=new Set,I=r.protocolArray(c.messages,200).map(v=>{const l=r.protocolRecord(v);if(l.role!=="user"&&l.role!=="assistant")throw new Error("Invalid Make App response: history role");const f=r.protocolInteger(l.cursor);if(f<=p||f>d)throw new Error("Invalid Make App response: history order");p=f;const A=l.messageId!==void 0,m=A?r.protocolId(l.messageId):`history-${a}-${f}`;if(u.has(m))throw new Error("Invalid Make App response: duplicate message");u.add(m);const s=r.protocolText(l.text,1e5,!0);if(g+=[...s].length,g>1e6)throw new Error("Invalid Make App response: history budget");return{id:m,role:l.role,content:s,persistent:A,cursor:f,createdAt:r.protocolText(l.createdAt,64),...l.responseId===void 0?{}:{responseId:r.protocolId(l.responseId)},...l.parts===void 0?{}:{parts:r.parseContentParts(l.parts)},...l.feedback===void 0?{}:{feedback:r.parseFeedback(l.feedback)}}});return{threadId:a,messages:I,nextCursor:d,hasMore:h}},x=(o,a)=>{const n=r.parseResponseSnapshot(o);if(n.chatId!==a.chatId||n.responseId!==a.responseId)throw new Error("Invalid Make App response: response scope");return n},R=(o,a)=>{const n=r.protocolRecord(o);if(!["uploading","ready","cancelled"].includes(String(n.status))||a&&n.id!==a)throw new Error("Invalid Make App response: upload");const c=r.protocolInteger(n.sizeBytes,0,64<<20),d=r.protocolInteger(n.partSize,1<<20,1<<20),h=r.protocolArray(n.completedParts,64).map(p=>r.protocolInteger(p,0,Math.max(0,Math.ceil(c/d)-1)));if(new Set(h).size!==h.length)throw new Error("Invalid Make App response: repeated upload part");const g={id:r.protocolId(n.id),status:n.status,name:T(n.name),contentType:r.protocolText(n.contentType,256),sizeBytes:c,partSize:d,completedParts:h};if(g.status==="ready"){const p=r.protocolRecord(n.content);if(p.kind!=="reference"||p.sizeBytes!==c||!/^[0-9a-f]{64}$/.test(String(p.digestSha256)))throw new Error("Invalid Make App response: content receipt");g.content={kind:"reference",contentRef:r.protocolId(p.contentRef),sizeBytes:c,digestSha256:String(p.digestSha256)}}return g},B=o=>{const a=r.protocolId(o.threadId),n=E(o.message.id);let c,d;if(o.message.parts!==void 0){const h=r.parseContentParts(o.message.parts);if(!h.length)throw new Error("Invalid Make App request: empty parts");const g=new Set;for(const p of h){const u=E(p.id);if(g.has(u))throw new Error("Invalid Make App request: duplicate part");if(g.add(u),p.kind!=="text"){p.name!==void 0&&T(p.name);const I=p.media.contentType;if(!/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/.test(I)||p.kind!=="file"&&(!I.startsWith(`${p.kind}/`)||I==="image/svg+xml"))throw new Error("Invalid Make App request: media type")}}if(d=h.filter(p=>p.kind==="text").map(p=>p.text).join(""),!d.trim()&&h.every(p=>p.kind==="text"))throw new Error("Invalid Make App request: empty input");c={chatId:a,messageId:n,parts:h}}else d=r.protocolText(o.message.content,8192),c={chatId:a,messageId:n,text:d};if(new TextEncoder().encode(d).length>8192||new TextEncoder().encode(JSON.stringify(c)).length>65536)throw new Error("输入内容过长,请控制在 8 KiB 文本和 32 个附件/文本片段以内");return c},F=()=>{const o=[];let a,n=!1,c;return{push(d){if(!n)if(a){const h=a;a=void 0,h.resolve({done:!1,value:d})}else o.length>=4096?this.fail(new Error("响应事件积压超过限制,请恢复对话")):o.push(d)},fail(d){c=d,n=!0,o.length=0,a?.reject(d),a=void 0},close(){n=!0,o.length=0,a?.resolve({done:!0,value:void 0}),a=void 0},next(){return c?Promise.reject(c):o.length?Promise.resolve({done:!1,value:o.shift()}):n?Promise.resolve({done:!0,value:void 0}):new Promise((d,h)=>{a={resolve:d,reject:h}})}}},S=(o,a)=>new Promise(n=>{if(a?.aborted){n();return}const c=()=>{clearTimeout(d),a?.removeEventListener("abort",c),n()},d=setTimeout(c,o);a?.addEventListener("abort",c,{once:!0})}),C=o=>{if(!/^\d{1,20}-\d{1,20}$/.test(o))throw new Error("Invalid Make App response: stream cursor");return o.split("-").map(BigInt)},q=(o,a)=>{const[n,c]=C(o),[d,h]=C(a);return n>d||n===d&&c>h},K=o=>{const a=o;return[400,401,403,404].includes(a?.status??a?.response?.status??0)||["AI_FORBIDDEN","AI_AUTH_REQUIRED","AI_AUTH_EXPIRED","AI_NOT_FOUND","AI_RESPONSE_NOT_FOUND"].includes(a?.code??"")||o instanceof Error&&o.message.startsWith("Invalid ")},z=["response.subscribed","response.state","response.output_item.added","response.output_text.delta","response.output_item.done","response.reset","response.snapshot","response.completed","response.failed","response.cancelled"];async function*$(o,a,n){if(n?.aborted)return;let c=o.cursor??"0-0";C(c);let d=0,h=!1,g=0;const p=new Map;yield{type:"response.state",chatId:o.chatId,responseId:o.responseId,status:"queued"};async function*u(I,v){if(I==="completed"){let l=o.historyCursor??-1,f=0;const A=[];let m=!0;for(;m&&!n?.aborted;){if(++f>200)throw new Error("历史恢复超过单次预算,请继续加载历史");const s=await a.loadHistory(o,l,n);for(const e of s.messages)if(e.responseId===o.responseId&&e.role==="assistant"&&e.persistent){const{artifacts:t,...i}=e;A.push(r.parseStoredMessage(i))}if(m=s.hasMore??!1,m&&(s.nextCursor??-1)<=l)throw new Error("Invalid Make App response: history cursor");l=s.nextCursor??l}if(n?.aborted)return;if(!A.length)throw new Error("回答已完成,历史尚未同步,请恢复对话");yield{type:"response.reconciled",chatId:o.chatId,responseId:o.responseId,messages:A}}yield{type:"response.terminal",chatId:o.chatId,responseId:o.responseId,status:I,...v?{code:v}:{}}}for(;!n?.aborted;){if(d>3){if(++g>600)throw new Error("响应连接中断,请恢复对话");let e;try{e=await a.getResponse(o,n)}catch(t){if(n?.aborted)return;if(K(t))throw t}if(e&&(yield{type:"response.snapshot",snapshot:e},r.isResponseTerminal(e.status))){yield*u(e.status);return}await S(Math.max(1e3,a.reconnectDelayMs),n);continue}const I=F();let v=0,l=!1;const f=a.eventSourceFactory({chatId:o.chatId,responseId:o.responseId,cursor:c},{withCredentials:!0}),A=z.map(e=>{const t=i=>{if(!(l||n?.aborted)){if(i.data.length>a.maxEventCharacters*2||[...i.data].length>a.maxEventCharacters||v+i.data.length>4e6){l=!0,f.close(),I.fail(new Error("Make App assistant SSE event exceeds maxEventCharacters"));return}v+=i.data.length,I.push({name:e,raw:i.data,id:i.lastEventId})}};return f.addEventListener(e,t),{name:e,listener:t}});f.onerror=()=>{!l&&!n?.aborted&&(l=!0,f.close(),I.push({reconnect:!0}))};const m=()=>{l=!0,f.close(),I.close()};n?.addEventListener("abort",m,{once:!0}),n?.aborted&&m();try{for(;!n?.aborted;){const e=await I.next();if(e.done)return;const t=e.value;if("reconnect"in t)break;if(v-=t.raw.length,t.id&&!q(t.id,c)){if(p.has(t.id)&&p.get(t.id)!==t.raw)throw new Error("Invalid Make App response: conflicting stream replay");continue}const i=r.protocolRecord(JSON.parse(t.raw));if(r.protocolId(i.responseId)!==o.responseId)throw new Error("Invalid Make App response: stream scope");if(t.name!=="response.subscribed"){if(t.name==="response.reset"){h=!0;continue}if(t.name==="response.snapshot"){const y=x(i,o);if(yield{type:"response.snapshot",snapshot:y},r.isResponseTerminal(y.status)){yield*u(y.status);return}}else if(t.name==="response.completed"||t.name==="response.cancelled"){yield*u(t.name==="response.completed"?"completed":"cancelled");return}else if(t.name==="response.failed"){if(i.code==="AI_UPSTREAM_ERROR"){l=!0,f.close();break}if(i.code==="AI_FORBIDDEN"||i.code==="AI_AUTH_EXPIRED")throw Object.assign(new Error("当前身份无法继续读取响应"),{code:i.code,status:i.code==="AI_FORBIDDEN"?403:401});yield*u("failed",typeof i.code=="string"?i.code:void 0);return}else t.name==="response.state"?yield r.parseAssistantEvent({type:t.name,chatId:o.chatId,...i}):h||(yield r.parseAssistantEvent({type:t.name,...i}));t.id&&(c=t.id,p.set(t.id,t.raw),p.size>512&&p.delete(p.keys().next().value))}}}finally{f.onerror=null,f.close(),I.close();for(const{name:e,listener:t}of A)f.removeEventListener(e,t);n?.removeEventListener("abort",m)}if(n?.aborted||(d+=1,console.info("[make-ai-assistant] response reconnect",{attempt:d}),await S(Math.min(a.reconnectDelayMs*2**(d-1),5e3),n),n?.aborted))return;let s;try{s=await a.getResponse(o,n)}catch(e){if(n?.aborted)return;if(K(e))throw e}if(s&&r.isResponseTerminal(s.status)){yield{type:"response.snapshot",snapshot:s},yield*u(s.status);return}h&&(d=4)}}const U=()=>Object.assign(new Error("Operation aborted"),{name:"AbortError"}),_=o=>{if(o?.aborted)throw U()},L=o=>{const a=r.protocolInteger(o.historyLimit??100,1,200),n=r.protocolInteger(o.maxEventCharacters??1e6,1,4e6),c=r.protocolInteger(o.reconnectDelayMs??500,1,3e4),d=o.modelInputKinds??["text"],h=o.readContent,g=s=>{const e=o.resolveScope(s);return{appKey:r.protocolId(e.appKey),agentId:r.protocolId(e.agentId),identityKey:r.protocolId(e.identityKey)}},p=s=>{const e=g(s);return`${e.identityKey}\0${e.appKey}\0${e.agentId}`},u=async(s,e,t,i)=>{_(i);const y=p(s);console.info("[make-ai-assistant] Make App operation start",{operation:e});try{const w=await t();if(_(i),y!==p(s))throw U();return w}catch(w){throw console.warn("[make-ai-assistant] Make App operation failed",{operation:e,errorType:w instanceof Error?w.name:typeof w}),w}},I=s=>({chatId:r.protocolId(s.chatId)}),v=s=>({...I(s),responseId:r.protocolId(s.responseId)}),l=s=>({...I(s),uploadId:r.protocolId(s.uploadId)}),f=async(s,e,t,i)=>u(s,"loadHistory",async()=>O(await o.loadHistory({chatId:r.protocolId(e),cursor:r.protocolInteger(t,-1),limit:a},{signal:i}),e,t),i),A=async(s,e,t)=>u(s,"getResponse",async()=>x(await o.getResponse(v(e),{signal:t}),e),t),m=(s,e,t)=>{const i=p(s),y=t?.signal;return(async function*(){for await(const w of $(e,{eventSourceFactory:o.eventSourceFactory,getResponse:(b,M)=>A(s,b,M),loadHistory:(b,M,P)=>f(s,b.chatId,M,P),maxEventCharacters:n,reconnectDelayMs:c},y)){if(y?.aborted||i!==p(s))return;yield w}})()};return{features:{history:!0,newConversation:!0,remoteCancellation:!0,regeneration:!1,conversationManagement:!0,feedback:!0,attachments:!0,modelInputKinds:d},scopeKey:p,listAgents:(s,e)=>u(s,"listAgents",async()=>{const t=g(s),i=r.protocolRecord(await o.listAgents({appKey:t.appKey},{signal:e?.signal}));return r.protocolArray(i.agents,1e3).map(y=>{const w=r.protocolRecord(y);if(w.appKey!==t.appKey)throw new Error("Invalid Make App response: agent scope");return{agentId:r.protocolId(w.agentId),appKey:t.appKey,name:r.protocolText(w.name)}})},e?.signal),listConversations:(s,e,t)=>u(s,"listChats",async()=>{const{appKey:i,agentId:y}=g(s);return D(await o.listChats({appKey:i,agentId:y,...e?.cursor?{cursor:r.protocolText(e.cursor,8192)}:{},limit:r.protocolInteger(e?.limit??50,1,100)},{signal:t?.signal}),{appKey:i,agentId:y})},t?.signal),createConversation:(s,e,t)=>u(s,"createChat",async()=>{const{appKey:i,agentId:y}=g(s),w={appKey:i,agentId:y,requestId:E(e.requestId),...e.title===void 0?{}:{title:r.protocolText(e.title.trim(),255)}};return k(await o.createChat(w,{signal:t?.signal}),{appKey:i,agentId:y})},t?.signal),getConversation:(s,e,t)=>u(s,"getChat",async()=>k(await o.getChat(I(e),{signal:t?.signal}),g(s),e.chatId),t?.signal),updateConversation:(s,e,t)=>u(s,"updateChat",async()=>{const i={...I(e),expectedRevision:r.protocolInteger(e.expectedRevision,1)};if(e.title!==void 0&&(i.title=r.protocolText(e.title.trim(),255)),e.pinned!==void 0){if(typeof e.pinned!="boolean")throw new Error("Invalid Make App request: pinned");i.pinned=e.pinned}if(i.title===void 0&&i.pinned===void 0)throw new Error("Invalid Make App request: empty patch");return k(await o.updateChat(i,{signal:t?.signal}),g(s),e.chatId)},t?.signal),deleteConversation:(s,e,t)=>u(s,"deleteChat",()=>o.deleteChat({...I(e),expectedRevision:r.protocolInteger(e.expectedRevision,1)},{signal:t?.signal}),t?.signal),loadConversation:async(s,e)=>e?.threadId?f(s,e.threadId,e.cursor??-1,e.signal):{messages:[]},getResponse:(s,e,t)=>A(s,e,t?.signal),cancelResponse:(s,e,t)=>u(s,"cancelResponse",async()=>x(await o.cancelResponse(v(e),{signal:t?.signal}),e),t?.signal),setFeedback:(s,e,t)=>u(s,"setFeedback",async()=>{if(!["like","dislike","none"].includes(e.rating))throw new Error("Invalid Make App request: rating");const i=r.protocolText(e.reason??"",128,!0).trim(),y=r.protocolText(e.comment??"",4e3,!0).trim();if(e.rating!=="dislike"&&(i||y))throw new Error("Invalid Make App request: feedback detail");return r.parseFeedback(await o.setFeedback({...I(e),messageId:r.protocolId(e.messageId),requestId:E(e.requestId),rating:e.rating,...i?{reason:i}:{},...y?{comment:y}:{}},{signal:t?.signal}))},t?.signal),startUpload:(s,e,t)=>u(s,"startUpload",async()=>R(await o.startUpload({...I(e),fileId:E(e.fileId),name:T(e.name),contentType:r.protocolText(e.contentType,256),sizeBytes:r.protocolInteger(e.sizeBytes,0,64<<20),...e.digestSha256?{digestSha256:r.protocolText(e.digestSha256,64)}:{}},{signal:t?.signal})),t?.signal),getUpload:(s,e,t)=>u(s,"getUpload",async()=>R(await o.getUpload(l(e),{signal:t?.signal}),e.uploadId),t?.signal),uploadPart:(s,e,t)=>u(s,"uploadPart",()=>{if(!(e.bytes instanceof Uint8Array)||e.bytes.byteLength>1<<20)throw new Error("Invalid Make App request: upload bytes");return o.uploadPart({...l(e),part:r.protocolInteger(e.part,0,63),bytes:e.bytes},{signal:t?.signal})},t?.signal),completeUpload:(s,e,t)=>u(s,"completeUpload",async()=>R(await o.completeUpload(l(e),{signal:t?.signal}),e.uploadId),t?.signal),...h?{readContent:(s,e,t)=>u(s,"readContent",async()=>{const i=await h({...I(e),contentRef:r.protocolId(e.contentRef)},{signal:t?.signal});if(!(i instanceof Uint8Array)||i.byteLength>64<<20)throw new Error("Invalid Make App response: content bytes");return i},t?.signal)}:{},watchResponse:m,async*run(s,e){if(e?.signal?.aborted)return;const t=B(s),i=await u(s.context,"sendMessage",async()=>r.protocolRecord(await o.sendMessage(t,{signal:e?.signal})),e?.signal);if(i.chatId!==t.chatId)throw new Error("Invalid Make App response: accepted chat");const y=r.protocolId(i.responseId),w=r.protocolInteger(i.acceptedCursor);yield{type:"response.accepted",chatId:t.chatId,responseId:y,messageId:t.messageId,acceptedCursor:w},yield*m(s.context,{chatId:t.chatId,responseId:y,historyCursor:w},e)}}};exports.createMakeAppAssistantTransport=L;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("./client.cjs"),w=require("./conversation-management-f1y0yRvt.cjs"),R=s=>({...s,titlePending:s.titlePending??!1}),x=s=>({id:s.messageId,role:s.role,content:s.text,persistent:!0,cursor:s.cursor,createdAt:s.createdAt,...s.responseId?{responseId:s.responseId}:{},...s.parts?{parts:[...s.parts]}:{},...s.feedback?{feedback:{...s.feedback}}:{}}),m=s=>({chatId:s.chatId,responseId:s.responseId,status:s.status,terminal:s.terminal,snapshotRevision:s.snapshotRevision,cancelRequested:s.cancelRequested,items:s.items.map(({parts:r,...i})=>({...i,...r?{parts:[...r]}:{}}))}),y=s=>({...s,completedParts:[...s.completedParts]}),E=s=>{if(!(s===void 0||s==="")){if(typeof s!="string")throw new d.ApiError("AI_BAD_REQUEST",{outcome:"notSent"});return s}},C=s=>{const r=w.protocolId(s.threadId),i=s.message.id;if(s.message.parts===void 0)return{chatId:r,messageId:i,text:s.message.content};const I=s.message.parts.map(p=>{if(!p.id||p.kind==="unknown")throw new d.ApiError("AI_BAD_REQUEST",{outcome:"notSent"});return{...p,id:p.id}});return{chatId:r,messageId:i,parts:I}};async function b(s){const{client:r}=s,i=w.protocolId(s.agentId),I=w.protocolInteger(s.historyLimit??100,1,200);console.info("[make-ai-assistant] Make App adapter initialize");let p;try{p=await r.capabilities.get({agentId:i},{signal:s.signal})}catch(a){throw console.warn("[make-ai-assistant] Make App adapter initialization failed"),a}const u=new Set(p.features),k=()=>`${r.scope.identityKey}\0${r.scope.appKey}\0${i}`,h=a=>{if(a.agentId!==i)throw new d.ApiError("AI_PROTOCOL_ERROR");return R(a)},f=async(a,e,t,o)=>{const n=[];for await(const c of r.messages.iterate({chatId:a,cursor:E(t),limit:I},{signal:o,maxPages:200,maxItems:4e4}))if(c.role==="assistant"&&c.responseId===e&&n.push(x(c)),n.length>200)throw new d.ApiError("AI_RESPONSE_TOO_LARGE");if(!n.length)throw new d.ApiError("AI_HISTORY_NOT_READY");return{type:"response.reconciled",chatId:a,responseId:e,messages:n}},g=(a,e,t)=>(async function*(){const o={chatId:e.chatId,responseId:e.responseId};yield{type:"response.state",...o,status:"queued"};for await(const n of r.responses.subscribe({...o,cursor:e.cursor},t))switch(n.kind){case"state":yield{type:"response.state",...o,status:n.status};break;case"itemAdded":yield{type:"response.output_item.added",responseId:n.responseId,itemId:n.itemId,partId:n.partId,sequence:n.sequence};break;case"textDelta":yield{type:"response.output_text.delta",responseId:n.responseId,itemId:n.itemId,partId:n.partId,sequence:n.sequence,delta:n.delta};break;case"itemDone":yield{type:"response.output_item.done",responseId:n.responseId,itemId:n.itemId,partId:n.partId,sequence:n.sequence,text:n.text,final:n.final};break;case"snapshot":if(yield{type:"response.snapshot",snapshot:m(n.snapshot)},n.snapshot.status==="completed"&&(yield await f(o.chatId,o.responseId,e.historyCursor,t?.signal)),n.snapshot.terminal)return;break;case"completed":case"failed":case"cancelled":n.kind==="completed"&&(yield await f(o.chatId,o.responseId,e.historyCursor,t?.signal)),yield{type:"response.terminal",...o,status:n.kind,...n.code?{code:n.code}:{}};return}})();return{scopeKey:k,features:{history:!0,newConversation:!0,conversationManagement:!0,conversationEditing:u.has("chat.management"),remoteCancellation:!0,regeneration:!1,feedback:u.has("feedback"),attachments:u.has("attachments.upload"),modelInputKinds:p.modelInputKinds.filter(a=>["text","image","file","audio","video"].includes(a))},async listAgents(a,e){const t=[];let o;for(let n=0;n<10;n++){const c=await r.agents.list({cursor:o,limit:100},e);if(t.push(...c.agents),!c.hasMore)return t;if(o===c.nextCursor)throw new d.ApiError("AI_PROTOCOL_ERROR");o=c.nextCursor}throw new d.ApiError("AI_ITERATION_LIMIT",{lastCursor:o})},async listConversations(a,e,t){const o=await r.chats.list({agentId:i,...e},t);return{...o,chats:o.chats.map(h)}},async createConversation(a,e,t){return h(await r.chats.create({agentId:i,...e},t))},async getConversation(a,e,t){return h(await r.chats.get(e,t))},async updateConversation(a,e,t){if(!u.has("chat.management"))throw new d.ApiError("AI_UNSUPPORTED_FEATURE",{outcome:"notSent"});if(e.title===void 0&&e.pinned===void 0)throw new d.ApiError("AI_BAD_REQUEST",{outcome:"notSent"});const o=e.title!==void 0?{...e,title:e.title}:{...e,pinned:e.pinned};return h(await r.chats.update(o,t))},deleteConversation:(a,e,t)=>{if(!u.has("chat.management"))throw new d.ApiError("AI_UNSUPPORTED_FEATURE",{outcome:"notSent"});return r.chats.delete(e,t)},async loadConversation(a,e){if(!e?.threadId)return{messages:[]};const t=await r.messages.list({chatId:e.threadId,cursor:E(e.cursor),limit:I},e);return{threadId:e.threadId,messages:t.messages.map(x),nextCursor:t.nextCursor,hasMore:t.hasMore}},async getResponse(a,e,t){return m(await r.responses.get(e,t))},async cancelResponse(a,e,t){return m(await r.responses.cancel(e,t))},setFeedback:(a,e,t)=>r.feedback.set(e,t),async startUpload(a,e,t){return y(await r.uploads.start(e,t))},async getUpload(a,e,t){return y(await r.uploads.get(e,t))},uploadPart:(a,e,t)=>r.uploads.putPart(e,t),async completeUpload(a,e,t){return y(await r.uploads.complete(e,t))},readContent:u.has("attachments.read")?async(a,e,t)=>{const o=await r.content.read({...e,maxBytes:p.limits.maxUploadBytes},t),n=[];let c=0;for await(const l of o.body)n.push(l),c+=l.length;const _=new Uint8Array(c);let A=0;for(const l of n)_.set(l,A),A+=l.length;return _}:void 0,watchResponse:g,async*run(a,e){const t=await r.messages.send(C(a),e);yield{type:"response.accepted",chatId:t.chatId,responseId:t.responseId,messageId:t.messageId,...t.acceptedCursor?{acceptedCursor:t.acceptedCursor}:{}},yield*g(a.context,{chatId:t.chatId,responseId:t.responseId,historyCursor:t.acceptedCursor},e)}}}exports.createMakeAppAssistantTransport=b;
@@ -1,71 +1,10 @@
1
- import type { AssistantTransport, MakeAssistantHostContext } from "./core/index.js";
2
- import { type AssistantCallOptions, type AssistantChatCreate, type AssistantChatPatch, type AssistantChatRef, type AssistantFeedbackWrite, type AssistantResponseRef, type AssistantUploadRef, type AssistantUploadStart, type AssistantContentPart } from "./core/conversation-management.js";
3
- import { type MessageInput } from "./make-app/protocol.js";
4
- export interface MakeAppAssistantEventSourceEvent {
5
- data: string;
6
- lastEventId: string;
7
- }
8
- export interface MakeAppAssistantEventSource {
9
- readonly readyState?: number;
10
- onerror: ((event: unknown) => void) | null;
11
- addEventListener(type: string, listener: (event: MakeAppAssistantEventSourceEvent) => void): void;
12
- removeEventListener(type: string, listener: (event: MakeAppAssistantEventSourceEvent) => void): void;
13
- close(): void;
14
- }
15
- export type MakeAppAssistantEventSourceFactory = (subscription: {
16
- chatId: string;
17
- cursor: string;
18
- responseId: string;
19
- }, init: {
20
- withCredentials: true;
21
- }) => MakeAppAssistantEventSource;
22
- export interface MakeAppAssistantScope {
23
- appKey: string;
24
- agentId: string;
25
- identityKey: string;
26
- }
1
+ import type { Client } from "./client-types.js";
2
+ import type { AssistantTransport } from "./core/index.js";
27
3
  export interface MakeAppAssistantTransportOptions {
28
- resolveScope(context: MakeAssistantHostContext): MakeAppAssistantScope;
29
- eventSourceFactory: MakeAppAssistantEventSourceFactory;
30
- historyLimit?: number;
31
- maxEventCharacters?: number;
32
- reconnectDelayMs?: number;
33
- modelInputKinds?: ReadonlyArray<AssistantContentPart["kind"]>;
34
- listAgents(input: {
35
- appKey: string;
36
- }, options: AssistantCallOptions): Promise<unknown>;
37
- listChats(input: {
38
- appKey: string;
39
- agentId: string;
40
- cursor?: string;
41
- limit?: number;
42
- }, options: AssistantCallOptions): Promise<unknown>;
43
- createChat(input: AssistantChatCreate & {
44
- appKey: string;
45
- agentId: string;
46
- }, options: AssistantCallOptions): Promise<unknown>;
47
- getChat(input: AssistantChatRef, options: AssistantCallOptions): Promise<unknown>;
48
- updateChat(input: AssistantChatPatch, options: AssistantCallOptions): Promise<unknown>;
49
- deleteChat(input: AssistantChatRef & {
50
- expectedRevision: number;
51
- }, options: AssistantCallOptions): Promise<void>;
52
- loadHistory(input: AssistantChatRef & {
53
- cursor: number;
54
- limit: number;
55
- }, options: AssistantCallOptions): Promise<unknown>;
56
- sendMessage(input: MessageInput, options: AssistantCallOptions): Promise<unknown>;
57
- getResponse(input: AssistantResponseRef, options: AssistantCallOptions): Promise<unknown>;
58
- cancelResponse(input: AssistantResponseRef, options: AssistantCallOptions): Promise<unknown>;
59
- setFeedback(input: AssistantFeedbackWrite, options: AssistantCallOptions): Promise<unknown>;
60
- startUpload(input: AssistantUploadStart, options: AssistantCallOptions): Promise<unknown>;
61
- getUpload(input: AssistantUploadRef, options: AssistantCallOptions): Promise<unknown>;
62
- uploadPart(input: AssistantUploadRef & {
63
- part: number;
64
- bytes: Uint8Array;
65
- }, options: AssistantCallOptions): Promise<void>;
66
- completeUpload(input: AssistantUploadRef, options: AssistantCallOptions): Promise<unknown>;
67
- readContent?(input: AssistantChatRef & {
68
- contentRef: string;
69
- }, options: AssistantCallOptions): Promise<Uint8Array>;
4
+ readonly client: Client;
5
+ readonly agentId: string;
6
+ readonly historyLimit?: number;
7
+ readonly signal?: AbortSignal;
70
8
  }
71
- export declare const createMakeAppAssistantTransport: (options: MakeAppAssistantTransportOptions) => AssistantTransport;
9
+ /** 将标准客户端结果映射为既有 UI 状态事件,宿主只提供认证传输和当前 Agent。 */
10
+ export declare function createMakeAppAssistantTransport(options: MakeAppAssistantTransportOptions): Promise<AssistantTransport>;