@mitralab.io/sdk-core 0.3.10 → 0.3.12

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" }),
@@ -1833,7 +1901,9 @@ function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory)
1833
1901
  sort: options.sort,
1834
1902
  kinds: options.kinds,
1835
1903
  include: options.include,
1836
- before: options.before
1904
+ before: options.before,
1905
+ thread: options.thread,
1906
+ parentToolId: options.parentToolId
1837
1907
  }
1838
1908
  }),
1839
1909
  context,
@@ -1852,6 +1922,26 @@ function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory)
1852
1922
  "Agent task channel response",
1853
1923
  errors
1854
1924
  );
1925
+ },
1926
+ async turnStates(ids) {
1927
+ const unique = [...new Set(ids.map((id) => id.toLowerCase()))].filter((id) => UUID.test(id));
1928
+ const states = [];
1929
+ for (let start = 0; start < unique.length; start += TURN_STATES_BATCH_SIZE) {
1930
+ const taskIds = unique.slice(start, start + TURN_STATES_BATCH_SIZE);
1931
+ states.push(
1932
+ ...expectAgentTaskTurnStates(
1933
+ await transport.request("/api/v1/tasks/turn-states", {
1934
+ method: "GET",
1935
+ // Joined here because a transport may send an array as repeated keys; the Copilot
1936
+ // reads one comma-separated value.
1937
+ params: { taskIds: taskIds.join(",") }
1938
+ }),
1939
+ "Agent task turn states response",
1940
+ errors
1941
+ )
1942
+ );
1943
+ }
1944
+ return states;
1855
1945
  }
1856
1946
  };
1857
1947
  }
@@ -3701,10 +3791,13 @@ function unavailableTransport(name, errors) {
3701
3791
  // src/agentTurnError.ts
3702
3792
  var AgentTaskTurnError = class extends Error {
3703
3793
  code;
3704
- constructor(message, code) {
3794
+ /** The compactions of a turn the box closed with an error; empty when it reported none. */
3795
+ compactions;
3796
+ constructor(message, code, compactions = []) {
3705
3797
  super(message);
3706
3798
  this.name = "AgentTaskTurnError";
3707
3799
  this.code = code;
3800
+ this.compactions = compactions;
3708
3801
  }
3709
3802
  };
3710
3803
 
@@ -4524,7 +4617,15 @@ var AgentDirectChannel = class {
4524
4617
 
4525
4618
  // src/agentSession.ts
4526
4619
  var CANCEL_SAFETY_MS = 1e4;
4620
+ var DELIVERY_DELAY_MS = 2e4;
4621
+ var MAX_TURN_START_READS = 10;
4527
4622
  var RECONCILE_DELAY_MS = 1e3;
4623
+ var ROOT_HISTORY = {
4624
+ sort: "createdAt,desc",
4625
+ kinds: "all",
4626
+ include: "plan",
4627
+ thread: "root"
4628
+ };
4528
4629
  var ENDED_POLLS_BEFORE_NEWEST = 3;
4529
4630
  var TURN_TAIL_TYPES = /* @__PURE__ */ new Set([
4530
4631
  "textDelta",
@@ -4696,6 +4797,10 @@ function rowOrHeld(held, row, liveComparable) {
4696
4797
  function hasOlderRows(page) {
4697
4798
  return page.page.totalPages > page.page.number + 1;
4698
4799
  }
4800
+ function pageWithOlder(content, older) {
4801
+ const size = content.length;
4802
+ return { content, page: { size, totalElements: size, totalPages: older ? 2 : 1, number: 0 } };
4803
+ }
4699
4804
  function isChatRow(message) {
4700
4805
  return (message.type === "TEXT" || message.type === "ERROR" || message.type === "TOOL_USE") && message.parentToolId === void 0;
4701
4806
  }
@@ -4788,6 +4893,12 @@ function toAgentTimelineItem(message) {
4788
4893
  ...parentToolIdOf(message.parentToolId)
4789
4894
  };
4790
4895
  }
4896
+ function parentToolIdOfItem(item) {
4897
+ return item.kind === "tool" ? item.tool.parentToolId : item.parentToolId;
4898
+ }
4899
+ function rootItemsOf(messages) {
4900
+ return messages.map(toAgentTimelineItem).filter((item) => parentToolIdOfItem(item) === void 0);
4901
+ }
4791
4902
  function liveAtOf(event) {
4792
4903
  return new Date(typeof event.timestamp === "number" ? event.timestamp : Date.now()).toISOString();
4793
4904
  }
@@ -4801,13 +4912,17 @@ function createAgentTaskSessionManager(options) {
4801
4912
  session(requested) {
4802
4913
  if ("taskId" in requested) {
4803
4914
  const current = sessions.get(requested.taskId);
4804
- if (current && current.status !== "closed") return current;
4915
+ if (current && current.status !== "closed") {
4916
+ if (!requested.reopen || current.status !== "error") return current;
4917
+ current.close();
4918
+ }
4805
4919
  }
4806
4920
  const sessionOptions = "create" in requested && requested.agentId && !requested.runtime && channel.canDial(requested.transport) ? { ...requested, runtime: "T3" } : requested;
4807
4921
  const session = new CoreAgentTaskSession(sessionOptions, {
4808
4922
  tasks: options.tasks,
4809
4923
  eventSource: options.eventSource,
4810
4924
  channel,
4925
+ deliveryDelayMs: options.deliveryDelayMs ?? DELIVERY_DELAY_MS,
4811
4926
  onTaskId: (taskId, value) => sessions.set(taskId, value),
4812
4927
  onClose: (taskId, value) => {
4813
4928
  if (sessions.get(taskId) === value) sessions.delete(taskId);
@@ -4856,6 +4971,7 @@ var CoreAgentTaskSession = class {
4856
4971
  recoveryGeneration = 0;
4857
4972
  recoveredTerminalReason;
4858
4973
  recoveredTerminalUsage;
4974
+ recoveredTerminalCompactions;
4859
4975
  // Polls that found no closing row although a terminal with usage was heard.
4860
4976
  endedPollsWithoutRow = 0;
4861
4977
  // The turn ids the running turn went by, and the highest box sequence seen in it. The Copilot
@@ -4899,6 +5015,9 @@ var CoreAgentTaskSession = class {
4899
5015
  openingCursor;
4900
5016
  historyLimit;
4901
5017
  _hasOlder = false;
5018
+ // The oldest row read so far, kept or not: a page of a Copilot that ignores `thread=root` can
5019
+ // be all subagent rows, and reading before the oldest kept row would read it again (#162).
5020
+ olderCursor;
4902
5021
  // Moves whenever `history` is replaced, so a `loadOlder` still reading drops what it read.
4903
5022
  historyGeneration = 0;
4904
5023
  // Whether the box the channel follows counts in the log of the history's rows. A box whose hello
@@ -4908,6 +5027,8 @@ var CoreAgentTaskSession = class {
4908
5027
  // flag above starts over at each reread, and a page from the old log may come again.
4909
5028
  channelLog;
4910
5029
  olderRead = null;
5030
+ // Messages sent and not at the server yet, by `clientMessageId`, each with its `delivery` clock.
5031
+ deliveries = /* @__PURE__ */ new Map();
4911
5032
  get taskId() {
4912
5033
  return this._taskId;
4913
5034
  }
@@ -4936,7 +5057,7 @@ var CoreAgentTaskSession = class {
4936
5057
  this.requireOpen();
4937
5058
  if (!prompt.trim()) return void 0;
4938
5059
  if (this.isBusy()) return this.steer(prompt, options);
4939
- const clientMessageId = newClientMessageId();
5060
+ const clientMessageId = options.clientMessageId || newClientMessageId();
4940
5061
  this.startDispatch(prompt, options, clientMessageId);
4941
5062
  return clientMessageId;
4942
5063
  }
@@ -4948,13 +5069,19 @@ var CoreAgentTaskSession = class {
4948
5069
  const sendOptions = {
4949
5070
  ...options.agentType ? { agentType: options.agentType } : {},
4950
5071
  ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {},
4951
- ...options.mode ? { mode: options.mode } : {}
5072
+ ...options.mode ? { mode: options.mode } : {},
5073
+ ...options.clientMessageId ? { clientMessageId: options.clientMessageId } : {}
4952
5074
  };
4953
5075
  if (this.isBusy()) {
4954
5076
  this.steer(prompt, sendOptions, waiter);
4955
5077
  return waiter.promise;
4956
5078
  }
4957
- this.startDispatch(prompt, sendOptions, newClientMessageId(), waiter);
5079
+ this.startDispatch(
5080
+ prompt,
5081
+ sendOptions,
5082
+ sendOptions.clientMessageId || newClientMessageId(),
5083
+ waiter
5084
+ );
4958
5085
  return waiter.promise;
4959
5086
  }
4960
5087
  async cancel() {
@@ -4972,7 +5099,7 @@ var CoreAgentTaskSession = class {
4972
5099
  const error = new AgentTaskTurnError(
4973
5100
  "Agent turn cancellation was not acknowledged before the safety timeout."
4974
5101
  );
4975
- this.emit("error", { error: error.message });
5102
+ this.emit("error", { error: error.message, compactions: [] });
4976
5103
  this.failTurn(error);
4977
5104
  }
4978
5105
  }, CANCEL_SAFETY_MS);
@@ -4999,14 +5126,14 @@ var CoreAgentTaskSession = class {
4999
5126
  }
5000
5127
  async loadHistory(options = {}) {
5001
5128
  if (!this._taskId) return [];
5129
+ const generation = this.historyGeneration;
5002
5130
  const page = await this.dependencies.tasks.listMessages(this._taskId, {
5003
5131
  ...options.limit !== void 0 ? { size: options.limit } : {},
5004
- sort: "createdAt,desc",
5005
- kinds: "all",
5006
- include: "plan"
5132
+ ...ROOT_HISTORY
5007
5133
  });
5008
5134
  this.historyLimit = options.limit;
5009
- await this.rereadHistory(page);
5135
+ const whole = this.reachesHistory(page) ? page : await this.backToTurnStart(page, options.limit, generation);
5136
+ if (whole) await this.rereadHistory(whole);
5010
5137
  const history = this.history;
5011
5138
  this.emit("historyLoaded", { history });
5012
5139
  return history;
@@ -5014,34 +5141,25 @@ var CoreAgentTaskSession = class {
5014
5141
  get hasOlder() {
5015
5142
  return this._hasOlder;
5016
5143
  }
5017
- loadOlder() {
5144
+ loadOlder(options = {}) {
5018
5145
  if (this.olderRead?.generation !== this.historyGeneration) {
5019
5146
  const generation = this.historyGeneration;
5020
- const promise = this.readOlder(generation).finally(() => {
5147
+ const size = options.limit ?? this.historyLimit;
5148
+ const promise = this.readOlder(generation, size).finally(() => {
5021
5149
  if (this.olderRead?.promise === promise) this.olderRead = null;
5022
5150
  });
5023
5151
  this.olderRead = { generation, promise };
5024
5152
  }
5025
5153
  return this.olderRead.promise;
5026
5154
  }
5027
- async readOlder(generation) {
5028
- const oldest = oldestRowOf(this._history);
5029
- if (!this._taskId || !this._hasOlder || !oldest) return [];
5030
- let page;
5031
- try {
5032
- page = await this.dependencies.tasks.listMessages(this._taskId, {
5033
- before: oldest.id,
5034
- ...this.historyLimit !== void 0 ? { size: this.historyLimit } : {},
5035
- sort: "createdAt,desc",
5036
- kinds: "all",
5037
- include: "plan"
5038
- });
5039
- } catch (error) {
5040
- if (generation !== this.historyGeneration || this.isClosed()) return [];
5041
- throw error;
5042
- }
5043
- if (generation !== this.historyGeneration || this.isClosed()) return [];
5044
- const rows = [...page.content].reverse().map(toAgentTimelineItem);
5155
+ async readOlder(generation, size) {
5156
+ const before = this.olderCursor ?? oldestRowOf(this._history)?.id;
5157
+ if (!this._taskId || !this._hasOlder || !before) return [];
5158
+ const page = await this.readBefore(before, size, generation);
5159
+ const whole = page && await this.backToTurnStart(page, size, generation);
5160
+ if (!whole) return [];
5161
+ this.olderCursor = whole.content[whole.content.length - 1]?.id ?? before;
5162
+ const rows = rootItemsOf([...whole.content].reverse());
5045
5163
  const rowsLog = [...rows].reverse().find((item) => item.boxLog !== void 0)?.boxLog;
5046
5164
  const liveComparable = this.rowsInChannelLog && (this.channelLog === void 0 || rowsLog === void 0 || rowsLog === this.channelLog);
5047
5165
  const taken = /* @__PURE__ */ new Set();
@@ -5053,11 +5171,73 @@ var CoreAgentTaskSession = class {
5053
5171
  taken.add(held);
5054
5172
  return rowOrHeld(held, row, liveComparable);
5055
5173
  });
5056
- this._hasOlder = hasOlderRows(page);
5174
+ this._hasOlder = hasOlderRows(whole);
5057
5175
  this._history = [...older, ...this._history.filter((item) => !taken.has(item))];
5058
5176
  this.emit("historyLoaded", { history: this.history });
5059
5177
  return older;
5060
5178
  }
5179
+ async loadSubagent(toolId, options = {}) {
5180
+ if (!this._taskId) return { items: [], hasOlder: false };
5181
+ const page = await this.dependencies.tasks.listMessages(this._taskId, {
5182
+ ...options.limit !== void 0 ? { size: options.limit } : {},
5183
+ ...options.before !== void 0 ? { before: options.before } : {},
5184
+ sort: "createdAt,desc",
5185
+ kinds: "all",
5186
+ include: "plan",
5187
+ parentToolId: toolId
5188
+ });
5189
+ const items = [...page.content].reverse().map(toAgentTimelineItem).filter((item) => parentToolIdOfItem(item) === toolId);
5190
+ const oldest = page.content[page.content.length - 1];
5191
+ return {
5192
+ items,
5193
+ hasOlder: hasOlderRows(page),
5194
+ ...oldest === void 0 ? {} : { before: oldest.id }
5195
+ };
5196
+ }
5197
+ // The rows recorded before `before`, or null once `history` was replaced or the session closed:
5198
+ // a read of a history since replaced resolves with nothing, as its success would.
5199
+ async readBefore(before, size, generation) {
5200
+ try {
5201
+ const page = await this.dependencies.tasks.listMessages(this._taskId, {
5202
+ before,
5203
+ ...size !== void 0 ? { size } : {},
5204
+ ...ROOT_HISTORY
5205
+ });
5206
+ return generation !== this.historyGeneration || this.isClosed() ? null : page;
5207
+ } catch (error) {
5208
+ if (generation !== this.historyGeneration || this.isClosed()) return null;
5209
+ throw error;
5210
+ }
5211
+ }
5212
+ // The Copilot pages by piece, so a page can start inside a turn, and without the person's
5213
+ // message that opened it a screen cannot tell the answer from the text between tools (Crew,
5214
+ // 0.3.9). The rows before it are read with the same size until that message, and what the last
5215
+ // read brought from before it is left for the next page. A steer is a person's message too: a
5216
+ // turn steered past a page boundary starts at the steer. Rows carry no turn id to do better.
5217
+ async backToTurnStart(page, size, generation) {
5218
+ let content = page.content;
5219
+ let last = page;
5220
+ let reads = 0;
5221
+ while (hasOlderRows(last) && reads < MAX_TURN_START_READS) {
5222
+ const oldest = content[content.length - 1];
5223
+ if (!oldest || oldest.sender === "USER") break;
5224
+ reads++;
5225
+ const older = await this.readBefore(oldest.id, size, generation);
5226
+ if (!older) return null;
5227
+ const known = new Set(content.map((message) => message.id));
5228
+ if (older.content.some((message) => known.has(message.id))) break;
5229
+ last = older;
5230
+ const start = older.content.findIndex((message) => message.sender === "USER");
5231
+ if (start >= 0) {
5232
+ const left = start + 1 < older.content.length;
5233
+ content = [...content, ...older.content.slice(0, start + 1)];
5234
+ return pageWithOlder(content, left || hasOlderRows(older));
5235
+ }
5236
+ if (older.content.length === 0) break;
5237
+ content = [...content, ...older.content];
5238
+ }
5239
+ return content === page.content ? page : pageWithOlder(content, hasOlderRows(last));
5240
+ }
5061
5241
  // A page that starts at a piece held live, with live pieces before it that no row of the page
5062
5242
  // takes, skipped rows the Copilot wrote between two rereads (more than a page of them): kept as
5063
5243
  // they are, those pieces never get their rows, and `loadOlder` only reads before the oldest row.
@@ -5076,9 +5256,7 @@ var CoreAgentTaskSession = class {
5076
5256
  older = await this.dependencies.tasks.listMessages(this._taskId, {
5077
5257
  before: oldest.id,
5078
5258
  ...this.historyLimit !== void 0 ? { size: this.historyLimit } : {},
5079
- sort: "createdAt,desc",
5080
- kinds: "all",
5081
- include: "plan"
5259
+ ...ROOT_HISTORY
5082
5260
  });
5083
5261
  } catch (error) {
5084
5262
  if (generation !== this.historyGeneration || this.isClosed()) return;
@@ -5090,10 +5268,14 @@ var CoreAgentTaskSession = class {
5090
5268
  }
5091
5269
  this.replaceHistory(current);
5092
5270
  }
5271
+ reachesHistory(page) {
5272
+ const oldest = rootItemsOf(page.content).pop();
5273
+ return oldest !== void 0 && this._history.some((item) => samePiece(item, oldest));
5274
+ }
5093
5275
  // Newest first, as the Copilot answers. Once rows before the page were read, a row the history
5094
5276
  // does not hold at all (one the session never heard) is still inside the gap.
5095
5277
  skipsRows(page, extended) {
5096
- const rows = page.content.map(toAgentTimelineItem);
5278
+ const rows = rootItemsOf(page.content);
5097
5279
  const first = rows[rows.length - 1];
5098
5280
  if (!first) return false;
5099
5281
  const anchor = this._history.findIndex((item) => samePiece(item, first));
@@ -5111,7 +5293,7 @@ var CoreAgentTaskSession = class {
5111
5293
  // `loadOlder` (#145). A page that does not reach the history it already has replaces it.
5112
5294
  replaceHistory(page) {
5113
5295
  const oldest = oldestRowOf(this._history)?.id;
5114
- const rows = [...page.content].reverse().map(toAgentTimelineItem);
5296
+ const rows = rootItemsOf([...page.content].reverse());
5115
5297
  const rowsLog = [...rows].reverse().find((item) => item.boxLog !== void 0)?.boxLog;
5116
5298
  const liveComparable = this.rowsInChannelLog && (this.channelLog === void 0 || rowsLog === void 0 || rowsLog === this.channelLog);
5117
5299
  this.rowsInChannelLog = true;
@@ -5119,7 +5301,10 @@ var CoreAgentTaskSession = class {
5119
5301
  const anchor = first ? this._history.findIndex((item) => samePiece(item, first)) : -1;
5120
5302
  const kept = anchor < 0 ? [] : this._history.slice(0, anchor).filter((item) => !rows.some((row) => samePiece(item, row)));
5121
5303
  const replaced = anchor < 0 ? this._history : this._history.slice(anchor);
5122
- if (anchor < 0) this._hasOlder = hasOlderRows(page);
5304
+ if (anchor < 0) {
5305
+ this._hasOlder = hasOlderRows(page);
5306
+ this.olderCursor = page.content[page.content.length - 1]?.id;
5307
+ }
5123
5308
  const used = /* @__PURE__ */ new Set();
5124
5309
  const merged = rows.map((row) => {
5125
5310
  const held = this._history.find((item) => !used.has(item) && samePiece(item, row));
@@ -5209,6 +5394,8 @@ var CoreAgentTaskSession = class {
5209
5394
  this.connection?.close();
5210
5395
  this.connection = null;
5211
5396
  this.recoveryGeneration += 1;
5397
+ for (const delivery of this.deliveries.values()) clearTimeout(delivery.timer);
5398
+ this.deliveries.clear();
5212
5399
  const closedError = new Error("Agent task session is closed.");
5213
5400
  this.activeWaiter?.reject(closedError);
5214
5401
  this.activeWaiter = void 0;
@@ -5236,6 +5423,7 @@ var CoreAgentTaskSession = class {
5236
5423
  }
5237
5424
  startDispatch(prompt, options, clientMessageId, waiter) {
5238
5425
  this.sentTexts.set(clientMessageId, prompt);
5426
+ this.watchDelivery(clientMessageId);
5239
5427
  this.dispatching = true;
5240
5428
  let handedOver;
5241
5429
  this.handOff = new Promise((resolve) => {
@@ -5249,6 +5437,9 @@ var CoreAgentTaskSession = class {
5249
5437
  this.setStatus("idle");
5250
5438
  }
5251
5439
  return false;
5440
+ }).then((sent) => {
5441
+ this.deliveryEnded(clientMessageId, sent ? "sent" : "failed");
5442
+ return sent;
5252
5443
  }).finally(() => {
5253
5444
  handedOver();
5254
5445
  if (this.dispatch === dispatch) {
@@ -5279,6 +5470,7 @@ var CoreAgentTaskSession = class {
5279
5470
  this.recoveryUsed = false;
5280
5471
  this.recoveredTerminalReason = void 0;
5281
5472
  this.recoveredTerminalUsage = void 0;
5473
+ this.recoveredTerminalCompactions = void 0;
5282
5474
  this.recoveryGeneration += 1;
5283
5475
  this.activeWaiter = waiter;
5284
5476
  this.setStatus("streaming");
@@ -5346,7 +5538,7 @@ var CoreAgentTaskSession = class {
5346
5538
  // session for a message that asks for another model, which would end that turn.
5347
5539
  steer(prompt, options, waiter) {
5348
5540
  const steered = {
5349
- clientMessageId: newClientMessageId(),
5541
+ clientMessageId: options.clientMessageId || newClientMessageId(),
5350
5542
  ...waiter ? { waiter } : {},
5351
5543
  taken: false
5352
5544
  };
@@ -5356,6 +5548,7 @@ var CoreAgentTaskSession = class {
5356
5548
  this.strayedSteers.push(steered);
5357
5549
  }
5358
5550
  this.sentTexts.set(steered.clientMessageId, prompt);
5551
+ this.watchDelivery(steered.clientMessageId);
5359
5552
  const input = messageInput(prompt, options);
5360
5553
  this.pendingSteers += 1;
5361
5554
  const handed = this.handOff.then(async () => {
@@ -5371,6 +5564,7 @@ var CoreAgentTaskSession = class {
5371
5564
  void handed.then(({ admitted }) => admitted).then((admitted) => {
5372
5565
  if (!admitted) {
5373
5566
  this.forgetSteer(steered);
5567
+ this.deliveryEnded(steered.clientMessageId, "failed");
5374
5568
  waiter?.reject(
5375
5569
  steered.refusal ?? new AgentTaskTurnError("The Agent box did not take the message.")
5376
5570
  );
@@ -5380,6 +5574,7 @@ var CoreAgentTaskSession = class {
5380
5574
  this.acceptOnce(steered.clientMessageId);
5381
5575
  }).catch((error) => {
5382
5576
  this.forgetSteer(steered);
5577
+ this.deliveryEnded(steered.clientMessageId, "failed");
5383
5578
  waiter?.reject(error);
5384
5579
  this.emitSendError(error);
5385
5580
  }).finally(() => {
@@ -5456,6 +5651,7 @@ var CoreAgentTaskSession = class {
5456
5651
  this.recoveryUsed = false;
5457
5652
  this.recoveredTerminalReason = void 0;
5458
5653
  this.recoveredTerminalUsage = void 0;
5654
+ this.recoveredTerminalCompactions = void 0;
5459
5655
  this.recoveryGeneration += 1;
5460
5656
  this.turnBaselineIds = new Set(this._history.map((item) => item.id));
5461
5657
  void this.captureTurnBaseline().catch(() => void 0);
@@ -5515,7 +5711,7 @@ var CoreAgentTaskSession = class {
5515
5711
  this.options.transport,
5516
5712
  historyCursor
5517
5713
  ).then((connection) => {
5518
- if (this.isClosed() || this._status === "error") {
5714
+ if (this.isClosed() || this._status === "error" && !this.dispatching) {
5519
5715
  connection.close();
5520
5716
  return;
5521
5717
  }
@@ -5559,9 +5755,7 @@ var CoreAgentTaskSession = class {
5559
5755
  if (!this._taskId) return;
5560
5756
  const page = await this.dependencies.tasks.listMessages(this._taskId, {
5561
5757
  size: 100,
5562
- sort: "createdAt,desc",
5563
- kinds: "all",
5564
- include: "plan"
5758
+ ...ROOT_HISTORY
5565
5759
  });
5566
5760
  this.turnBaselineIds = new Set(page.content.map((message) => message.id));
5567
5761
  }
@@ -5569,9 +5763,7 @@ var CoreAgentTaskSession = class {
5569
5763
  if (!this._taskId) return false;
5570
5764
  const page = await this.dependencies.tasks.listMessages(this._taskId, {
5571
5765
  size: 100,
5572
- sort: "createdAt,desc",
5573
- kinds: "all",
5574
- include: "plan"
5766
+ ...ROOT_HISTORY
5575
5767
  });
5576
5768
  await this.rereadHistory(page);
5577
5769
  this.emit("historyLoaded", { history: this.history });
@@ -5590,19 +5782,28 @@ var CoreAgentTaskSession = class {
5590
5782
  );
5591
5783
  if (!newest) return false;
5592
5784
  this._content = newest.content;
5593
- this.finishTurn(reason, this.recoveredTerminalUsage);
5785
+ this.finishTurn(reason, this.recoveredTerminalUsage, this.recoveredTerminalEnd());
5594
5786
  return true;
5595
5787
  }
5596
5788
  if (recovered.type === "ERROR") {
5597
5789
  const error = new AgentTaskTurnError(recovered.content);
5598
- this.emit("error", { error: error.message });
5790
+ this.emit("error", { error: error.message, compactions: [] });
5599
5791
  this.failTurn(error);
5600
5792
  return true;
5601
5793
  }
5602
5794
  this._content = recovered.content;
5603
- this.finishTurn(reason, recovered.usage ?? this.recoveredTerminalUsage);
5795
+ this.finishTurn(
5796
+ reason,
5797
+ recovered.usage ?? this.recoveredTerminalUsage,
5798
+ this.recoveredTerminalEnd()
5799
+ );
5604
5800
  return true;
5605
5801
  }
5802
+ // The history rows carry no compactions: only a terminal heard live has the turn's list.
5803
+ recoveredTerminalEnd() {
5804
+ const compactions = this.recoveredTerminalCompactions;
5805
+ return compactions ? { compactions } : {};
5806
+ }
5606
5807
  closesThisTurn(message) {
5607
5808
  if (!message.usage) return false;
5608
5809
  const prompt = message.usage.requestMessageId;
@@ -5763,9 +5964,11 @@ var CoreAgentTaskSession = class {
5763
5964
  const finished = typeof lifecycle2?.turnId === "string" ? lifecycle2.turnId : void 0;
5764
5965
  if (finished !== void 0 && this.finishedTurnIds.includes(finished)) break;
5765
5966
  if (finished === void 0 && lifecycle2 && this.turnIds.size > 0) break;
5967
+ const compactions = agentTurnCompactionsOf(payload?.compactions);
5766
5968
  const end = {
5767
5969
  ...sequenceOf(event),
5768
- ...finished === void 0 ? {} : { turnId: finished }
5970
+ ...finished === void 0 ? {} : { turnId: finished },
5971
+ compactions
5769
5972
  };
5770
5973
  if (reason === "interrupted" || lifecycle2?.interruptTerminal === true) {
5771
5974
  this.rememberFinishedTurn(lifecycle2);
@@ -5777,6 +5980,7 @@ var CoreAgentTaskSession = class {
5777
5980
  if (this.recoveryUsed) {
5778
5981
  this.recoveredTerminalReason = reason;
5779
5982
  this.recoveredTerminalUsage = usage;
5983
+ this.recoveredTerminalCompactions = compactions;
5780
5984
  if (!this.recoveryPromise) {
5781
5985
  const generation = this.recoveryGeneration;
5782
5986
  this.recoveryPromise = this.recoverTurn(generation).finally(() => {
@@ -5792,24 +5996,20 @@ var CoreAgentTaskSession = class {
5792
5996
  case "error": {
5793
5997
  const code = typeof payload?.code === "string" ? payload.code : void 0;
5794
5998
  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
- }
5999
+ const compactions = agentTurnCompactionsOf(payload?.compactions);
6000
+ const endsTurn = this.boxErrorEndsTurn(payload, message, code);
6001
+ this.emit("error", {
6002
+ ...code ? { code } : {},
6003
+ error: message,
6004
+ ...sequenceOf(event),
6005
+ ...endsTurn ? { compactions } : {}
6006
+ });
6007
+ if (endsTurn) this.failTurn(new AgentTaskTurnError(message, code, compactions));
5811
6008
  break;
5812
6009
  }
6010
+ case "contextCompacted":
6011
+ if (!this.isFinishedTurnFrame(lifecycle)) this.emitCompaction(event, payload);
6012
+ break;
5813
6013
  case "approval":
5814
6014
  case "user_input_request":
5815
6015
  this.liveRequest(event, payload);
@@ -5883,6 +6083,7 @@ var CoreAgentTaskSession = class {
5883
6083
  if (ours) this.acceptOnce(id);
5884
6084
  }
5885
6085
  acceptOnce(id) {
6086
+ this.deliveryEnded(id, "sent");
5886
6087
  if (this.acceptedIds.includes(id)) return;
5887
6088
  this.acceptedIds.push(id);
5888
6089
  if (this.acceptedIds.length > 32) this.acceptedIds.shift();
@@ -5953,6 +6154,22 @@ var CoreAgentTaskSession = class {
5953
6154
  this.turnIds.add(turnId);
5954
6155
  return false;
5955
6156
  }
6157
+ // A refused steer is handed its refusal here, for the send that waits on it.
6158
+ boxErrorEndsTurn(payload, message, code) {
6159
+ if (!payload?.lifecycle && payload?.requestId !== void 0) return false;
6160
+ if (typeof payload?.command === "string") return false;
6161
+ const refused = payload?.lifecycle ? void 0 : payload?.clientMessageId;
6162
+ if (typeof refused === "string") {
6163
+ if (refused !== this.openingMessageId) {
6164
+ const steered = [...this.steers, ...this.strayedSteers].find(
6165
+ (pending) => pending.clientMessageId === refused
6166
+ );
6167
+ if (steered) steered.refusal = new AgentTaskTurnError(message, code);
6168
+ return false;
6169
+ }
6170
+ } else if (!payload?.lifecycle && !this.dispatching && this.pendingSteers > 0) return false;
6171
+ return this._status === "streaming" || this._status === "cancelled";
6172
+ }
5956
6173
  isFinishedTurnFrame(lifecycle) {
5957
6174
  const turnId = lifecycle?.turnId;
5958
6175
  return typeof turnId === "string" && this.finishedTurnIds.includes(turnId);
@@ -6039,7 +6256,7 @@ var CoreAgentTaskSession = class {
6039
6256
  if (oldest?.sequence === void 0 || oldest.boxLog !== newest?.boxLog) return false;
6040
6257
  return sequence < oldest.sequence;
6041
6258
  }
6042
- liveText(event, payload, kind, parentToolId) {
6259
+ liveText(event, payload, kind) {
6043
6260
  const itemId = typeof payload?.itemId === "string" ? payload.itemId : void 0;
6044
6261
  if (itemId === void 0) return;
6045
6262
  const piece = itemDeltaOf(payload).itemDelta ?? (typeof payload?.text === "string" ? payload.text : "");
@@ -6053,8 +6270,7 @@ var CoreAgentTaskSession = class {
6053
6270
  text: piece,
6054
6271
  at: liveAtOf(event),
6055
6272
  itemId,
6056
- ...sequence === void 0 ? {} : { sequence },
6057
- ...parentToolIdOf(parentToolId)
6273
+ ...sequence === void 0 ? {} : { sequence }
6058
6274
  }),
6059
6275
  (item) => {
6060
6276
  const held = item.lastSequence ?? item.sequence;
@@ -6087,7 +6303,7 @@ var CoreAgentTaskSession = class {
6087
6303
  // An approval or a question T3 asks mid-turn enters where it came, with the frame's payload as
6088
6304
  // it came, as the Copilot records it (`APPROVAL` and `USER_INPUT_REQUEST` rows). It still
6089
6305
  // reaches the app as a `raw` event, as before.
6090
- liveRequest(event, payload, parentToolId) {
6306
+ liveRequest(event, payload) {
6091
6307
  if (!payload) return;
6092
6308
  const kind = event.type === "approval" ? "approval" : event.type === "notification" ? "notification" : "userInputRequest";
6093
6309
  const itemId = typeof payload.itemId === "string" ? payload.itemId : void 0;
@@ -6101,8 +6317,7 @@ var CoreAgentTaskSession = class {
6101
6317
  payload,
6102
6318
  at: liveAtOf(event),
6103
6319
  ...sequence === void 0 ? {} : { sequence },
6104
- ...itemId === void 0 ? {} : { itemId },
6105
- ...parentToolIdOf(parentToolId)
6320
+ ...itemId === void 0 ? {} : { itemId }
6106
6321
  };
6107
6322
  return kind === "notification" ? { ...item, kind, ...notificationFieldsOf(payload) } : { ...item, kind };
6108
6323
  },
@@ -6149,7 +6364,9 @@ var CoreAgentTaskSession = class {
6149
6364
  }
6150
6365
  // A child thread's frames are the subagent's conversation: they open no turn and settle no
6151
6366
  // message. Its text and tools still reach `delta`, `content` and `tool` as they did in 0.2.13,
6152
- // which knew no subagents, so an app that only bumps the version sees what it saw before.
6367
+ // which knew no subagents, so an app that only bumps the version sees what it saw before. None
6368
+ // enters `history`, which holds the chat's own thread as `thread=root` reads it back: the
6369
+ // subagent's pieces come from `loadSubagent`, and its approvals still reach `raw`.
6153
6370
  handleSubagentFrame(event, payload) {
6154
6371
  const parentToolId = payload.parentToolId;
6155
6372
  switch (event.type) {
@@ -6160,7 +6377,6 @@ var CoreAgentTaskSession = class {
6160
6377
  const kind = event.type === "thinking" ? "thinking" : "text";
6161
6378
  const identity = { ...itemDeltaOf(payload), ...pieceIdentityOf(event, payload) };
6162
6379
  if (kind === "text") this._content += delta;
6163
- this.liveText(event, payload, kind, parentToolId);
6164
6380
  this.emit("delta", { delta, kind, parentToolId, ...identity });
6165
6381
  this.emit("subagentDelta", { parentToolId, delta, kind, ...identity });
6166
6382
  break;
@@ -6171,19 +6387,26 @@ var CoreAgentTaskSession = class {
6171
6387
  ...toolEventOf(event, payload, event.type === "toolCall" ? "call" : "result"),
6172
6388
  parentToolId
6173
6389
  };
6174
- this.liveTool(tool, event);
6175
6390
  this.emit("tool", tool);
6176
6391
  this.emit("subagentTool", tool);
6177
6392
  break;
6178
6393
  }
6179
- case "approval":
6180
- case "user_input_request":
6181
- this.liveRequest(event, payload, parentToolId);
6394
+ case "contextCompacted":
6395
+ this.emitCompaction(event, payload, parentToolId);
6182
6396
  break;
6183
6397
  default:
6184
6398
  break;
6185
6399
  }
6186
6400
  }
6401
+ emitCompaction(event, payload, parentToolId) {
6402
+ const compaction = agentTurnCompactionOf(payload);
6403
+ if (!compaction) return;
6404
+ this.emit("contextCompacted", {
6405
+ ...compaction,
6406
+ ...pieceIdentityOf(event, payload),
6407
+ ...parentToolIdOf(parentToolId)
6408
+ });
6409
+ }
6187
6410
  applySubagent(event, payload) {
6188
6411
  const subagentId = payload?.subagentId;
6189
6412
  const toolId = payload?.toolId;
@@ -6247,7 +6470,8 @@ var CoreAgentTaskSession = class {
6247
6470
  content: this._content,
6248
6471
  reason,
6249
6472
  ...usage ? { usage } : {},
6250
- ...end
6473
+ ...end,
6474
+ compactions: end.compactions ?? []
6251
6475
  };
6252
6476
  this.emit("turnEnd", result);
6253
6477
  this.activeWaiter?.resolve(result);
@@ -6317,6 +6541,29 @@ var CoreAgentTaskSession = class {
6317
6541
  }
6318
6542
  return waiter;
6319
6543
  }
6544
+ // A message waits in silence for whatever it needs before it leaves (the task, the channel, a
6545
+ // read of the history, the box's answer) when the network is down without failing the request
6546
+ // (Crew, 0.3.9). Failing it after a deadline could not stop the request already out, which may
6547
+ // still deliver it, and a send again would be a second message: the screen is told instead.
6548
+ watchDelivery(id) {
6549
+ const delivery = {
6550
+ timer: void 0,
6551
+ delayed: false
6552
+ };
6553
+ delivery.timer = setTimeout(() => {
6554
+ delivery.timer = void 0;
6555
+ delivery.delayed = true;
6556
+ this.emit("delivery", { clientMessageId: id, state: "delayed" });
6557
+ }, this.dependencies.deliveryDelayMs);
6558
+ this.deliveries.set(id, delivery);
6559
+ }
6560
+ deliveryEnded(id, state) {
6561
+ const delivery = this.deliveries.get(id);
6562
+ if (!delivery) return;
6563
+ this.deliveries.delete(id);
6564
+ clearTimeout(delivery.timer);
6565
+ if (delivery.delayed) this.emit("delivery", { clientMessageId: id, state });
6566
+ }
6320
6567
  emitError(prefix, error) {
6321
6568
  const code = errorCode(error);
6322
6569
  this.emit("error", {
@@ -6367,6 +6614,13 @@ var CoreAgentTaskSession = class {
6367
6614
  }
6368
6615
  };
6369
6616
 
6617
+ // src/agentTurnEvent.ts
6618
+ function isAgentTurnEvent(value) {
6619
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
6620
+ const event = value;
6621
+ return (event.type === "STARTED" || event.type === "ENDED") && typeof event.eventId === "string" && typeof event.taskId === "string" && typeof event.turnId === "string" && typeof event.occurredAt === "string";
6622
+ }
6623
+
6370
6624
  // src/apiKeySession.ts
6371
6625
  var API_KEY_EXCHANGE_PATH = "/api/v1/auth/exchange";
6372
6626
  function appAccessTokenPath(appId) {
@@ -6478,6 +6732,7 @@ async function resolveApiKeyToken(call, appId, apiKey, errors = defaultSdkCoreEr
6478
6732
  expectObjectArray,
6479
6733
  expectPage,
6480
6734
  expectStringArray,
6735
+ isAgentTurnEvent,
6481
6736
  isWorkspaceSession,
6482
6737
  readTokenAppId,
6483
6738
  readTokenExpiry,