@mitralab.io/sdk-core 0.3.9 → 0.3.11

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.js CHANGED
@@ -673,6 +673,55 @@ function expectImportExecution(value, context, errors = defaultSdkCoreErrorFacto
673
673
  if (!isNullableString(execution.errorMessage)) invalidField(context, "errorMessage", errors);
674
674
  return execution;
675
675
  }
676
+ function expectFileMetadata(value, context, errors = defaultSdkCoreErrorFactory) {
677
+ const file = expectObject(value, context, errors);
678
+ for (const field of ["id", "name", "contentType", "createdAt"]) {
679
+ if (typeof file[field] !== "string") invalidField(context, field, errors);
680
+ }
681
+ if (!isInteger(file.sizeBytes)) invalidField(context, "sizeBytes", errors);
682
+ if (!isOneOf(file.kind, ["TEMPORARY", "PERMANENT"])) {
683
+ invalidField(context, "kind", errors);
684
+ }
685
+ if (!isOneOf(file.visibility, ["PRIVATE", "RESTRICTED", "APP"])) {
686
+ invalidField(context, "visibility", errors);
687
+ }
688
+ if (!isOneOf(file.status, ["PENDING", "READY", "DELETED"])) {
689
+ invalidField(context, "status", errors);
690
+ }
691
+ if (!isOneOf(file.createdBy, ["USER", "FUNCTION"])) {
692
+ invalidField(context, "createdBy", errors);
693
+ }
694
+ for (const field of ["ownerUserId", "confirmedAt", "expiresAt"]) {
695
+ if (!isNullableString(file[field])) invalidField(context, field, errors);
696
+ }
697
+ return file;
698
+ }
699
+ function expectFileUpload(value, context, errors = defaultSdkCoreErrorFactory) {
700
+ const upload = expectObject(value, context, errors);
701
+ for (const field of ["fileId", "uploadUrl", "uploadMethod", "expiresAt"]) {
702
+ if (typeof upload[field] !== "string" || !upload[field]) invalidField(context, field, errors);
703
+ }
704
+ if (!isStringRecord(upload.uploadHeaders)) invalidField(context, "uploadHeaders", errors);
705
+ return upload;
706
+ }
707
+ function expectFileReadUrl(value, context, errors = defaultSdkCoreErrorFactory) {
708
+ const read = expectObject(value, context, errors);
709
+ if (typeof read.url !== "string" || !read.url) invalidField(context, "url", errors);
710
+ if (typeof read.expiresAt !== "string") invalidField(context, "expiresAt", errors);
711
+ return read;
712
+ }
713
+ function expectFileReadUrls(value, context, errors = defaultSdkCoreErrorFactory) {
714
+ const response = expectObject(value, context, errors);
715
+ expectObjectArray(response.results, `${context} results`, errors).forEach(
716
+ (item, position) => {
717
+ const itemContext = `${context} result ${position}`;
718
+ if (typeof item.fileId !== "string") invalidField(itemContext, "fileId", errors);
719
+ if (typeof item.errorCode === "string") return;
720
+ expectFileReadUrl(item, itemContext, errors);
721
+ }
722
+ );
723
+ return response;
724
+ }
676
725
  function expectMessageAccepted(value, context, errors = defaultSdkCoreErrorFactory) {
677
726
  const response = expectObject(value, context, errors);
678
727
  if (typeof response.messageId !== "string") invalidField(context, "messageId", errors);
@@ -931,7 +980,40 @@ function expectAgentTask(value, context, errors = defaultSdkCoreErrorFactory) {
931
980
  if (typeof task.archived !== "boolean") invalidField(context, "archived", errors);
932
981
  if (!isNullableString(task.createdAt)) invalidField(context, "createdAt", errors);
933
982
  if (typeof task.updatedAt !== "string") invalidField(context, "updatedAt", errors);
934
- return task;
983
+ const { turn: rawTurn, instructions: rawInstructions, folderKey: rawFolderKey, ...rest } = task;
984
+ const turn = rawTurn === null ? null : agentTaskTurnOf(rawTurn);
985
+ const instructions = typeof rawInstructions === "string" ? rawInstructions : void 0;
986
+ const folderKey = typeof rawFolderKey === "string" ? rawFolderKey : void 0;
987
+ return {
988
+ ...rest,
989
+ ...turn !== void 0 ? { turn } : {},
990
+ ...instructions !== void 0 ? { instructions } : {},
991
+ ...folderKey !== void 0 ? { folderKey } : {}
992
+ };
993
+ }
994
+ function agentTaskTurnOf(value) {
995
+ if (!isObject(value)) return void 0;
996
+ if (typeof value.state !== "string") return void 0;
997
+ if (!isNullableString(value.currentTurnId) || !isCount(value.queuedCount)) return void 0;
998
+ if (value.lastTurn === null) return value;
999
+ const lastTurn = value.lastTurn;
1000
+ if (!isObject(lastTurn)) return void 0;
1001
+ if (typeof lastTurn.turnId !== "string" || typeof lastTurn.status !== "string") return void 0;
1002
+ if (!isStringArray(lastTurn.messageIds)) return void 0;
1003
+ const nullableTexts = ["finishReason", "errorCode", "startedAt", "endedAt"];
1004
+ if (!nullableTexts.every((field) => isNullableString(lastTurn[field]))) return void 0;
1005
+ return value;
1006
+ }
1007
+ function expectAgentTaskTurnStates(value, context, errors = defaultSdkCoreErrorFactory) {
1008
+ return expectObjectArray(value, context, errors).map((state, position) => {
1009
+ if (typeof state.taskId !== "string") {
1010
+ invalidField(`${context} item ${position}`, "taskId", errors);
1011
+ }
1012
+ return {
1013
+ ...state,
1014
+ turn: agentTaskTurnOf(state.turn) ?? null
1015
+ };
1016
+ });
935
1017
  }
936
1018
  function expectAgentTaskChannel(value, context, errors = defaultSdkCoreErrorFactory) {
937
1019
  if (value === void 0 || value === null || value === "") return null;
@@ -1005,6 +1087,22 @@ function agentTurnUsageOf(value) {
1005
1087
  }
1006
1088
  return usage;
1007
1089
  }
1090
+ function agentTurnCompactionsOf(value) {
1091
+ if (!Array.isArray(value)) return [];
1092
+ return value.flatMap((item) => {
1093
+ const compaction = agentTurnCompactionOf(item);
1094
+ return compaction ? [compaction] : [];
1095
+ });
1096
+ }
1097
+ function agentTurnCompactionOf(value) {
1098
+ if (!isObject(value) || typeof value.trigger !== "string") return void 0;
1099
+ return {
1100
+ trigger: value.trigger,
1101
+ tokensBefore: isCount(value.tokensBefore) ? value.tokensBefore : null,
1102
+ tokensAfter: isCount(value.tokensAfter) ? value.tokensAfter : null,
1103
+ at: typeof value.at === "string" ? value.at : null
1104
+ };
1105
+ }
1008
1106
  function agentTurnUsageRequestOf(value) {
1009
1107
  if (!isObject(value)) return void 0;
1010
1108
  const request = {};
@@ -1643,6 +1741,8 @@ function createAgentsModule(functionsTransport, copilotTransport, errors = defau
1643
1741
  }
1644
1742
 
1645
1743
  // src/modules/agentTasks.ts
1744
+ var TURN_STATES_BATCH_SIZE = 100;
1745
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
1646
1746
  function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory) {
1647
1747
  const path = (id) => `/api/v1/tasks/${encodePathSegment(id, "task id", errors)}`;
1648
1748
  return {
@@ -1656,12 +1756,18 @@ function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory)
1656
1756
  search: options.search,
1657
1757
  userId: options.userId
1658
1758
  };
1659
- return expectPage(
1759
+ const context = "Agent task page response";
1760
+ const page = expectPage(
1660
1761
  await transport.request("/api/v1/tasks", { method: "GET", params }),
1661
- "Agent task page response",
1662
- errors,
1663
- expectAgentTask
1762
+ context,
1763
+ errors
1664
1764
  );
1765
+ return {
1766
+ ...page,
1767
+ content: page.content.map(
1768
+ (task, position) => expectAgentTask(task, `${context} item ${position}`, errors)
1769
+ )
1770
+ };
1665
1771
  },
1666
1772
  async get(id) {
1667
1773
  return expectAgentTask(
@@ -1684,6 +1790,16 @@ function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory)
1684
1790
  errors
1685
1791
  );
1686
1792
  },
1793
+ async setInstructions(id, instructions) {
1794
+ return expectAgentTask(
1795
+ await transport.request(`${path(id)}/instructions`, {
1796
+ method: "PUT",
1797
+ body: { instructions }
1798
+ }),
1799
+ "Agent task instructions response",
1800
+ errors
1801
+ );
1802
+ },
1687
1803
  async archive(id) {
1688
1804
  expectEmpty(
1689
1805
  await transport.request(`${path(id)}/archive`, { method: "PATCH" }),
@@ -1728,6 +1844,26 @@ function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory)
1728
1844
  "Agent task channel response",
1729
1845
  errors
1730
1846
  );
1847
+ },
1848
+ async turnStates(ids) {
1849
+ const unique = [...new Set(ids.map((id) => id.toLowerCase()))].filter((id) => UUID.test(id));
1850
+ const states = [];
1851
+ for (let start = 0; start < unique.length; start += TURN_STATES_BATCH_SIZE) {
1852
+ const taskIds = unique.slice(start, start + TURN_STATES_BATCH_SIZE);
1853
+ states.push(
1854
+ ...expectAgentTaskTurnStates(
1855
+ await transport.request("/api/v1/tasks/turn-states", {
1856
+ method: "GET",
1857
+ // Joined here because a transport may send an array as repeated keys; the Copilot
1858
+ // reads one comma-separated value.
1859
+ params: { taskIds: taskIds.join(",") }
1860
+ }),
1861
+ "Agent task turn states response",
1862
+ errors
1863
+ )
1864
+ );
1865
+ }
1866
+ return states;
1731
1867
  }
1732
1868
  };
1733
1869
  }
@@ -2298,6 +2434,248 @@ function createEntitiesModule(transport, errors = defaultSdkCoreErrorFactory) {
2298
2434
  });
2299
2435
  }
2300
2436
 
2437
+ // src/fileTransferError.ts
2438
+ var FileTransferError = class extends Error {
2439
+ fileId;
2440
+ step;
2441
+ /**
2442
+ * HTTP status storage answered in `send` and `download`; null when storage gave no status or the
2443
+ * content failed to arrive, and always in `confirm`.
2444
+ */
2445
+ status;
2446
+ /**
2447
+ * True when the `PENDING` file a failed `send` left behind was deleted. False when that delete
2448
+ * failed too, and always in `confirm` and `download`, where nothing is deleted.
2449
+ */
2450
+ cleanedUp;
2451
+ constructor(message, details) {
2452
+ super(message, details.cause === void 0 ? void 0 : { cause: details.cause });
2453
+ this.name = "FileTransferError";
2454
+ this.fileId = details.fileId;
2455
+ this.step = details.step;
2456
+ this.status = details.status ?? null;
2457
+ this.cleanedUp = details.cleanedUp ?? false;
2458
+ }
2459
+ };
2460
+
2461
+ // src/modules/files.ts
2462
+ var MAX_READ_URLS = 100;
2463
+ var UNTYPED_CONTENT = "application/octet-stream";
2464
+ var REDACTED = "<redacted>";
2465
+ var MAX_CAUSE_DEPTH = 5;
2466
+ var MIN_SECRET_LENGTH = 16;
2467
+ var UNREADABLE_STORAGE_ERROR = "storage failed with an error the Core cannot show";
2468
+ function createFilesModule(transport, options = {}, errors = defaultSdkCoreErrorFactory) {
2469
+ const path = (fileId) => `/api/v1/files/${encodePathSegment(fileId, "file id", errors)}`;
2470
+ const storageFetch = () => {
2471
+ if (options.fetch) return options.fetch;
2472
+ const global = globalThis.fetch;
2473
+ if (typeof global !== "function") {
2474
+ configurationError("fetch is not available: pass files.fetch to the Core", errors);
2475
+ }
2476
+ return global;
2477
+ };
2478
+ const requestUpload = async (input) => expectFileUpload(
2479
+ await transport.request("/api/v1/files", { method: "POST", body: input }),
2480
+ "File upload response",
2481
+ errors
2482
+ );
2483
+ const confirmUpload = async (fileId) => expectFileMetadata(
2484
+ await transport.request(`${path(fileId)}/confirm`, { method: "POST" }),
2485
+ "Confirm file upload response",
2486
+ errors
2487
+ );
2488
+ const getUrl = async (fileId, { expiresInSeconds } = {}) => expectFileReadUrl(
2489
+ await transport.request(`${path(fileId)}/read-url`, {
2490
+ method: "POST",
2491
+ ...expiresInSeconds === void 0 ? {} : { body: { expiresInSeconds } }
2492
+ }),
2493
+ "File read URL response",
2494
+ errors
2495
+ );
2496
+ const deleteFile = async (fileId) => {
2497
+ expectEmpty(
2498
+ await transport.request(path(fileId), { method: "DELETE" }),
2499
+ "Delete file response",
2500
+ errors
2501
+ );
2502
+ };
2503
+ const sendContent = async (fetch, upload, content, signal) => {
2504
+ const failure = await putContent(fetch, upload, content, signal);
2505
+ if (failure === null) return;
2506
+ const cleanedUp = await deleteFile(upload.fileId).then(
2507
+ () => true,
2508
+ () => false
2509
+ );
2510
+ if (failure.aborted && signal !== void 0) throw abortReason(signal);
2511
+ throw new FileTransferError(`File ${upload.fileId} was not sent: ${failure.reason}`, {
2512
+ fileId: upload.fileId,
2513
+ step: "send",
2514
+ status: failure.status,
2515
+ cause: "error" in failure ? storageCause(failure.error, upload.uploadUrl) : void 0,
2516
+ cleanedUp
2517
+ });
2518
+ };
2519
+ const confirmSent = async (fileId) => {
2520
+ try {
2521
+ return await confirmUpload(fileId);
2522
+ } catch (error) {
2523
+ throw new FileTransferError(
2524
+ `File ${fileId} was sent but not confirmed: ${messageOf(error)}`,
2525
+ {
2526
+ fileId,
2527
+ step: "confirm",
2528
+ cause: error
2529
+ }
2530
+ );
2531
+ }
2532
+ };
2533
+ return {
2534
+ requestUpload,
2535
+ confirmUpload,
2536
+ async upload(content, uploadOptions) {
2537
+ const fetch = storageFetch();
2538
+ const input = uploadInput(content, uploadOptions, errors);
2539
+ const { signal } = uploadOptions;
2540
+ if (signal?.aborted) throw abortReason(signal);
2541
+ const upload = await requestUpload(input);
2542
+ await sendContent(fetch, upload, content, signal);
2543
+ return confirmSent(upload.fileId);
2544
+ },
2545
+ getUrl,
2546
+ async getUrls(fileIds, { expiresInSeconds } = {}) {
2547
+ requireBatchSize(fileIds, "fileIds", MAX_READ_URLS, errors);
2548
+ return expectFileReadUrls(
2549
+ await transport.request("/api/v1/files/read-urls", {
2550
+ method: "POST",
2551
+ body: { fileIds, ...expiresInSeconds === void 0 ? {} : { expiresInSeconds } }
2552
+ }),
2553
+ "File read URLs response",
2554
+ errors
2555
+ );
2556
+ },
2557
+ async download(fileId, { signal } = {}) {
2558
+ const fetch = storageFetch();
2559
+ if (signal?.aborted) throw abortReason(signal);
2560
+ const { url } = await getUrl(fileId);
2561
+ return fetchContent(fetch, fileId, url, signal);
2562
+ },
2563
+ async get(fileId) {
2564
+ return expectFileMetadata(
2565
+ await transport.request(path(fileId), { method: "GET" }),
2566
+ "File response",
2567
+ errors
2568
+ );
2569
+ },
2570
+ delete: deleteFile
2571
+ };
2572
+ }
2573
+ function uploadInput(content, options, errors) {
2574
+ const name = options.name ?? fileNameOf(content);
2575
+ if (!name) configurationError("name is required when the content is not a named File", errors);
2576
+ const contentType = options.contentType || content.type || UNTYPED_CONTENT;
2577
+ return {
2578
+ name,
2579
+ contentType,
2580
+ sizeBytes: content.size,
2581
+ kind: options.kind,
2582
+ visibility: options.visibility,
2583
+ ...options.appOwned === void 0 ? {} : { appOwned: options.appOwned }
2584
+ };
2585
+ }
2586
+ function fileNameOf(content) {
2587
+ const name = content.name;
2588
+ return typeof name === "string" ? name : void 0;
2589
+ }
2590
+ async function putContent(fetch, upload, content, signal) {
2591
+ try {
2592
+ const response = await fetch(upload.uploadUrl, {
2593
+ method: upload.uploadMethod,
2594
+ headers: upload.uploadHeaders,
2595
+ body: content,
2596
+ redirect: "error",
2597
+ ...signal === void 0 ? {} : { signal }
2598
+ });
2599
+ discardBody(response);
2600
+ if (response.ok) return null;
2601
+ return {
2602
+ reason: `storage answered ${response.status}`,
2603
+ status: response.status,
2604
+ aborted: false
2605
+ };
2606
+ } catch (error) {
2607
+ return {
2608
+ reason: "the transfer to storage failed",
2609
+ status: null,
2610
+ aborted: signal?.aborted === true,
2611
+ error
2612
+ };
2613
+ }
2614
+ }
2615
+ async function fetchContent(fetch, fileId, url, signal) {
2616
+ let response;
2617
+ try {
2618
+ response = await fetch(url, {
2619
+ method: "GET",
2620
+ redirect: "error",
2621
+ ...signal === void 0 ? {} : { signal }
2622
+ });
2623
+ if (response.ok) return await response.blob();
2624
+ } catch (error) {
2625
+ if (signal?.aborted) throw abortReason(signal);
2626
+ throw new FileTransferError(
2627
+ `File ${fileId} was not downloaded: the transfer from storage failed`,
2628
+ { fileId, step: "download", cause: storageCause(error, url) }
2629
+ );
2630
+ }
2631
+ discardBody(response);
2632
+ throw new FileTransferError(
2633
+ `File ${fileId} was not downloaded: storage answered ${response.status}`,
2634
+ { fileId, step: "download", status: response.status }
2635
+ );
2636
+ }
2637
+ function storageCause(thrown, link) {
2638
+ const secrets = linkSecrets(link);
2639
+ const redact = (text) => secrets.reduce((result, secret) => result.replaceAll(secret, REDACTED), text);
2640
+ const rebuild = (value, depth) => {
2641
+ if (!(value instanceof Error)) {
2642
+ const opaque = typeof value === "function" || typeof value === "object" && value !== null;
2643
+ return new Error(opaque ? UNREADABLE_STORAGE_ERROR : redact(String(value)));
2644
+ }
2645
+ const below = depth < MAX_CAUSE_DEPTH && value.cause != null ? rebuild(value.cause, depth + 1) : void 0;
2646
+ const error = new Error(
2647
+ redact(String(value.message)),
2648
+ below === void 0 ? void 0 : { cause: below }
2649
+ );
2650
+ error.name = redact(String(value.name));
2651
+ if (typeof value.stack === "string") error.stack = redact(value.stack);
2652
+ const { code } = value;
2653
+ return typeof code === "string" ? Object.assign(error, { code: redact(code) }) : error;
2654
+ };
2655
+ try {
2656
+ return rebuild(thrown, 1);
2657
+ } catch {
2658
+ return new Error(UNREADABLE_STORAGE_ERROR);
2659
+ }
2660
+ }
2661
+ function linkSecrets(link) {
2662
+ const start = link.indexOf("?");
2663
+ const query = start < 0 ? "" : link.slice(start + 1);
2664
+ const raw = query.split("&").map((pair) => pair.slice(pair.indexOf("=") + 1));
2665
+ const decoded = [...new URLSearchParams(query).values()];
2666
+ const values = [...raw, ...decoded].filter((value) => value.length >= MIN_SECRET_LENGTH);
2667
+ return [link, query, ...values].filter((secret) => secret.length > 0);
2668
+ }
2669
+ function discardBody(response) {
2670
+ void Promise.resolve().then(() => response.body?.cancel()).catch(() => void 0);
2671
+ }
2672
+ function abortReason(signal) {
2673
+ return signal.reason ?? new DOMException("This operation was aborted", "AbortError");
2674
+ }
2675
+ function messageOf(error) {
2676
+ return error instanceof Error ? error.message : String(error);
2677
+ }
2678
+
2301
2679
  // src/modules/functions.ts
2302
2680
  var DefaultFunctionsModule = class {
2303
2681
  constructor(transport, errors, options) {
@@ -3307,6 +3685,7 @@ function createSdkCore(options) {
3307
3685
  customQueries: createCustomQueriesModule(options.transports.dataManager, errors),
3308
3686
  dataSources: createDataSourcesModule(options.transports.dataManager, errors),
3309
3687
  entities: createEntitiesModule(options.transports.dataManager, errors),
3688
+ files: createFilesModule(options.transports.dataManager, options.files, errors),
3310
3689
  functions: createFunctionsModule(options.transports.functions, options.functions, errors),
3311
3690
  functionsAdmin,
3312
3691
  imports: createImportsModule(options.transports.dataManager, errors),
@@ -3334,10 +3713,13 @@ function unavailableTransport(name, errors) {
3334
3713
  // src/agentTurnError.ts
3335
3714
  var AgentTaskTurnError = class extends Error {
3336
3715
  code;
3337
- constructor(message, code) {
3716
+ /** The compactions of a turn the box closed with an error; empty when it reported none. */
3717
+ compactions;
3718
+ constructor(message, code, compactions = []) {
3338
3719
  super(message);
3339
3720
  this.name = "AgentTaskTurnError";
3340
3721
  this.code = code;
3722
+ this.compactions = compactions;
3341
3723
  }
3342
3724
  };
3343
3725
 
@@ -4489,6 +4871,7 @@ var CoreAgentTaskSession = class {
4489
4871
  recoveryGeneration = 0;
4490
4872
  recoveredTerminalReason;
4491
4873
  recoveredTerminalUsage;
4874
+ recoveredTerminalCompactions;
4492
4875
  // Polls that found no closing row although a terminal with usage was heard.
4493
4876
  endedPollsWithoutRow = 0;
4494
4877
  // The turn ids the running turn went by, and the highest box sequence seen in it. The Copilot
@@ -4605,7 +4988,7 @@ var CoreAgentTaskSession = class {
4605
4988
  const error = new AgentTaskTurnError(
4606
4989
  "Agent turn cancellation was not acknowledged before the safety timeout."
4607
4990
  );
4608
- this.emit("error", { error: error.message });
4991
+ this.emit("error", { error: error.message, compactions: [] });
4609
4992
  this.failTurn(error);
4610
4993
  }
4611
4994
  }, CANCEL_SAFETY_MS);
@@ -4912,6 +5295,7 @@ var CoreAgentTaskSession = class {
4912
5295
  this.recoveryUsed = false;
4913
5296
  this.recoveredTerminalReason = void 0;
4914
5297
  this.recoveredTerminalUsage = void 0;
5298
+ this.recoveredTerminalCompactions = void 0;
4915
5299
  this.recoveryGeneration += 1;
4916
5300
  this.activeWaiter = waiter;
4917
5301
  this.setStatus("streaming");
@@ -5089,6 +5473,7 @@ var CoreAgentTaskSession = class {
5089
5473
  this.recoveryUsed = false;
5090
5474
  this.recoveredTerminalReason = void 0;
5091
5475
  this.recoveredTerminalUsage = void 0;
5476
+ this.recoveredTerminalCompactions = void 0;
5092
5477
  this.recoveryGeneration += 1;
5093
5478
  this.turnBaselineIds = new Set(this._history.map((item) => item.id));
5094
5479
  void this.captureTurnBaseline().catch(() => void 0);
@@ -5223,19 +5608,28 @@ var CoreAgentTaskSession = class {
5223
5608
  );
5224
5609
  if (!newest) return false;
5225
5610
  this._content = newest.content;
5226
- this.finishTurn(reason, this.recoveredTerminalUsage);
5611
+ this.finishTurn(reason, this.recoveredTerminalUsage, this.recoveredTerminalEnd());
5227
5612
  return true;
5228
5613
  }
5229
5614
  if (recovered.type === "ERROR") {
5230
5615
  const error = new AgentTaskTurnError(recovered.content);
5231
- this.emit("error", { error: error.message });
5616
+ this.emit("error", { error: error.message, compactions: [] });
5232
5617
  this.failTurn(error);
5233
5618
  return true;
5234
5619
  }
5235
5620
  this._content = recovered.content;
5236
- this.finishTurn(reason, recovered.usage ?? this.recoveredTerminalUsage);
5621
+ this.finishTurn(
5622
+ reason,
5623
+ recovered.usage ?? this.recoveredTerminalUsage,
5624
+ this.recoveredTerminalEnd()
5625
+ );
5237
5626
  return true;
5238
5627
  }
5628
+ // The history rows carry no compactions: only a terminal heard live has the turn's list.
5629
+ recoveredTerminalEnd() {
5630
+ const compactions = this.recoveredTerminalCompactions;
5631
+ return compactions ? { compactions } : {};
5632
+ }
5239
5633
  closesThisTurn(message) {
5240
5634
  if (!message.usage) return false;
5241
5635
  const prompt = message.usage.requestMessageId;
@@ -5396,9 +5790,11 @@ var CoreAgentTaskSession = class {
5396
5790
  const finished = typeof lifecycle2?.turnId === "string" ? lifecycle2.turnId : void 0;
5397
5791
  if (finished !== void 0 && this.finishedTurnIds.includes(finished)) break;
5398
5792
  if (finished === void 0 && lifecycle2 && this.turnIds.size > 0) break;
5793
+ const compactions = agentTurnCompactionsOf(payload?.compactions);
5399
5794
  const end = {
5400
5795
  ...sequenceOf(event),
5401
- ...finished === void 0 ? {} : { turnId: finished }
5796
+ ...finished === void 0 ? {} : { turnId: finished },
5797
+ compactions
5402
5798
  };
5403
5799
  if (reason === "interrupted" || lifecycle2?.interruptTerminal === true) {
5404
5800
  this.rememberFinishedTurn(lifecycle2);
@@ -5410,6 +5806,7 @@ var CoreAgentTaskSession = class {
5410
5806
  if (this.recoveryUsed) {
5411
5807
  this.recoveredTerminalReason = reason;
5412
5808
  this.recoveredTerminalUsage = usage;
5809
+ this.recoveredTerminalCompactions = compactions;
5413
5810
  if (!this.recoveryPromise) {
5414
5811
  const generation = this.recoveryGeneration;
5415
5812
  this.recoveryPromise = this.recoverTurn(generation).finally(() => {
@@ -5425,24 +5822,20 @@ var CoreAgentTaskSession = class {
5425
5822
  case "error": {
5426
5823
  const code = typeof payload?.code === "string" ? payload.code : void 0;
5427
5824
  const message = typeof payload?.message === "string" ? payload.message : "Agent returned an error.";
5428
- this.emit("error", { ...code ? { code } : {}, error: message, ...sequenceOf(event) });
5429
- if (!payload?.lifecycle && payload?.requestId !== void 0) break;
5430
- if (typeof payload?.command === "string") break;
5431
- const refused = payload?.lifecycle ? void 0 : payload?.clientMessageId;
5432
- if (typeof refused === "string") {
5433
- if (refused !== this.openingMessageId) {
5434
- const steered = [...this.steers, ...this.strayedSteers].find(
5435
- (pending) => pending.clientMessageId === refused
5436
- );
5437
- if (steered) steered.refusal = new AgentTaskTurnError(message, code);
5438
- break;
5439
- }
5440
- } else if (!payload?.lifecycle && !this.dispatching && this.pendingSteers > 0) break;
5441
- if (this._status === "streaming" || this._status === "cancelled") {
5442
- this.failTurn(new AgentTaskTurnError(message, code));
5443
- }
5825
+ const compactions = agentTurnCompactionsOf(payload?.compactions);
5826
+ const endsTurn = this.boxErrorEndsTurn(payload, message, code);
5827
+ this.emit("error", {
5828
+ ...code ? { code } : {},
5829
+ error: message,
5830
+ ...sequenceOf(event),
5831
+ ...endsTurn ? { compactions } : {}
5832
+ });
5833
+ if (endsTurn) this.failTurn(new AgentTaskTurnError(message, code, compactions));
5444
5834
  break;
5445
5835
  }
5836
+ case "contextCompacted":
5837
+ if (!this.isFinishedTurnFrame(lifecycle)) this.emitCompaction(event, payload);
5838
+ break;
5446
5839
  case "approval":
5447
5840
  case "user_input_request":
5448
5841
  this.liveRequest(event, payload);
@@ -5586,6 +5979,22 @@ var CoreAgentTaskSession = class {
5586
5979
  this.turnIds.add(turnId);
5587
5980
  return false;
5588
5981
  }
5982
+ // A refused steer is handed its refusal here, for the send that waits on it.
5983
+ boxErrorEndsTurn(payload, message, code) {
5984
+ if (!payload?.lifecycle && payload?.requestId !== void 0) return false;
5985
+ if (typeof payload?.command === "string") return false;
5986
+ const refused = payload?.lifecycle ? void 0 : payload?.clientMessageId;
5987
+ if (typeof refused === "string") {
5988
+ if (refused !== this.openingMessageId) {
5989
+ const steered = [...this.steers, ...this.strayedSteers].find(
5990
+ (pending) => pending.clientMessageId === refused
5991
+ );
5992
+ if (steered) steered.refusal = new AgentTaskTurnError(message, code);
5993
+ return false;
5994
+ }
5995
+ } else if (!payload?.lifecycle && !this.dispatching && this.pendingSteers > 0) return false;
5996
+ return this._status === "streaming" || this._status === "cancelled";
5997
+ }
5589
5998
  isFinishedTurnFrame(lifecycle) {
5590
5999
  const turnId = lifecycle?.turnId;
5591
6000
  return typeof turnId === "string" && this.finishedTurnIds.includes(turnId);
@@ -5813,10 +6222,22 @@ var CoreAgentTaskSession = class {
5813
6222
  case "user_input_request":
5814
6223
  this.liveRequest(event, payload, parentToolId);
5815
6224
  break;
6225
+ case "contextCompacted":
6226
+ this.emitCompaction(event, payload, parentToolId);
6227
+ break;
5816
6228
  default:
5817
6229
  break;
5818
6230
  }
5819
6231
  }
6232
+ emitCompaction(event, payload, parentToolId) {
6233
+ const compaction = agentTurnCompactionOf(payload);
6234
+ if (!compaction) return;
6235
+ this.emit("contextCompacted", {
6236
+ ...compaction,
6237
+ ...pieceIdentityOf(event, payload),
6238
+ ...parentToolIdOf(parentToolId)
6239
+ });
6240
+ }
5820
6241
  applySubagent(event, payload) {
5821
6242
  const subagentId = payload?.subagentId;
5822
6243
  const toolId = payload?.toolId;
@@ -5880,7 +6301,8 @@ var CoreAgentTaskSession = class {
5880
6301
  content: this._content,
5881
6302
  reason,
5882
6303
  ...usage ? { usage } : {},
5883
- ...end
6304
+ ...end,
6305
+ compactions: end.compactions ?? []
5884
6306
  };
5885
6307
  this.emit("turnEnd", result);
5886
6308
  this.activeWaiter?.resolve(result);
@@ -6000,6 +6422,13 @@ var CoreAgentTaskSession = class {
6000
6422
  }
6001
6423
  };
6002
6424
 
6425
+ // src/agentTurnEvent.ts
6426
+ function isAgentTurnEvent(value) {
6427
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
6428
+ const event = value;
6429
+ return (event.type === "STARTED" || event.type === "ENDED") && typeof event.eventId === "string" && typeof event.taskId === "string" && typeof event.turnId === "string" && typeof event.occurredAt === "string";
6430
+ }
6431
+
6003
6432
  // src/apiKeySession.ts
6004
6433
  var API_KEY_EXCHANGE_PATH = "/api/v1/auth/exchange";
6005
6434
  function appAccessTokenPath(appId) {
@@ -6069,6 +6498,7 @@ async function resolveApiKeyToken(call, appId, apiKey, errors = defaultSdkCoreEr
6069
6498
  export {
6070
6499
  API_KEY_EXCHANGE_PATH,
6071
6500
  AgentTaskTurnError,
6501
+ FileTransferError,
6072
6502
  SdkCoreConfigurationError,
6073
6503
  SdkCoreResponseError,
6074
6504
  appAccessTokenPath,
@@ -6084,6 +6514,7 @@ export {
6084
6514
  createCustomQueriesModule,
6085
6515
  createDataSourcesModule,
6086
6516
  createEntitiesModule,
6517
+ createFilesModule,
6087
6518
  createFunctionsAdminModule,
6088
6519
  createFunctionsModule,
6089
6520
  createImportsModule,
@@ -6108,6 +6539,7 @@ export {
6108
6539
  expectObjectArray,
6109
6540
  expectPage,
6110
6541
  expectStringArray,
6542
+ isAgentTurnEvent,
6111
6543
  isWorkspaceSession,
6112
6544
  readTokenAppId,
6113
6545
  readTokenExpiry,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mitralab.io/sdk-core",
3
- "version": "0.3.9",
3
+ "version": "0.3.11",
4
4
  "description": "Environment-neutral contracts and modules shared by Mitra JavaScript SDKs",
5
5
  "type": "module",
6
6
  "sideEffects": false,