@axiom-lattice/client-sdk 8.0.0 → 8.0.1

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
@@ -4702,7 +4702,6 @@ var _Client = class extends AbstractClient {
4702
4702
  const fullUrl = url.startsWith("http") ? url : `${this.config.baseURL}${url}`;
4703
4703
  const workspaceHeaders = this.getWorkspaceHeaders();
4704
4704
  const mergedHeaders = {
4705
- ...this.headers,
4706
4705
  ...workspaceHeaders,
4707
4706
  ...options.headers || {}
4708
4707
  };
@@ -5218,16 +5217,20 @@ var WeChatClient = class extends AbstractClient {
5218
5217
  "Content-Type": "application/json",
5219
5218
  Authorization: `Bearer ${this.config.apiKey}`,
5220
5219
  ...this.config.headers,
5220
+ ...this.getWorkspaceHeaders(),
5221
5221
  ...options?.headers || {}
5222
5222
  };
5223
5223
  if (this.tenantId) {
5224
5224
  headers["x-tenant-id"] = this.tenantId;
5225
5225
  }
5226
+ if (method === "DELETE" && !options?.body) {
5227
+ delete headers["Content-Type"];
5228
+ }
5226
5229
  return this.wechatRequest({
5227
5230
  url: fullUrl,
5228
5231
  method,
5229
5232
  data: options?.body,
5230
- headers: this.getWorkspaceHeaders()
5233
+ headers
5231
5234
  });
5232
5235
  }
5233
5236
  /**
@@ -5236,6 +5239,109 @@ var WeChatClient = class extends AbstractClient {
5236
5239
  streamRequest(options, onEvent, onComplete, onError) {
5237
5240
  return this.streamRun(options, onEvent, onComplete, onError);
5238
5241
  }
5242
+ /**
5243
+ * Returns the WeChat request primitive or throws a descriptive error when
5244
+ * this client is used outside a WeChat Mini Program runtime.
5245
+ */
5246
+ getWxRequest() {
5247
+ if (typeof wx === "undefined" || typeof wx.request !== "function") {
5248
+ throw new Error(
5249
+ "WeChat global `wx.request` is not available. Use WeChatClient inside a WeChat Mini Program runtime."
5250
+ );
5251
+ }
5252
+ return wx.request;
5253
+ }
5254
+ /**
5255
+ * Builds a stateful chunk processor: UTF-8 is decoded across chunk
5256
+ * boundaries and only complete SSE lines are parsed, so a JSON frame or a
5257
+ * multibyte character split across chunks is not lost.
5258
+ */
5259
+ createChunkProcessor(onEvent, onError) {
5260
+ const decoder = new import_encoding.default.TextDecoder("utf-8");
5261
+ let pending = "";
5262
+ const handleLine = (line) => {
5263
+ const trimmed = line.trim();
5264
+ if (!trimmed.startsWith("data:"))
5265
+ return;
5266
+ const payload = trimmed.slice("data:".length);
5267
+ const json = payload.startsWith(" ") ? payload.slice(1) : payload;
5268
+ try {
5269
+ onEvent(JSON.parse(json));
5270
+ } catch (error) {
5271
+ if (onError) {
5272
+ onError(error instanceof Error ? error : new Error(String(error)));
5273
+ }
5274
+ }
5275
+ };
5276
+ const push = (res) => {
5277
+ if (!res.data)
5278
+ return;
5279
+ pending += decoder.decode(res.data, { stream: true });
5280
+ const lines = pending.split("\n");
5281
+ pending = lines.pop();
5282
+ for (const line of lines) {
5283
+ handleLine(line);
5284
+ }
5285
+ };
5286
+ const flush = () => {
5287
+ pending += decoder.decode();
5288
+ const lines = pending.split("\n");
5289
+ pending = "";
5290
+ for (const line of lines) {
5291
+ handleLine(line);
5292
+ }
5293
+ };
5294
+ return { push, flush };
5295
+ }
5296
+ /**
5297
+ * Extracts a human-readable message from an error body. With
5298
+ * `responseType: "text"` the body can be an object, a JSON string, or plain
5299
+ * text.
5300
+ */
5301
+ errorMessageFromBody(data) {
5302
+ if (typeof data === "string") {
5303
+ const text = data.trim();
5304
+ if (!text)
5305
+ return void 0;
5306
+ try {
5307
+ return this.recordMessage(JSON.parse(text));
5308
+ } catch {
5309
+ return text;
5310
+ }
5311
+ }
5312
+ return this.recordMessage(data);
5313
+ }
5314
+ recordMessage(value) {
5315
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
5316
+ return void 0;
5317
+ }
5318
+ const record3 = value;
5319
+ if (typeof record3.message === "string" && record3.message) {
5320
+ return record3.message;
5321
+ }
5322
+ if (typeof record3.error === "string" && record3.error) {
5323
+ return record3.error;
5324
+ }
5325
+ return void 0;
5326
+ }
5327
+ /**
5328
+ * Maps a non-2xx stream response to the same typed errors as `makeRequest`,
5329
+ * returning `undefined` for 2xx responses.
5330
+ */
5331
+ streamStatusError(res) {
5332
+ const statusCode = res.statusCode;
5333
+ if (statusCode >= 200 && statusCode < 300)
5334
+ return void 0;
5335
+ const message = this.errorMessageFromBody(res.data);
5336
+ if (statusCode === 401) {
5337
+ return new AuthenticationError(message || "Authentication failed");
5338
+ }
5339
+ return new ApiError(
5340
+ message || `HTTP error! Status: ${statusCode}`,
5341
+ statusCode,
5342
+ res.data
5343
+ );
5344
+ }
5239
5345
  /**
5240
5346
  * Resume streaming from a known position
5241
5347
  * @param options - Options for resuming the stream
@@ -5245,19 +5351,27 @@ var WeChatClient = class extends AbstractClient {
5245
5351
  * @returns A function that can be called to stop the stream
5246
5352
  */
5247
5353
  resumeStream(options, onEvent, onComplete, onError) {
5354
+ const lastEventId = options.lastEventId?.trim();
5248
5355
  const headers = {
5249
5356
  "Content-Type": "application/json",
5357
+ Accept: "text/event-stream",
5250
5358
  Authorization: `Bearer ${this.config.apiKey}`,
5251
5359
  ...this.config.headers,
5252
- ...threadAffinityHeaders3(options.threadId)
5360
+ ...this.getWorkspaceHeaders(),
5361
+ ...threadAffinityHeaders3(options.threadId),
5362
+ ...lastEventId ? { "Last-Event-ID": lastEventId } : {}
5253
5363
  };
5254
5364
  if (this.tenantId) {
5255
5365
  headers["x-tenant-id"] = this.tenantId;
5256
5366
  }
5257
- const requestTask = wx.request({
5367
+ const processor = this.createChunkProcessor(onEvent, onError);
5368
+ let terminal = false;
5369
+ let aborted = false;
5370
+ const requestTask = this.getWxRequest()({
5258
5371
  url: `${this.config.baseURL}/api/resume_stream`,
5259
5372
  method: "POST",
5260
5373
  data: {
5374
+ assistant_id: options.assistantId,
5261
5375
  thread_id: options.threadId,
5262
5376
  message_id: options.messageId,
5263
5377
  known_content: options.knownContent,
@@ -5266,40 +5380,41 @@ var WeChatClient = class extends AbstractClient {
5266
5380
  header: headers,
5267
5381
  responseType: "text",
5268
5382
  enableChunked: true,
5269
- success: () => {
5383
+ success: (res) => {
5384
+ if (aborted || terminal)
5385
+ return;
5386
+ const error = this.streamStatusError(res);
5387
+ if (error) {
5388
+ terminal = true;
5389
+ if (onError)
5390
+ onError(error);
5391
+ }
5270
5392
  },
5271
5393
  fail: (err) => {
5394
+ if (aborted)
5395
+ return;
5396
+ terminal = true;
5272
5397
  if (onError) {
5273
5398
  onError(new Error(`Resume stream request failed: ${err.errMsg}`));
5274
5399
  }
5275
5400
  },
5276
5401
  complete: () => {
5402
+ if (terminal)
5403
+ return;
5404
+ processor.flush();
5277
5405
  if (onComplete) {
5278
5406
  onComplete();
5279
5407
  }
5280
5408
  }
5281
5409
  });
5282
5410
  requestTask.onChunkReceived((res) => {
5283
- if (!res.data)
5411
+ if (terminal)
5284
5412
  return;
5285
- const text = this.decodeUint8Array(res.data);
5286
- const lines = text.split("\n");
5287
- for (const line of lines) {
5288
- if (line.trim().startsWith("data: ")) {
5289
- try {
5290
- const eventData = JSON.parse(line.trim().slice(6));
5291
- onEvent(eventData);
5292
- } catch (error) {
5293
- if (onError) {
5294
- onError(
5295
- error instanceof Error ? error : new Error(String(error))
5296
- );
5297
- }
5298
- }
5299
- }
5300
- }
5413
+ processor.push(res);
5301
5414
  });
5302
5415
  return () => {
5416
+ aborted = true;
5417
+ terminal = true;
5303
5418
  requestTask.abort();
5304
5419
  };
5305
5420
  }
@@ -5318,8 +5433,11 @@ var WeChatClient = class extends AbstractClient {
5318
5433
  if (this.tenantId) {
5319
5434
  headers["x-tenant-id"] = this.tenantId;
5320
5435
  }
5436
+ if (method === "DELETE" && (data === void 0 || data === null)) {
5437
+ delete headers["Content-Type"];
5438
+ }
5321
5439
  return new Promise((resolve, reject) => {
5322
- wx.request({
5440
+ this.getWxRequest()({
5323
5441
  url,
5324
5442
  method,
5325
5443
  data,
@@ -5329,20 +5447,15 @@ var WeChatClient = class extends AbstractClient {
5329
5447
  const statusCode = res.statusCode;
5330
5448
  if (statusCode >= 200 && statusCode < 300) {
5331
5449
  resolve(res.data);
5332
- } else if (statusCode === 401) {
5450
+ return;
5451
+ }
5452
+ const message = this.errorMessageFromBody(res.data);
5453
+ if (statusCode === 401) {
5333
5454
  reject(
5334
- new AuthenticationError(
5335
- res.data?.message || "Authentication failed"
5336
- )
5455
+ new AuthenticationError(message || "Authentication failed")
5337
5456
  );
5338
5457
  } else {
5339
- reject(
5340
- new ApiError(
5341
- res.data?.message || "API Error",
5342
- statusCode,
5343
- res.data
5344
- )
5345
- );
5458
+ reject(new ApiError(message || "API Error", statusCode, res.data));
5346
5459
  }
5347
5460
  },
5348
5461
  fail: (err) => {
@@ -5362,29 +5475,48 @@ var WeChatClient = class extends AbstractClient {
5362
5475
  streamRun(options, onEvent, onComplete, onError) {
5363
5476
  const headers = {
5364
5477
  "Content-Type": "application/json",
5478
+ Accept: "text/event-stream",
5365
5479
  Authorization: `Bearer ${this.config.apiKey}`,
5366
5480
  ...this.config.headers,
5481
+ ...this.getWorkspaceHeaders(),
5367
5482
  ...threadAffinityHeaders3(options.threadId)
5368
5483
  };
5369
5484
  if (this.tenantId) {
5370
5485
  headers["x-tenant-id"] = this.tenantId;
5371
5486
  }
5372
5487
  const requestParams = this.buildStreamRequestParams(options);
5373
- const requestTask = wx.request({
5488
+ const processor = this.createChunkProcessor(onEvent, onError);
5489
+ let terminal = false;
5490
+ let aborted = false;
5491
+ const requestTask = this.getWxRequest()({
5374
5492
  url: `${this.config.baseURL}${requestParams.url}`,
5375
5493
  method: requestParams.method,
5376
5494
  data: requestParams.body,
5377
5495
  header: headers,
5378
5496
  responseType: "text",
5379
5497
  enableChunked: true,
5380
- success: () => {
5498
+ success: (res) => {
5499
+ if (aborted || terminal)
5500
+ return;
5501
+ const error = this.streamStatusError(res);
5502
+ if (error) {
5503
+ terminal = true;
5504
+ if (onError)
5505
+ onError(error);
5506
+ }
5381
5507
  },
5382
5508
  fail: (err) => {
5509
+ if (aborted)
5510
+ return;
5511
+ terminal = true;
5383
5512
  if (onError) {
5384
5513
  onError(new Error(`Stream request failed: ${err.errMsg}`));
5385
5514
  }
5386
5515
  },
5387
5516
  complete: async () => {
5517
+ if (terminal)
5518
+ return;
5519
+ processor.flush();
5388
5520
  if (onComplete) {
5389
5521
  if (options.enableReturnStateWhenSteamCompleted) {
5390
5522
  try {
@@ -5400,26 +5532,13 @@ var WeChatClient = class extends AbstractClient {
5400
5532
  }
5401
5533
  });
5402
5534
  requestTask.onChunkReceived((res) => {
5403
- if (!res.data)
5535
+ if (terminal)
5404
5536
  return;
5405
- const text = this.decodeUint8Array(res.data);
5406
- const lines = text.split("\n");
5407
- for (const line of lines) {
5408
- if (line.trim().startsWith("data: ")) {
5409
- try {
5410
- const eventData = JSON.parse(line.trim().slice(6));
5411
- onEvent(eventData);
5412
- } catch (error) {
5413
- if (onError) {
5414
- onError(
5415
- error instanceof Error ? error : new Error(String(error))
5416
- );
5417
- }
5418
- }
5419
- }
5420
- }
5537
+ processor.push(res);
5421
5538
  });
5422
5539
  return () => {
5540
+ aborted = true;
5541
+ terminal = true;
5423
5542
  requestTask.abort();
5424
5543
  };
5425
5544
  }
@@ -5476,16 +5595,26 @@ var WorkspaceClient = class {
5476
5595
  }
5477
5596
  async request(url, options = {}) {
5478
5597
  const fullUrl = `${this.baseURL}${url}`;
5598
+ const headers = {
5599
+ ...this.headers,
5600
+ ...options.headers
5601
+ };
5602
+ if (typeof options.method === "string" && options.method.toUpperCase() === "DELETE" && options.body == null) {
5603
+ for (const key of Object.keys(headers)) {
5604
+ if (key.toLowerCase() === "content-type") {
5605
+ delete headers[key];
5606
+ }
5607
+ }
5608
+ }
5479
5609
  const response = await fetch(fullUrl, {
5480
5610
  ...options,
5481
- headers: {
5482
- ...this.headers,
5483
- ...options.headers
5484
- }
5611
+ headers
5485
5612
  });
5486
5613
  if (!response.ok) {
5487
5614
  const err = await response.json().catch(() => ({}));
5488
- throw new Error(err.message || `HTTP error! Status: ${response.status}`);
5615
+ throw new Error(
5616
+ err.error || err.message || `HTTP error! Status: ${response.status}`
5617
+ );
5489
5618
  }
5490
5619
  return response.json();
5491
5620
  }
@@ -5499,10 +5628,16 @@ var WorkspaceClient = class {
5499
5628
  method: "POST",
5500
5629
  body: JSON.stringify(data)
5501
5630
  });
5631
+ if (!response.data) {
5632
+ throw new Error("Failed to create workspace");
5633
+ }
5502
5634
  return response.data;
5503
5635
  }
5504
5636
  async getWorkspace(workspaceId) {
5505
5637
  const response = await this.request(`/api/workspaces/${workspaceId}`);
5638
+ if (!response.data) {
5639
+ throw new Error("Workspace not found");
5640
+ }
5506
5641
  return response.data;
5507
5642
  }
5508
5643
  async updateWorkspace(workspaceId, updates) {
@@ -5513,6 +5648,9 @@ var WorkspaceClient = class {
5513
5648
  body: JSON.stringify(updates)
5514
5649
  }
5515
5650
  );
5651
+ if (!response.data) {
5652
+ throw new Error("Failed to update workspace");
5653
+ }
5516
5654
  return response.data;
5517
5655
  }
5518
5656
  async deleteWorkspace(workspaceId) {
@@ -5540,12 +5678,18 @@ var WorkspaceClient = class {
5540
5678
  body: JSON.stringify(data)
5541
5679
  }
5542
5680
  );
5681
+ if (!response.data) {
5682
+ throw new Error("Failed to create project");
5683
+ }
5543
5684
  return response.data;
5544
5685
  }
5545
5686
  async getProject(workspaceId, projectId) {
5546
5687
  const response = await this.request(
5547
5688
  `/api/workspaces/${workspaceId}/projects/${projectId}`
5548
5689
  );
5690
+ if (!response.data) {
5691
+ throw new Error("Project not found");
5692
+ }
5549
5693
  return response.data;
5550
5694
  }
5551
5695
  async updateProject(workspaceId, projectId, updates) {
@@ -5556,6 +5700,9 @@ var WorkspaceClient = class {
5556
5700
  body: JSON.stringify(updates)
5557
5701
  }
5558
5702
  );
5703
+ if (!response.data) {
5704
+ throw new Error("Failed to update project");
5705
+ }
5559
5706
  return response.data;
5560
5707
  }
5561
5708
  async deleteProject(workspaceId, projectId) {
@@ -5589,6 +5736,9 @@ var WorkspaceClient = class {
5589
5736
  const response = await this.request(
5590
5737
  `/api/workspaces/${workspaceId}/projects/${projectId}/readfile?${params}`
5591
5738
  );
5739
+ if (!response.data) {
5740
+ throw new Error("Failed to read file");
5741
+ }
5592
5742
  return response.data;
5593
5743
  }
5594
5744
  /**
@@ -5690,6 +5840,9 @@ var WorkspaceClient = class {
5690
5840
  params.set("path", fsPath);
5691
5841
  }
5692
5842
  const response = await this.request(`/api/filesystem/browse?${params}`);
5843
+ if (!response.data) {
5844
+ throw new Error("Failed to browse filesystem");
5845
+ }
5693
5846
  return response.data;
5694
5847
  }
5695
5848
  };