super-agent-sdk 1.0.4 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,18 +1,21 @@
1
- function u(n) {
2
- if (Array.isArray(n)) return n.map((e) => u(e));
3
- if (n && typeof n == "object" && n.constructor === Object) {
1
+ function f(a) {
2
+ if (Array.isArray(a)) return a.map((e) => f(e));
3
+ if (a && typeof a == "object" && a.constructor === Object) {
4
4
  const e = {};
5
- for (const [t, r] of Object.entries(n)) {
6
- const o = t.replace(/_([a-z])/g, (s, a) => a.toUpperCase());
7
- e[o] = u(r);
5
+ for (const [t, n] of Object.entries(a)) {
6
+ const o = t.replace(/_([a-z])/g, (r, s) => s.toUpperCase());
7
+ e[o] = f(n);
8
8
  }
9
9
  return e;
10
10
  }
11
- return n;
11
+ return a;
12
12
  }
13
- class g {
13
+ const w = "/api/agent/runtime/v1";
14
+ class I {
14
15
  constructor(e) {
15
- this.refreshing = null, this.baseUrl = e.baseUrl.replace(/\/$/, ""), this.appId = e.appId, this.token = e.token ?? "", this.botId = e.botId;
16
+ this.refreshing = null;
17
+ const t = e.baseUrl ?? w;
18
+ this.baseUrl = t.replace(/\/$/, ""), this.tokenGateway = e.tokenGateway.replace(/\/$/, ""), this.appId = e.appId ?? "", this.token = e.token ?? "", this.botId = e.botId, this.isAbsoluteUrl = /^https?:\/\//.test(this.baseUrl), this.isAbsoluteGateway = /^https?:\/\//.test(this.tokenGateway);
16
19
  }
17
20
  getBotId() {
18
21
  return this.botId;
@@ -23,28 +26,24 @@ class g {
23
26
  setToken(e) {
24
27
  this.token = e;
25
28
  }
26
- /** Derive the base origin from baseUrl (e.g. "https://example.com/api/v1" "https://example.com") */
29
+ /** Derive browser origin (for relative URL resolution) */
27
30
  getOrigin() {
28
- try {
29
- return new URL(this.baseUrl).origin;
30
- } catch {
31
- return "";
32
- }
31
+ return typeof window < "u" ? window.location.origin : "";
33
32
  }
34
- /** POST /api/token (fixed path) to get token */
33
+ /** POST {origin}{tokenGateway}/v1/token 获取 token + appId */
35
34
  async fetchToken() {
36
- const e = `${this.getOrigin()}/api/token`, t = await fetch(e, {
35
+ const t = `${this.isAbsoluteGateway ? this.tokenGateway : `${this.getOrigin()}${this.tokenGateway}`}/v1/token`, n = await fetch(t, {
37
36
  method: "POST",
38
37
  headers: { "Content-Type": "application/json" },
39
- body: JSON.stringify({ appId: this.appId, botId: this.botId })
38
+ body: JSON.stringify({ botId: this.botId })
40
39
  });
41
- if (!t.ok)
42
- throw new Error(`HTTP ${t.status}: ${t.statusText}`);
43
- const r = await t.json();
44
- if (r.code !== "200")
45
- throw new Error(r.message || `API error: ${r.code}`);
46
- const o = u(r.data);
47
- return this.token = o.token, o.token;
40
+ if (!n.ok)
41
+ throw new Error(`HTTP ${n.status}: ${n.statusText}`);
42
+ const o = await n.json();
43
+ if (o.code !== "200")
44
+ throw new Error(o.message || `API error: ${o.code}`);
45
+ const r = f(o.data);
46
+ return this.token = r.token, r.appId && !this.appId && (this.appId = r.appId), r.token;
48
47
  }
49
48
  headers(e) {
50
49
  return {
@@ -67,30 +66,30 @@ class g {
67
66
  this.refreshing = null;
68
67
  }
69
68
  }
70
- async request(e, t, r) {
69
+ async request(e, t, n) {
71
70
  if (!this.token && !await this.handleTokenRefresh())
72
71
  throw new Error("SDK token not available: POST /token failed");
73
- let o = `${this.baseUrl}${t}`;
74
- if (r != null && r.params) {
72
+ let o = this.isAbsoluteUrl ? `${this.baseUrl}${t}` : `${this.getOrigin()}${this.baseUrl}${t}`;
73
+ if (n != null && n.params) {
75
74
  const i = new URLSearchParams();
76
- for (const [l, d] of Object.entries(r.params))
75
+ for (const [l, d] of Object.entries(n.params))
77
76
  d != null && i.set(l, String(d));
78
77
  const c = i.toString();
79
78
  c && (o += `?${c}`);
80
79
  }
81
- const s = await fetch(o, {
80
+ const r = await fetch(o, {
82
81
  method: e,
83
82
  headers: this.headers(),
84
- body: r != null && r.body ? JSON.stringify(r.body) : void 0
83
+ body: n != null && n.body ? JSON.stringify(n.body) : void 0
85
84
  });
86
- if (s.status === 401 && !(r != null && r.retry) && await this.handleTokenRefresh())
87
- return this.request(e, t, { ...r, retry: !0 });
88
- if (!s.ok)
89
- throw new Error(`HTTP ${s.status}: ${s.statusText}`);
90
- const a = await s.json();
91
- if (a.code !== "200")
92
- throw new Error(a.message || `API error: ${a.code}`);
93
- return u(a.data);
85
+ if (r.status === 401 && !(n != null && n.retry) && await this.handleTokenRefresh())
86
+ return this.request(e, t, { ...n, retry: !0 });
87
+ if (!r.ok)
88
+ throw new Error(`HTTP ${r.status}: ${r.statusText}`);
89
+ const s = await r.json();
90
+ if (s.code !== "200")
91
+ throw new Error(s.message || `API error: ${s.code}`);
92
+ return f(s.data);
94
93
  }
95
94
  get(e, t) {
96
95
  return this.request("GET", e, { params: t });
@@ -105,26 +104,26 @@ class g {
105
104
  return this.request("DELETE", e);
106
105
  }
107
106
  /** For SSE streaming — returns raw Response (no envelope unwrap) */
108
- async streamPost(e, t, r) {
107
+ async streamPost(e, t, n) {
109
108
  if (!this.token && !await this.handleTokenRefresh())
110
109
  throw new Error("SDK token not available: POST /token failed");
111
- const o = `${this.baseUrl}${e}`, s = await fetch(o, {
110
+ const o = this.isAbsoluteUrl ? `${this.baseUrl}${e}` : `${this.getOrigin()}${this.baseUrl}${e}`, r = await fetch(o, {
112
111
  method: "POST",
113
112
  headers: this.headers(),
114
113
  body: JSON.stringify(t),
115
- signal: r
114
+ signal: n
116
115
  });
117
- return s.status === 401 && await this.handleTokenRefresh() ? fetch(o, {
116
+ return r.status === 401 && await this.handleTokenRefresh() ? fetch(o, {
118
117
  method: "POST",
119
118
  headers: this.headers(),
120
119
  body: JSON.stringify(t),
121
- signal: r
122
- }) : s;
120
+ signal: n
121
+ }) : r;
123
122
  }
124
123
  }
125
- function f(n) {
126
- const e = n.split(`
127
- `).map((r) => r.trim()).filter((r) => r.startsWith("data:")).map((r) => r.slice(5).trim());
124
+ function y(a) {
125
+ const e = a.split(`
126
+ `).map((n) => n.trim()).filter((n) => n.startsWith("data:")).map((n) => n.slice(5).trim());
128
127
  if (!e.length) return null;
129
128
  let t;
130
129
  try {
@@ -153,14 +152,19 @@ function f(n) {
153
152
  type: "tool_result",
154
153
  content: t.output ?? "",
155
154
  toolName: t.name,
156
- toolCallId: t.id
155
+ toolCallId: t.id,
156
+ // 通用 artifacts(type + data),原样透传
157
+ artifacts: Array.isArray(t.artifacts) ? t.artifacts : void 0,
158
+ // fill_html_template 的 render_mode + html
159
+ renderMode: t.render_mode ?? t.renderMode,
160
+ html: t.html
157
161
  };
158
162
  case "done":
159
163
  return {
160
164
  type: "done",
161
165
  content: t.content ?? "",
162
- // 后端 SSE 返回 session_id (snake_case),此处统一映射为 sessionId
163
- sessionId: t.sessionId ?? t.session_id ?? ""
166
+ sessionId: t.sessionId ?? t.session_id ?? "",
167
+ messageId: t.messageId ?? t.message_id
164
168
  };
165
169
  case "error":
166
170
  return { type: "error", content: t.message ?? "Unknown error" };
@@ -185,191 +189,216 @@ function f(n) {
185
189
  return null;
186
190
  }
187
191
  }
188
- async function y(n, e, t) {
189
- if (!n.body) {
192
+ async function m(a, e, t) {
193
+ if (!a.body) {
190
194
  t(new Error("Response body is null"));
191
195
  return;
192
196
  }
193
- const r = n.body.getReader(), o = new TextDecoder();
194
- let s = "";
197
+ const n = a.body.getReader(), o = new TextDecoder();
198
+ let r = "";
195
199
  try {
196
200
  for (; ; ) {
197
- const { value: a, done: i } = await r.read();
201
+ const { value: s, done: i } = await n.read();
198
202
  if (i) break;
199
- s += o.decode(a, { stream: !0 });
203
+ r += o.decode(s, { stream: !0 });
200
204
  let c;
201
- for (; (c = s.indexOf(`
205
+ for (; (c = r.indexOf(`
202
206
 
203
207
  `)) !== -1; ) {
204
- const l = s.slice(0, c);
205
- s = s.slice(c + 2);
206
- const d = f(l);
208
+ const l = r.slice(0, c);
209
+ r = r.slice(c + 2);
210
+ const d = y(l);
207
211
  d && e(d);
208
212
  }
209
213
  }
210
- if (s.trim()) {
211
- const a = f(s);
212
- a && e(a);
214
+ if (r.trim()) {
215
+ const s = y(r);
216
+ s && e(s);
213
217
  }
214
- } catch (a) {
215
- (a == null ? void 0 : a.name) !== "AbortError" && t(a instanceof Error ? a : new Error(String(a)));
218
+ } catch (s) {
219
+ (s == null ? void 0 : s.name) !== "AbortError" && t(s instanceof Error ? s : new Error(String(s)));
216
220
  } finally {
217
221
  try {
218
- r.releaseLock();
222
+ n.releaseLock();
219
223
  } catch {
220
224
  }
221
225
  }
222
226
  }
223
- function m(n, e) {
224
- const t = new AbortController(), r = e.signal ? I(e.signal, t.signal) : t.signal, o = {
225
- botId: n.getBotId(),
227
+ function k(a, e) {
228
+ const t = new AbortController(), n = e.signal ? b(e.signal, t.signal) : t.signal, o = {
229
+ botId: a.getBotId(),
226
230
  message: e.message,
227
231
  sessionId: e.sessionId,
228
232
  stream: e.stream !== !1
229
233
  };
230
- return o.stream ? n.streamPost("/chat", o, r).then((s) => {
231
- var a;
232
- if (!s.ok) {
233
- (a = e.onError) == null || a.call(e, new Error(`HTTP ${s.status}`));
234
+ return o.stream ? a.streamPost("/chat", o, n).then((r) => {
235
+ var s;
236
+ if (!r.ok) {
237
+ (s = e.onError) == null || s.call(e, new Error(`HTTP ${r.status}`));
234
238
  return;
235
239
  }
236
- return y(
237
- s,
240
+ return m(
241
+ r,
238
242
  (i) => {
239
243
  var c, l, d, h;
240
- i.type === "done" && i.sessionId ? (c = e.onDone) == null || c.call(e, { sessionId: i.sessionId, content: i.content }) : i.type === "done" ? (l = e.onDone) == null || l.call(e, { sessionId: "", content: i.content }) : i.type === "error" ? (d = e.onError) == null || d.call(e, new Error(i.content)) : (h = e.onMessage) == null || h.call(e, i);
244
+ i.type === "done" && i.sessionId ? (c = e.onDone) == null || c.call(e, { sessionId: i.sessionId, content: i.content, messageId: i.messageId }) : i.type === "done" ? (l = e.onDone) == null || l.call(e, { sessionId: "", content: i.content, messageId: i.messageId }) : i.type === "error" ? (d = e.onError) == null || d.call(e, new Error(i.content)) : (h = e.onMessage) == null || h.call(e, i);
241
245
  },
242
246
  (i) => {
243
247
  var c;
244
248
  return (c = e.onError) == null ? void 0 : c.call(e, i);
245
249
  }
246
250
  );
247
- }).catch((s) => {
248
- var a;
249
- (s == null ? void 0 : s.name) !== "AbortError" && ((a = e.onError) == null || a.call(e, s instanceof Error ? s : new Error(String(s))));
250
- }) : n.post("/chat", o).then((s) => {
251
- var a;
252
- (a = e.onDone) == null || a.call(e, {
253
- sessionId: s.sessionId,
254
- content: s.content ?? ""
251
+ }).catch((r) => {
252
+ var s;
253
+ (r == null ? void 0 : r.name) !== "AbortError" && ((s = e.onError) == null || s.call(e, r instanceof Error ? r : new Error(String(r))));
254
+ }) : a.post("/chat", o).then((r) => {
255
+ var s;
256
+ (s = e.onDone) == null || s.call(e, {
257
+ sessionId: r.sessionId,
258
+ content: r.content ?? "",
259
+ messageId: r.messageId
255
260
  });
256
- }).catch((s) => {
257
- var a;
258
- (a = e.onError) == null || a.call(e, s instanceof Error ? s : new Error(String(s)));
261
+ }).catch((r) => {
262
+ var s;
263
+ (s = e.onError) == null || s.call(e, r instanceof Error ? r : new Error(String(r)));
259
264
  }), t;
260
265
  }
261
- function I(n, e) {
262
- const t = new AbortController(), r = () => t.abort();
263
- return n.addEventListener("abort", r, { once: !0 }), e.addEventListener("abort", r, { once: !0 }), (n.aborted || e.aborted) && t.abort(), t.signal;
266
+ function b(a, e) {
267
+ const t = new AbortController(), n = () => t.abort();
268
+ return a.addEventListener("abort", n, { once: !0 }), e.addEventListener("abort", n, { once: !0 }), (a.aborted || e.aborted) && t.abort(), t.signal;
264
269
  }
265
- async function w(n) {
266
- return (await n.post("/chat/sessions", {
267
- botId: n.getBotId()
270
+ async function T(a) {
271
+ return (await a.post("/chat/sessions", {
272
+ botId: a.getBotId()
268
273
  })).sessionId;
269
274
  }
270
- function T(n) {
275
+ function S(a) {
271
276
  return {
272
277
  // 后端返回 thread_id,toCamelCase 转为 threadId,映射为 sessionId
273
- sessionId: n.threadId ?? n.sessionId,
274
- botId: n.botId,
275
- title: n.title,
276
- createTime: n.createTime,
277
- updateTime: n.updateTime
278
+ sessionId: a.threadId ?? a.sessionId,
279
+ botId: a.botId,
280
+ title: a.title,
281
+ createTime: a.createTime,
282
+ updateTime: a.updateTime
278
283
  };
279
284
  }
280
- async function b(n, e) {
281
- const t = await n.get("/chat/conversations", {
282
- botId: n.getBotId(),
285
+ async function $(a, e) {
286
+ const t = await a.get("/chat/conversations", {
287
+ botId: a.getBotId(),
283
288
  page: (e == null ? void 0 : e.page) ?? 1,
284
289
  size: (e == null ? void 0 : e.size) ?? 20
285
290
  });
286
291
  return {
287
292
  ...t,
288
- items: t.items.map(T)
293
+ items: t.items.map(S)
289
294
  };
290
295
  }
291
- async function k(n, e, t) {
292
- await n.patch(`/chat/conversations/${e}`, { title: t });
296
+ async function p(a, e, t) {
297
+ await a.patch(`/chat/conversations/${e}`, { title: t });
293
298
  }
294
- async function p(n, e) {
295
- await n.del(`/chat/conversations/${e}`);
299
+ async function A(a, e) {
300
+ await a.del(`/chat/conversations/${e}`);
296
301
  }
297
- async function S(n, e) {
298
- const t = await n.get(`/chat/conversations/${e}/messages`);
299
- return E(t);
302
+ async function C(a, e) {
303
+ const t = await a.get(`/chat/conversations/${e}/messages`);
304
+ return O(t);
300
305
  }
301
- function E(n) {
302
- const e = [], t = [...n].sort((r, o) => (r.seq ?? 0) - (o.seq ?? 0));
303
- for (const r of t) {
304
- const o = r.role;
305
- if (o === "system") continue;
306
- const s = r.messageId ?? `msg_${r.id}`, a = new Date(r.createTime ?? "").getTime() || Date.now();
307
- if (o === "human")
306
+ function O(a) {
307
+ var n, o, r;
308
+ const e = [], t = [...a].sort((s, i) => (s.seq ?? 0) - (i.seq ?? 0));
309
+ for (const s of t) {
310
+ const i = s.role;
311
+ if (i === "system") continue;
312
+ const c = s.messageId ?? `msg_${s.id}`, l = new Date(s.createTime ?? "").getTime() || Date.now();
313
+ if (i === "human")
308
314
  e.push({
309
- id: s,
315
+ id: c,
310
316
  role: "user",
311
- parts: [{ type: "text", content: r.content ?? "" }],
312
- timestamp: a
317
+ parts: [{ type: "text", content: s.content ?? "" }],
318
+ timestamp: l
313
319
  });
314
- else if (o === "ai") {
315
- const i = [];
316
- r.reasoning && i.push({ type: "thinking", content: r.reasoning }), r.content && i.push({ type: "text", content: r.content });
317
- const c = r.toolCalls;
318
- if (c && Array.isArray(c))
319
- for (const l of c) {
320
- let d;
320
+ else if (i === "ai") {
321
+ const d = [];
322
+ s.reasoning && d.push({ type: "thinking", content: s.reasoning }), s.content && d.push({ type: "text", content: s.content });
323
+ const h = s.toolCalls;
324
+ if (h && Array.isArray(h))
325
+ for (const u of h) {
326
+ let g;
321
327
  try {
322
- d = typeof l.args == "string" ? l.args : JSON.stringify(l.args ?? {});
328
+ g = typeof u.args == "string" ? u.args : JSON.stringify(u.args ?? {});
323
329
  } catch {
324
- d = String(l.args ?? "{}");
330
+ g = String(u.args ?? "{}");
325
331
  }
326
- i.push({
332
+ d.push({
327
333
  type: "tool_call",
328
- toolName: l.name ?? "",
329
- toolCallId: l.id ?? "",
330
- args: d
334
+ toolName: u.name ?? "",
335
+ toolCallId: u.id ?? "",
336
+ args: g
331
337
  });
332
338
  }
333
- e.push({ id: s, role: "assistant", parts: i, timestamp: a });
334
- } else o === "tool" && e.push({
335
- id: s,
336
- role: "assistant",
337
- parts: [{
338
- type: "tool_result",
339
- toolName: r.toolName ?? "",
340
- toolCallId: r.toolCallId ?? "",
341
- content: r.content ?? ""
342
- }],
343
- timestamp: a
344
- });
339
+ e.push({ id: c, role: "assistant", parts: d, timestamp: l });
340
+ } else if (i === "tool") {
341
+ const d = Array.isArray(s.artifacts) ? s.artifacts : void 0;
342
+ e.push({
343
+ id: c,
344
+ role: "assistant",
345
+ parts: [{
346
+ type: "tool_result",
347
+ toolName: s.toolName ?? "",
348
+ toolCallId: s.toolCallId ?? "",
349
+ content: s.content ?? "",
350
+ artifacts: d,
351
+ renderMode: ((n = s.metadata) == null ? void 0 : n.renderMode) ?? ((o = s.metadata) == null ? void 0 : o.render_mode),
352
+ html: (r = s.metadata) == null ? void 0 : r.html
353
+ }],
354
+ timestamp: l
355
+ });
356
+ }
345
357
  }
346
358
  return e;
347
359
  }
348
- async function C(n, e, t, r) {
349
- await n.post(`/chat/interrupt/${e}/respond`, {
350
- sessionId: t,
351
- action: r.action,
352
- value: r.value
353
- });
360
+ async function _(a, e, t, n, o, r) {
361
+ const s = await a.streamPost(
362
+ `/chat/interrupt/${e}/respond`,
363
+ {
364
+ sessionId: t,
365
+ action: n.action,
366
+ value: n.value
367
+ }
368
+ );
369
+ if (!s.ok) {
370
+ const i = new Error(`HTTP ${s.status}`);
371
+ throw r == null || r(i), i;
372
+ }
373
+ o && await m(
374
+ s,
375
+ (i) => {
376
+ i.type === "error" ? r == null || r(new Error(i.content)) : o(i);
377
+ },
378
+ (i) => r == null ? void 0 : r(i)
379
+ );
354
380
  }
355
- function O(n) {
356
- const e = new g(n), t = {
381
+ function E(a) {
382
+ const e = new I(a);
383
+ return {
357
384
  getToken: () => e.fetchToken(),
358
- createSession: () => w(e),
359
- chat: (r) => m(e, r),
360
- listConversations: (r) => b(e, r),
361
- renameConversation: (r, o) => k(e, r, o),
362
- deleteConversation: (r) => p(e, r),
363
- getMessages: (r) => S(e, r),
364
- respondInterrupt: (r, o, s) => C(e, r, o, s),
365
- setToken: (r) => e.setToken(r),
366
- feedback: (r, o) => {
367
- var s;
368
- (s = t.onFeedback) == null || s.call(t, r, o);
385
+ createSession: () => T(e),
386
+ chat: (n) => k(e, n),
387
+ listConversations: (n) => $(e, n),
388
+ renameConversation: (n, o) => p(e, n, o),
389
+ deleteConversation: (n) => A(e, n),
390
+ getMessages: (n) => C(e, n),
391
+ respondInterrupt: (n, o, r, s, i) => _(e, n, o, r, s, i),
392
+ setToken: (n) => e.setToken(n),
393
+ feedback: async (n, o, r) => {
394
+ const s = { type: o };
395
+ o === "dislike" && ((r == null ? void 0 : r.reason) != null && (s.reason = r.reason), r != null && r.remark && (s.remark = r.remark)), await e.post(`/chat/messages/${n}/feedback`, s);
396
+ },
397
+ cancelFeedback: async (n) => {
398
+ await e.del(`/chat/messages/${n}/feedback`);
369
399
  }
370
400
  };
371
- return t;
372
401
  }
373
402
  export {
374
- O as createSuperAgent
403
+ E as createSuperAgent
375
404
  };