super-agent-sdk 1.0.2 → 1.0.4

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,38 +1,50 @@
1
- function h(s) {
2
- if (Array.isArray(s)) return s.map((e) => h(e));
3
- if (s && typeof s == "object" && s.constructor === Object) {
1
+ function u(n) {
2
+ if (Array.isArray(n)) return n.map((e) => u(e));
3
+ if (n && typeof n == "object" && n.constructor === Object) {
4
4
  const e = {};
5
- for (const [r, t] of Object.entries(s)) {
6
- const o = r.replace(/_([a-z])/g, (n, a) => a.toUpperCase());
7
- e[o] = h(t);
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);
8
8
  }
9
9
  return e;
10
10
  }
11
- return s;
11
+ return n;
12
12
  }
13
13
  class g {
14
14
  constructor(e) {
15
- this.refreshing = null, this.baseUrl = e.baseUrl.replace(/\/$/, ""), this.appId = e.appId ?? "", this.token = e.token ?? "", this.botId = e.botId;
15
+ this.refreshing = null, this.baseUrl = e.baseUrl.replace(/\/$/, ""), this.appId = e.appId, this.token = e.token ?? "", this.botId = e.botId;
16
16
  }
17
17
  getBotId() {
18
18
  return this.botId;
19
19
  }
20
- setToken(e, r) {
21
- this.appId = e, this.token = r;
20
+ getAppKey() {
21
+ return this.appId;
22
22
  }
23
- /** POST without auth headers (for /token endpoint) */
24
- async postPublic(e, r) {
25
- const t = `${this.baseUrl}${e}`, o = await fetch(t, {
23
+ setToken(e) {
24
+ this.token = e;
25
+ }
26
+ /** Derive the base origin from baseUrl (e.g. "https://example.com/api/v1" → "https://example.com") */
27
+ getOrigin() {
28
+ try {
29
+ return new URL(this.baseUrl).origin;
30
+ } catch {
31
+ return "";
32
+ }
33
+ }
34
+ /** POST /api/token (fixed path) to get token */
35
+ async fetchToken() {
36
+ const e = `${this.getOrigin()}/api/token`, t = await fetch(e, {
26
37
  method: "POST",
27
38
  headers: { "Content-Type": "application/json" },
28
- body: r ? JSON.stringify(r) : void 0
39
+ body: JSON.stringify({ appId: this.appId, botId: this.botId })
29
40
  });
30
- if (!o.ok)
31
- throw new Error(`HTTP ${o.status}: ${o.statusText}`);
32
- const n = await o.json();
33
- if (n.code !== "200")
34
- throw new Error(n.message || `API error: ${n.code}`);
35
- return h(n.data);
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;
36
48
  }
37
49
  headers(e) {
38
50
  return {
@@ -47,8 +59,7 @@ class g {
47
59
  return await this.refreshing, !0;
48
60
  try {
49
61
  return this.refreshing = (async () => {
50
- const e = await this.postPublic("/token", { botId: this.botId });
51
- this.appId = e.appId, this.token = e.token;
62
+ await this.fetchToken();
52
63
  })(), await this.refreshing, !0;
53
64
  } catch {
54
65
  return !1;
@@ -56,290 +67,309 @@ class g {
56
67
  this.refreshing = null;
57
68
  }
58
69
  }
59
- async request(e, r, t) {
60
- if ((!this.appId || !this.token) && !await this.handleTokenRefresh())
70
+ async request(e, t, r) {
71
+ if (!this.token && !await this.handleTokenRefresh())
61
72
  throw new Error("SDK token not available: POST /token failed");
62
- let o = `${this.baseUrl}${r}`;
63
- if (t != null && t.params) {
64
- const c = new URLSearchParams();
65
- for (const [l, d] of Object.entries(t.params))
66
- d != null && c.set(l, String(d));
67
- const i = c.toString();
68
- i && (o += `?${i}`);
73
+ let o = `${this.baseUrl}${t}`;
74
+ if (r != null && r.params) {
75
+ const i = new URLSearchParams();
76
+ for (const [l, d] of Object.entries(r.params))
77
+ d != null && i.set(l, String(d));
78
+ const c = i.toString();
79
+ c && (o += `?${c}`);
69
80
  }
70
- const n = await fetch(o, {
81
+ const s = await fetch(o, {
71
82
  method: e,
72
83
  headers: this.headers(),
73
- body: t != null && t.body ? JSON.stringify(t.body) : void 0
84
+ body: r != null && r.body ? JSON.stringify(r.body) : void 0
74
85
  });
75
- if (n.status === 401 && !(t != null && t.retry) && await this.handleTokenRefresh())
76
- return this.request(e, r, { ...t, retry: !0 });
77
- if (!n.ok)
78
- throw new Error(`HTTP ${n.status}: ${n.statusText}`);
79
- const a = await n.json();
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();
80
91
  if (a.code !== "200")
81
92
  throw new Error(a.message || `API error: ${a.code}`);
82
- return h(a.data);
93
+ return u(a.data);
83
94
  }
84
- get(e, r) {
85
- return this.request("GET", e, { params: r });
95
+ get(e, t) {
96
+ return this.request("GET", e, { params: t });
86
97
  }
87
- post(e, r) {
88
- return this.request("POST", e, { body: r });
98
+ post(e, t) {
99
+ return this.request("POST", e, { body: t });
89
100
  }
90
- patch(e, r) {
91
- return this.request("PATCH", e, { body: r });
101
+ patch(e, t) {
102
+ return this.request("PATCH", e, { body: t });
92
103
  }
93
104
  del(e) {
94
105
  return this.request("DELETE", e);
95
106
  }
96
107
  /** For SSE streaming — returns raw Response (no envelope unwrap) */
97
- async streamPost(e, r, t) {
98
- if ((!this.appId || !this.token) && !await this.handleTokenRefresh())
108
+ async streamPost(e, t, r) {
109
+ if (!this.token && !await this.handleTokenRefresh())
99
110
  throw new Error("SDK token not available: POST /token failed");
100
- const o = `${this.baseUrl}${e}`, n = await fetch(o, {
111
+ const o = `${this.baseUrl}${e}`, s = await fetch(o, {
101
112
  method: "POST",
102
113
  headers: this.headers(),
103
- body: JSON.stringify(r),
104
- signal: t
114
+ body: JSON.stringify(t),
115
+ signal: r
105
116
  });
106
- return n.status === 401 && await this.handleTokenRefresh() ? fetch(o, {
117
+ return s.status === 401 && await this.handleTokenRefresh() ? fetch(o, {
107
118
  method: "POST",
108
119
  headers: this.headers(),
109
- body: JSON.stringify(r),
110
- signal: t
111
- }) : n;
120
+ body: JSON.stringify(t),
121
+ signal: r
122
+ }) : s;
112
123
  }
113
124
  }
114
- function f(s) {
115
- const e = s.split(`
116
- `).map((t) => t.trim()).filter((t) => t.startsWith("data:")).map((t) => t.slice(5).trim());
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());
117
128
  if (!e.length) return null;
118
- let r;
129
+ let t;
119
130
  try {
120
- r = JSON.parse(e.join(`
131
+ t = JSON.parse(e.join(`
121
132
  `));
122
133
  } catch {
123
134
  return null;
124
135
  }
125
- switch (r.type) {
136
+ switch (t.type) {
126
137
  case "user":
127
- return { type: "user", content: r.content ?? "" };
138
+ return { type: "user", content: t.content ?? "" };
128
139
  case "thinking":
129
- return { type: "thinking", content: r.content ?? "" };
140
+ return { type: "thinking", content: t.content ?? "" };
130
141
  case "ai":
131
- return { type: "ai", content: r.content ?? "" };
142
+ return { type: "ai", content: t.content ?? "" };
132
143
  case "tool_call":
133
144
  return {
134
145
  type: "tool_call",
135
- content: r.name ?? "",
136
- toolName: r.name,
137
- toolCallId: r.id,
138
- args: typeof r.args == "string" ? r.args : JSON.stringify(r.args ?? {})
146
+ content: t.name ?? "",
147
+ toolName: t.name,
148
+ toolCallId: t.id,
149
+ args: typeof t.args == "string" ? t.args : JSON.stringify(t.args ?? {})
139
150
  };
140
151
  case "tool_result":
141
152
  return {
142
153
  type: "tool_result",
143
- content: r.output ?? "",
144
- toolName: r.name,
145
- toolCallId: r.id
154
+ content: t.output ?? "",
155
+ toolName: t.name,
156
+ toolCallId: t.id
146
157
  };
147
158
  case "done":
148
159
  return {
149
160
  type: "done",
150
- content: r.content ?? "",
161
+ content: t.content ?? "",
151
162
  // 后端 SSE 返回 session_id (snake_case),此处统一映射为 sessionId
152
- sessionId: r.sessionId ?? r.session_id ?? ""
163
+ sessionId: t.sessionId ?? t.session_id ?? ""
153
164
  };
154
165
  case "error":
155
- return { type: "error", content: r.message ?? "Unknown error" };
166
+ return { type: "error", content: t.message ?? "Unknown error" };
167
+ case "interrupt":
168
+ return {
169
+ type: "interrupt",
170
+ content: t.content ?? "",
171
+ interrupt: {
172
+ interruptId: t.interruptId ?? t.interrupt_id ?? "",
173
+ interruptType: t.interruptType ?? t.interrupt_type ?? "confirm",
174
+ content: t.content ?? "",
175
+ options: t.options,
176
+ placeholder: t.placeholder,
177
+ inputType: t.inputType ?? t.input_type,
178
+ maxLength: t.maxLength ?? t.max_length,
179
+ required: t.required,
180
+ fields: t.fields,
181
+ metadata: t.metadata
182
+ }
183
+ };
156
184
  default:
157
185
  return null;
158
186
  }
159
187
  }
160
- async function y(s, e, r) {
161
- if (!s.body) {
162
- r(new Error("Response body is null"));
188
+ async function y(n, e, t) {
189
+ if (!n.body) {
190
+ t(new Error("Response body is null"));
163
191
  return;
164
192
  }
165
- const t = s.body.getReader(), o = new TextDecoder();
166
- let n = "";
193
+ const r = n.body.getReader(), o = new TextDecoder();
194
+ let s = "";
167
195
  try {
168
196
  for (; ; ) {
169
- const { value: a, done: c } = await t.read();
170
- if (c) break;
171
- n += o.decode(a, { stream: !0 });
172
- let i;
173
- for (; (i = n.indexOf(`
197
+ const { value: a, done: i } = await r.read();
198
+ if (i) break;
199
+ s += o.decode(a, { stream: !0 });
200
+ let c;
201
+ for (; (c = s.indexOf(`
174
202
 
175
203
  `)) !== -1; ) {
176
- const l = n.slice(0, i);
177
- n = n.slice(i + 2);
204
+ const l = s.slice(0, c);
205
+ s = s.slice(c + 2);
178
206
  const d = f(l);
179
207
  d && e(d);
180
208
  }
181
209
  }
182
- if (n.trim()) {
183
- const a = f(n);
210
+ if (s.trim()) {
211
+ const a = f(s);
184
212
  a && e(a);
185
213
  }
186
214
  } catch (a) {
187
- (a == null ? void 0 : a.name) !== "AbortError" && r(a instanceof Error ? a : new Error(String(a)));
215
+ (a == null ? void 0 : a.name) !== "AbortError" && t(a instanceof Error ? a : new Error(String(a)));
188
216
  } finally {
189
217
  try {
190
- t.releaseLock();
218
+ r.releaseLock();
191
219
  } catch {
192
220
  }
193
221
  }
194
222
  }
195
- function m(s, e) {
196
- const r = new AbortController(), t = e.signal ? I(e.signal, r.signal) : r.signal, o = {
197
- botId: s.getBotId(),
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(),
198
226
  message: e.message,
199
227
  sessionId: e.sessionId,
200
228
  stream: e.stream !== !1
201
229
  };
202
- return o.stream ? s.streamPost("/chat", o, t).then((n) => {
230
+ return o.stream ? n.streamPost("/chat", o, r).then((s) => {
203
231
  var a;
204
- if (!n.ok) {
205
- (a = e.onError) == null || a.call(e, new Error(`HTTP ${n.status}`));
232
+ if (!s.ok) {
233
+ (a = e.onError) == null || a.call(e, new Error(`HTTP ${s.status}`));
206
234
  return;
207
235
  }
208
236
  return y(
209
- n,
210
- (c) => {
211
- var i, l, d, u;
212
- c.type === "done" && c.sessionId ? (i = e.onDone) == null || i.call(e, { sessionId: c.sessionId, content: c.content }) : c.type === "done" ? (l = e.onDone) == null || l.call(e, { sessionId: "", content: c.content }) : c.type === "error" ? (d = e.onError) == null || d.call(e, new Error(c.content)) : (u = e.onMessage) == null || u.call(e, c);
237
+ s,
238
+ (i) => {
239
+ 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);
213
241
  },
214
- (c) => {
215
- var i;
216
- return (i = e.onError) == null ? void 0 : i.call(e, c);
242
+ (i) => {
243
+ var c;
244
+ return (c = e.onError) == null ? void 0 : c.call(e, i);
217
245
  }
218
246
  );
219
- }).catch((n) => {
247
+ }).catch((s) => {
220
248
  var a;
221
- (n == null ? void 0 : n.name) !== "AbortError" && ((a = e.onError) == null || a.call(e, n instanceof Error ? n : new Error(String(n))));
222
- }) : s.post("/chat", o).then((n) => {
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) => {
223
251
  var a;
224
252
  (a = e.onDone) == null || a.call(e, {
225
- sessionId: n.sessionId,
226
- content: n.content ?? ""
253
+ sessionId: s.sessionId,
254
+ content: s.content ?? ""
227
255
  });
228
- }).catch((n) => {
256
+ }).catch((s) => {
229
257
  var a;
230
- (a = e.onError) == null || a.call(e, n instanceof Error ? n : new Error(String(n)));
231
- }), r;
258
+ (a = e.onError) == null || a.call(e, s instanceof Error ? s : new Error(String(s)));
259
+ }), t;
232
260
  }
233
- function I(s, e) {
234
- const r = new AbortController(), t = () => r.abort();
235
- return s.addEventListener("abort", t, { once: !0 }), e.addEventListener("abort", t, { once: !0 }), (s.aborted || e.aborted) && r.abort(), r.signal;
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;
236
264
  }
237
- async function w(s) {
238
- return (await s.post("/chat/sessions", {
239
- botId: s.getBotId()
265
+ async function w(n) {
266
+ return (await n.post("/chat/sessions", {
267
+ botId: n.getBotId()
240
268
  })).sessionId;
241
269
  }
242
- function b(s) {
270
+ function T(n) {
243
271
  return {
244
272
  // 后端返回 thread_id,toCamelCase 转为 threadId,映射为 sessionId
245
- sessionId: s.threadId ?? s.sessionId,
246
- botId: s.botId,
247
- title: s.title,
248
- createTime: s.createTime,
249
- updateTime: s.updateTime
273
+ sessionId: n.threadId ?? n.sessionId,
274
+ botId: n.botId,
275
+ title: n.title,
276
+ createTime: n.createTime,
277
+ updateTime: n.updateTime
250
278
  };
251
279
  }
252
- async function k(s, e) {
253
- const r = await s.get("/chat/conversations", {
254
- botId: s.getBotId(),
280
+ async function b(n, e) {
281
+ const t = await n.get("/chat/conversations", {
282
+ botId: n.getBotId(),
255
283
  page: (e == null ? void 0 : e.page) ?? 1,
256
284
  size: (e == null ? void 0 : e.size) ?? 20
257
285
  });
258
286
  return {
259
- ...r,
260
- items: r.items.map(b)
287
+ ...t,
288
+ items: t.items.map(T)
261
289
  };
262
290
  }
263
- async function T(s, e, r) {
264
- await s.patch(`/chat/conversations/${e}`, { title: r });
291
+ async function k(n, e, t) {
292
+ await n.patch(`/chat/conversations/${e}`, { title: t });
265
293
  }
266
- async function S(s, e) {
267
- await s.del(`/chat/conversations/${e}`);
294
+ async function p(n, e) {
295
+ await n.del(`/chat/conversations/${e}`);
268
296
  }
269
- async function E(s, e) {
270
- const r = await s.get(`/chat/conversations/${e}/messages`);
271
- return C(r);
297
+ async function S(n, e) {
298
+ const t = await n.get(`/chat/conversations/${e}/messages`);
299
+ return E(t);
272
300
  }
273
- function C(s) {
274
- const e = [], r = [...s].sort((t, o) => (t.seq ?? 0) - (o.seq ?? 0));
275
- for (const t of r) {
276
- const o = t.role;
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;
277
305
  if (o === "system") continue;
278
- const n = t.messageId ?? `msg_${t.id}`, a = new Date(t.createTime ?? "").getTime() || Date.now();
306
+ const s = r.messageId ?? `msg_${r.id}`, a = new Date(r.createTime ?? "").getTime() || Date.now();
279
307
  if (o === "human")
280
308
  e.push({
281
- id: n,
309
+ id: s,
282
310
  role: "user",
283
- parts: [{ type: "text", content: t.content ?? "" }],
311
+ parts: [{ type: "text", content: r.content ?? "" }],
284
312
  timestamp: a
285
313
  });
286
314
  else if (o === "ai") {
287
- const c = [];
288
- t.reasoning && c.push({ type: "thinking", content: t.reasoning }), t.content && c.push({ type: "text", content: t.content });
289
- const i = t.toolCalls;
290
- if (i && Array.isArray(i))
291
- for (const l of i) {
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) {
292
320
  let d;
293
321
  try {
294
322
  d = typeof l.args == "string" ? l.args : JSON.stringify(l.args ?? {});
295
323
  } catch {
296
324
  d = String(l.args ?? "{}");
297
325
  }
298
- c.push({
326
+ i.push({
299
327
  type: "tool_call",
300
328
  toolName: l.name ?? "",
301
329
  toolCallId: l.id ?? "",
302
330
  args: d
303
331
  });
304
332
  }
305
- e.push({ id: n, role: "assistant", parts: c, timestamp: a });
333
+ e.push({ id: s, role: "assistant", parts: i, timestamp: a });
306
334
  } else o === "tool" && e.push({
307
- id: n,
335
+ id: s,
308
336
  role: "assistant",
309
337
  parts: [{
310
338
  type: "tool_result",
311
- toolName: t.toolName ?? "",
312
- toolCallId: t.toolCallId ?? "",
313
- content: t.content ?? ""
339
+ toolName: r.toolName ?? "",
340
+ toolCallId: r.toolCallId ?? "",
341
+ content: r.content ?? ""
314
342
  }],
315
343
  timestamp: a
316
344
  });
317
345
  }
318
346
  return e;
319
347
  }
320
- function $(s) {
321
- const e = new g(s), r = {
322
- getToken: async () => {
323
- const t = await e.postPublic(
324
- "/token",
325
- { botId: e.getBotId() }
326
- );
327
- return e.setToken(t.appId, t.token), t;
328
- },
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
+ });
354
+ }
355
+ function O(n) {
356
+ const e = new g(n), t = {
357
+ getToken: () => e.fetchToken(),
329
358
  createSession: () => w(e),
330
- chat: (t) => m(e, t),
331
- listConversations: (t) => k(e, t),
332
- renameConversation: (t, o) => T(e, t, o),
333
- deleteConversation: (t) => S(e, t),
334
- getMessages: (t) => E(e, t),
335
- setToken: (t, o) => e.setToken(t, o),
336
- feedback: (t, o) => {
337
- var n;
338
- (n = r.onFeedback) == null || n.call(r, t, o);
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);
339
369
  }
340
370
  };
341
- return r;
371
+ return t;
342
372
  }
343
373
  export {
344
- $ as createSuperAgent
374
+ O as createSuperAgent
345
375
  };