@mitralab.io/sdk-core 0.3.10 → 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.cjs CHANGED
@@ -63,6 +63,7 @@ __export(index_exports, {
63
63
  expectObjectArray: () => expectObjectArray,
64
64
  expectPage: () => expectPage,
65
65
  expectStringArray: () => expectStringArray,
66
+ isAgentTurnEvent: () => isAgentTurnEvent,
66
67
  isWorkspaceSession: () => isWorkspaceSession,
67
68
  readTokenAppId: () => readTokenAppId,
68
69
  readTokenExpiry: () => readTokenExpiry,
@@ -1055,7 +1056,40 @@ function expectAgentTask(value, context, errors = defaultSdkCoreErrorFactory) {
1055
1056
  if (typeof task.archived !== "boolean") invalidField(context, "archived", errors);
1056
1057
  if (!isNullableString(task.createdAt)) invalidField(context, "createdAt", errors);
1057
1058
  if (typeof task.updatedAt !== "string") invalidField(context, "updatedAt", errors);
1058
- return task;
1059
+ const { turn: rawTurn, instructions: rawInstructions, folderKey: rawFolderKey, ...rest } = task;
1060
+ const turn = rawTurn === null ? null : agentTaskTurnOf(rawTurn);
1061
+ const instructions = typeof rawInstructions === "string" ? rawInstructions : void 0;
1062
+ const folderKey = typeof rawFolderKey === "string" ? rawFolderKey : void 0;
1063
+ return {
1064
+ ...rest,
1065
+ ...turn !== void 0 ? { turn } : {},
1066
+ ...instructions !== void 0 ? { instructions } : {},
1067
+ ...folderKey !== void 0 ? { folderKey } : {}
1068
+ };
1069
+ }
1070
+ function agentTaskTurnOf(value) {
1071
+ if (!isObject(value)) return void 0;
1072
+ if (typeof value.state !== "string") return void 0;
1073
+ if (!isNullableString(value.currentTurnId) || !isCount(value.queuedCount)) return void 0;
1074
+ if (value.lastTurn === null) return value;
1075
+ const lastTurn = value.lastTurn;
1076
+ if (!isObject(lastTurn)) return void 0;
1077
+ if (typeof lastTurn.turnId !== "string" || typeof lastTurn.status !== "string") return void 0;
1078
+ if (!isStringArray(lastTurn.messageIds)) return void 0;
1079
+ const nullableTexts = ["finishReason", "errorCode", "startedAt", "endedAt"];
1080
+ if (!nullableTexts.every((field) => isNullableString(lastTurn[field]))) return void 0;
1081
+ return value;
1082
+ }
1083
+ function expectAgentTaskTurnStates(value, context, errors = defaultSdkCoreErrorFactory) {
1084
+ return expectObjectArray(value, context, errors).map((state, position) => {
1085
+ if (typeof state.taskId !== "string") {
1086
+ invalidField(`${context} item ${position}`, "taskId", errors);
1087
+ }
1088
+ return {
1089
+ ...state,
1090
+ turn: agentTaskTurnOf(state.turn) ?? null
1091
+ };
1092
+ });
1059
1093
  }
1060
1094
  function expectAgentTaskChannel(value, context, errors = defaultSdkCoreErrorFactory) {
1061
1095
  if (value === void 0 || value === null || value === "") return null;
@@ -1129,6 +1163,22 @@ function agentTurnUsageOf(value) {
1129
1163
  }
1130
1164
  return usage;
1131
1165
  }
1166
+ function agentTurnCompactionsOf(value) {
1167
+ if (!Array.isArray(value)) return [];
1168
+ return value.flatMap((item) => {
1169
+ const compaction = agentTurnCompactionOf(item);
1170
+ return compaction ? [compaction] : [];
1171
+ });
1172
+ }
1173
+ function agentTurnCompactionOf(value) {
1174
+ if (!isObject(value) || typeof value.trigger !== "string") return void 0;
1175
+ return {
1176
+ trigger: value.trigger,
1177
+ tokensBefore: isCount(value.tokensBefore) ? value.tokensBefore : null,
1178
+ tokensAfter: isCount(value.tokensAfter) ? value.tokensAfter : null,
1179
+ at: typeof value.at === "string" ? value.at : null
1180
+ };
1181
+ }
1132
1182
  function agentTurnUsageRequestOf(value) {
1133
1183
  if (!isObject(value)) return void 0;
1134
1184
  const request = {};
@@ -1767,6 +1817,8 @@ function createAgentsModule(functionsTransport, copilotTransport, errors = defau
1767
1817
  }
1768
1818
 
1769
1819
  // src/modules/agentTasks.ts
1820
+ var TURN_STATES_BATCH_SIZE = 100;
1821
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
1770
1822
  function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory) {
1771
1823
  const path = (id) => `/api/v1/tasks/${encodePathSegment(id, "task id", errors)}`;
1772
1824
  return {
@@ -1780,12 +1832,18 @@ function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory)
1780
1832
  search: options.search,
1781
1833
  userId: options.userId
1782
1834
  };
1783
- return expectPage(
1835
+ const context = "Agent task page response";
1836
+ const page = expectPage(
1784
1837
  await transport.request("/api/v1/tasks", { method: "GET", params }),
1785
- "Agent task page response",
1786
- errors,
1787
- expectAgentTask
1838
+ context,
1839
+ errors
1788
1840
  );
1841
+ return {
1842
+ ...page,
1843
+ content: page.content.map(
1844
+ (task, position) => expectAgentTask(task, `${context} item ${position}`, errors)
1845
+ )
1846
+ };
1789
1847
  },
1790
1848
  async get(id) {
1791
1849
  return expectAgentTask(
@@ -1808,6 +1866,16 @@ function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory)
1808
1866
  errors
1809
1867
  );
1810
1868
  },
1869
+ async setInstructions(id, instructions) {
1870
+ return expectAgentTask(
1871
+ await transport.request(`${path(id)}/instructions`, {
1872
+ method: "PUT",
1873
+ body: { instructions }
1874
+ }),
1875
+ "Agent task instructions response",
1876
+ errors
1877
+ );
1878
+ },
1811
1879
  async archive(id) {
1812
1880
  expectEmpty(
1813
1881
  await transport.request(`${path(id)}/archive`, { method: "PATCH" }),
@@ -1852,6 +1920,26 @@ function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory)
1852
1920
  "Agent task channel response",
1853
1921
  errors
1854
1922
  );
1923
+ },
1924
+ async turnStates(ids) {
1925
+ const unique = [...new Set(ids.map((id) => id.toLowerCase()))].filter((id) => UUID.test(id));
1926
+ const states = [];
1927
+ for (let start = 0; start < unique.length; start += TURN_STATES_BATCH_SIZE) {
1928
+ const taskIds = unique.slice(start, start + TURN_STATES_BATCH_SIZE);
1929
+ states.push(
1930
+ ...expectAgentTaskTurnStates(
1931
+ await transport.request("/api/v1/tasks/turn-states", {
1932
+ method: "GET",
1933
+ // Joined here because a transport may send an array as repeated keys; the Copilot
1934
+ // reads one comma-separated value.
1935
+ params: { taskIds: taskIds.join(",") }
1936
+ }),
1937
+ "Agent task turn states response",
1938
+ errors
1939
+ )
1940
+ );
1941
+ }
1942
+ return states;
1855
1943
  }
1856
1944
  };
1857
1945
  }
@@ -3701,10 +3789,13 @@ function unavailableTransport(name, errors) {
3701
3789
  // src/agentTurnError.ts
3702
3790
  var AgentTaskTurnError = class extends Error {
3703
3791
  code;
3704
- constructor(message, code) {
3792
+ /** The compactions of a turn the box closed with an error; empty when it reported none. */
3793
+ compactions;
3794
+ constructor(message, code, compactions = []) {
3705
3795
  super(message);
3706
3796
  this.name = "AgentTaskTurnError";
3707
3797
  this.code = code;
3798
+ this.compactions = compactions;
3708
3799
  }
3709
3800
  };
3710
3801
 
@@ -4856,6 +4947,7 @@ var CoreAgentTaskSession = class {
4856
4947
  recoveryGeneration = 0;
4857
4948
  recoveredTerminalReason;
4858
4949
  recoveredTerminalUsage;
4950
+ recoveredTerminalCompactions;
4859
4951
  // Polls that found no closing row although a terminal with usage was heard.
4860
4952
  endedPollsWithoutRow = 0;
4861
4953
  // The turn ids the running turn went by, and the highest box sequence seen in it. The Copilot
@@ -4972,7 +5064,7 @@ var CoreAgentTaskSession = class {
4972
5064
  const error = new AgentTaskTurnError(
4973
5065
  "Agent turn cancellation was not acknowledged before the safety timeout."
4974
5066
  );
4975
- this.emit("error", { error: error.message });
5067
+ this.emit("error", { error: error.message, compactions: [] });
4976
5068
  this.failTurn(error);
4977
5069
  }
4978
5070
  }, CANCEL_SAFETY_MS);
@@ -5279,6 +5371,7 @@ var CoreAgentTaskSession = class {
5279
5371
  this.recoveryUsed = false;
5280
5372
  this.recoveredTerminalReason = void 0;
5281
5373
  this.recoveredTerminalUsage = void 0;
5374
+ this.recoveredTerminalCompactions = void 0;
5282
5375
  this.recoveryGeneration += 1;
5283
5376
  this.activeWaiter = waiter;
5284
5377
  this.setStatus("streaming");
@@ -5456,6 +5549,7 @@ var CoreAgentTaskSession = class {
5456
5549
  this.recoveryUsed = false;
5457
5550
  this.recoveredTerminalReason = void 0;
5458
5551
  this.recoveredTerminalUsage = void 0;
5552
+ this.recoveredTerminalCompactions = void 0;
5459
5553
  this.recoveryGeneration += 1;
5460
5554
  this.turnBaselineIds = new Set(this._history.map((item) => item.id));
5461
5555
  void this.captureTurnBaseline().catch(() => void 0);
@@ -5590,19 +5684,28 @@ var CoreAgentTaskSession = class {
5590
5684
  );
5591
5685
  if (!newest) return false;
5592
5686
  this._content = newest.content;
5593
- this.finishTurn(reason, this.recoveredTerminalUsage);
5687
+ this.finishTurn(reason, this.recoveredTerminalUsage, this.recoveredTerminalEnd());
5594
5688
  return true;
5595
5689
  }
5596
5690
  if (recovered.type === "ERROR") {
5597
5691
  const error = new AgentTaskTurnError(recovered.content);
5598
- this.emit("error", { error: error.message });
5692
+ this.emit("error", { error: error.message, compactions: [] });
5599
5693
  this.failTurn(error);
5600
5694
  return true;
5601
5695
  }
5602
5696
  this._content = recovered.content;
5603
- this.finishTurn(reason, recovered.usage ?? this.recoveredTerminalUsage);
5697
+ this.finishTurn(
5698
+ reason,
5699
+ recovered.usage ?? this.recoveredTerminalUsage,
5700
+ this.recoveredTerminalEnd()
5701
+ );
5604
5702
  return true;
5605
5703
  }
5704
+ // The history rows carry no compactions: only a terminal heard live has the turn's list.
5705
+ recoveredTerminalEnd() {
5706
+ const compactions = this.recoveredTerminalCompactions;
5707
+ return compactions ? { compactions } : {};
5708
+ }
5606
5709
  closesThisTurn(message) {
5607
5710
  if (!message.usage) return false;
5608
5711
  const prompt = message.usage.requestMessageId;
@@ -5763,9 +5866,11 @@ var CoreAgentTaskSession = class {
5763
5866
  const finished = typeof lifecycle2?.turnId === "string" ? lifecycle2.turnId : void 0;
5764
5867
  if (finished !== void 0 && this.finishedTurnIds.includes(finished)) break;
5765
5868
  if (finished === void 0 && lifecycle2 && this.turnIds.size > 0) break;
5869
+ const compactions = agentTurnCompactionsOf(payload?.compactions);
5766
5870
  const end = {
5767
5871
  ...sequenceOf(event),
5768
- ...finished === void 0 ? {} : { turnId: finished }
5872
+ ...finished === void 0 ? {} : { turnId: finished },
5873
+ compactions
5769
5874
  };
5770
5875
  if (reason === "interrupted" || lifecycle2?.interruptTerminal === true) {
5771
5876
  this.rememberFinishedTurn(lifecycle2);
@@ -5777,6 +5882,7 @@ var CoreAgentTaskSession = class {
5777
5882
  if (this.recoveryUsed) {
5778
5883
  this.recoveredTerminalReason = reason;
5779
5884
  this.recoveredTerminalUsage = usage;
5885
+ this.recoveredTerminalCompactions = compactions;
5780
5886
  if (!this.recoveryPromise) {
5781
5887
  const generation = this.recoveryGeneration;
5782
5888
  this.recoveryPromise = this.recoverTurn(generation).finally(() => {
@@ -5792,24 +5898,20 @@ var CoreAgentTaskSession = class {
5792
5898
  case "error": {
5793
5899
  const code = typeof payload?.code === "string" ? payload.code : void 0;
5794
5900
  const message = typeof payload?.message === "string" ? payload.message : "Agent returned an error.";
5795
- this.emit("error", { ...code ? { code } : {}, error: message, ...sequenceOf(event) });
5796
- if (!payload?.lifecycle && payload?.requestId !== void 0) break;
5797
- if (typeof payload?.command === "string") break;
5798
- const refused = payload?.lifecycle ? void 0 : payload?.clientMessageId;
5799
- if (typeof refused === "string") {
5800
- if (refused !== this.openingMessageId) {
5801
- const steered = [...this.steers, ...this.strayedSteers].find(
5802
- (pending) => pending.clientMessageId === refused
5803
- );
5804
- if (steered) steered.refusal = new AgentTaskTurnError(message, code);
5805
- break;
5806
- }
5807
- } else if (!payload?.lifecycle && !this.dispatching && this.pendingSteers > 0) break;
5808
- if (this._status === "streaming" || this._status === "cancelled") {
5809
- this.failTurn(new AgentTaskTurnError(message, code));
5810
- }
5901
+ const compactions = agentTurnCompactionsOf(payload?.compactions);
5902
+ const endsTurn = this.boxErrorEndsTurn(payload, message, code);
5903
+ this.emit("error", {
5904
+ ...code ? { code } : {},
5905
+ error: message,
5906
+ ...sequenceOf(event),
5907
+ ...endsTurn ? { compactions } : {}
5908
+ });
5909
+ if (endsTurn) this.failTurn(new AgentTaskTurnError(message, code, compactions));
5811
5910
  break;
5812
5911
  }
5912
+ case "contextCompacted":
5913
+ if (!this.isFinishedTurnFrame(lifecycle)) this.emitCompaction(event, payload);
5914
+ break;
5813
5915
  case "approval":
5814
5916
  case "user_input_request":
5815
5917
  this.liveRequest(event, payload);
@@ -5953,6 +6055,22 @@ var CoreAgentTaskSession = class {
5953
6055
  this.turnIds.add(turnId);
5954
6056
  return false;
5955
6057
  }
6058
+ // A refused steer is handed its refusal here, for the send that waits on it.
6059
+ boxErrorEndsTurn(payload, message, code) {
6060
+ if (!payload?.lifecycle && payload?.requestId !== void 0) return false;
6061
+ if (typeof payload?.command === "string") return false;
6062
+ const refused = payload?.lifecycle ? void 0 : payload?.clientMessageId;
6063
+ if (typeof refused === "string") {
6064
+ if (refused !== this.openingMessageId) {
6065
+ const steered = [...this.steers, ...this.strayedSteers].find(
6066
+ (pending) => pending.clientMessageId === refused
6067
+ );
6068
+ if (steered) steered.refusal = new AgentTaskTurnError(message, code);
6069
+ return false;
6070
+ }
6071
+ } else if (!payload?.lifecycle && !this.dispatching && this.pendingSteers > 0) return false;
6072
+ return this._status === "streaming" || this._status === "cancelled";
6073
+ }
5956
6074
  isFinishedTurnFrame(lifecycle) {
5957
6075
  const turnId = lifecycle?.turnId;
5958
6076
  return typeof turnId === "string" && this.finishedTurnIds.includes(turnId);
@@ -6180,10 +6298,22 @@ var CoreAgentTaskSession = class {
6180
6298
  case "user_input_request":
6181
6299
  this.liveRequest(event, payload, parentToolId);
6182
6300
  break;
6301
+ case "contextCompacted":
6302
+ this.emitCompaction(event, payload, parentToolId);
6303
+ break;
6183
6304
  default:
6184
6305
  break;
6185
6306
  }
6186
6307
  }
6308
+ emitCompaction(event, payload, parentToolId) {
6309
+ const compaction = agentTurnCompactionOf(payload);
6310
+ if (!compaction) return;
6311
+ this.emit("contextCompacted", {
6312
+ ...compaction,
6313
+ ...pieceIdentityOf(event, payload),
6314
+ ...parentToolIdOf(parentToolId)
6315
+ });
6316
+ }
6187
6317
  applySubagent(event, payload) {
6188
6318
  const subagentId = payload?.subagentId;
6189
6319
  const toolId = payload?.toolId;
@@ -6247,7 +6377,8 @@ var CoreAgentTaskSession = class {
6247
6377
  content: this._content,
6248
6378
  reason,
6249
6379
  ...usage ? { usage } : {},
6250
- ...end
6380
+ ...end,
6381
+ compactions: end.compactions ?? []
6251
6382
  };
6252
6383
  this.emit("turnEnd", result);
6253
6384
  this.activeWaiter?.resolve(result);
@@ -6367,6 +6498,13 @@ var CoreAgentTaskSession = class {
6367
6498
  }
6368
6499
  };
6369
6500
 
6501
+ // src/agentTurnEvent.ts
6502
+ function isAgentTurnEvent(value) {
6503
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
6504
+ const event = value;
6505
+ return (event.type === "STARTED" || event.type === "ENDED") && typeof event.eventId === "string" && typeof event.taskId === "string" && typeof event.turnId === "string" && typeof event.occurredAt === "string";
6506
+ }
6507
+
6370
6508
  // src/apiKeySession.ts
6371
6509
  var API_KEY_EXCHANGE_PATH = "/api/v1/auth/exchange";
6372
6510
  function appAccessTokenPath(appId) {
@@ -6478,6 +6616,7 @@ async function resolveApiKeyToken(call, appId, apiKey, errors = defaultSdkCoreEr
6478
6616
  expectObjectArray,
6479
6617
  expectPage,
6480
6618
  expectStringArray,
6619
+ isAgentTurnEvent,
6481
6620
  isWorkspaceSession,
6482
6621
  readTokenAppId,
6483
6622
  readTokenExpiry,