@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.js CHANGED
@@ -980,7 +980,40 @@ function expectAgentTask(value, context, errors = defaultSdkCoreErrorFactory) {
980
980
  if (typeof task.archived !== "boolean") invalidField(context, "archived", errors);
981
981
  if (!isNullableString(task.createdAt)) invalidField(context, "createdAt", errors);
982
982
  if (typeof task.updatedAt !== "string") invalidField(context, "updatedAt", errors);
983
- 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
+ });
984
1017
  }
985
1018
  function expectAgentTaskChannel(value, context, errors = defaultSdkCoreErrorFactory) {
986
1019
  if (value === void 0 || value === null || value === "") return null;
@@ -1054,6 +1087,22 @@ function agentTurnUsageOf(value) {
1054
1087
  }
1055
1088
  return usage;
1056
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
+ }
1057
1106
  function agentTurnUsageRequestOf(value) {
1058
1107
  if (!isObject(value)) return void 0;
1059
1108
  const request = {};
@@ -1692,6 +1741,8 @@ function createAgentsModule(functionsTransport, copilotTransport, errors = defau
1692
1741
  }
1693
1742
 
1694
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}$/;
1695
1746
  function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory) {
1696
1747
  const path = (id) => `/api/v1/tasks/${encodePathSegment(id, "task id", errors)}`;
1697
1748
  return {
@@ -1705,12 +1756,18 @@ function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory)
1705
1756
  search: options.search,
1706
1757
  userId: options.userId
1707
1758
  };
1708
- return expectPage(
1759
+ const context = "Agent task page response";
1760
+ const page = expectPage(
1709
1761
  await transport.request("/api/v1/tasks", { method: "GET", params }),
1710
- "Agent task page response",
1711
- errors,
1712
- expectAgentTask
1762
+ context,
1763
+ errors
1713
1764
  );
1765
+ return {
1766
+ ...page,
1767
+ content: page.content.map(
1768
+ (task, position) => expectAgentTask(task, `${context} item ${position}`, errors)
1769
+ )
1770
+ };
1714
1771
  },
1715
1772
  async get(id) {
1716
1773
  return expectAgentTask(
@@ -1733,6 +1790,16 @@ function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory)
1733
1790
  errors
1734
1791
  );
1735
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
+ },
1736
1803
  async archive(id) {
1737
1804
  expectEmpty(
1738
1805
  await transport.request(`${path(id)}/archive`, { method: "PATCH" }),
@@ -1758,7 +1825,9 @@ function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory)
1758
1825
  sort: options.sort,
1759
1826
  kinds: options.kinds,
1760
1827
  include: options.include,
1761
- before: options.before
1828
+ before: options.before,
1829
+ thread: options.thread,
1830
+ parentToolId: options.parentToolId
1762
1831
  }
1763
1832
  }),
1764
1833
  context,
@@ -1777,6 +1846,26 @@ function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory)
1777
1846
  "Agent task channel response",
1778
1847
  errors
1779
1848
  );
1849
+ },
1850
+ async turnStates(ids) {
1851
+ const unique = [...new Set(ids.map((id) => id.toLowerCase()))].filter((id) => UUID.test(id));
1852
+ const states = [];
1853
+ for (let start = 0; start < unique.length; start += TURN_STATES_BATCH_SIZE) {
1854
+ const taskIds = unique.slice(start, start + TURN_STATES_BATCH_SIZE);
1855
+ states.push(
1856
+ ...expectAgentTaskTurnStates(
1857
+ await transport.request("/api/v1/tasks/turn-states", {
1858
+ method: "GET",
1859
+ // Joined here because a transport may send an array as repeated keys; the Copilot
1860
+ // reads one comma-separated value.
1861
+ params: { taskIds: taskIds.join(",") }
1862
+ }),
1863
+ "Agent task turn states response",
1864
+ errors
1865
+ )
1866
+ );
1867
+ }
1868
+ return states;
1780
1869
  }
1781
1870
  };
1782
1871
  }
@@ -3626,10 +3715,13 @@ function unavailableTransport(name, errors) {
3626
3715
  // src/agentTurnError.ts
3627
3716
  var AgentTaskTurnError = class extends Error {
3628
3717
  code;
3629
- constructor(message, code) {
3718
+ /** The compactions of a turn the box closed with an error; empty when it reported none. */
3719
+ compactions;
3720
+ constructor(message, code, compactions = []) {
3630
3721
  super(message);
3631
3722
  this.name = "AgentTaskTurnError";
3632
3723
  this.code = code;
3724
+ this.compactions = compactions;
3633
3725
  }
3634
3726
  };
3635
3727
 
@@ -4449,7 +4541,15 @@ var AgentDirectChannel = class {
4449
4541
 
4450
4542
  // src/agentSession.ts
4451
4543
  var CANCEL_SAFETY_MS = 1e4;
4544
+ var DELIVERY_DELAY_MS = 2e4;
4545
+ var MAX_TURN_START_READS = 10;
4452
4546
  var RECONCILE_DELAY_MS = 1e3;
4547
+ var ROOT_HISTORY = {
4548
+ sort: "createdAt,desc",
4549
+ kinds: "all",
4550
+ include: "plan",
4551
+ thread: "root"
4552
+ };
4453
4553
  var ENDED_POLLS_BEFORE_NEWEST = 3;
4454
4554
  var TURN_TAIL_TYPES = /* @__PURE__ */ new Set([
4455
4555
  "textDelta",
@@ -4621,6 +4721,10 @@ function rowOrHeld(held, row, liveComparable) {
4621
4721
  function hasOlderRows(page) {
4622
4722
  return page.page.totalPages > page.page.number + 1;
4623
4723
  }
4724
+ function pageWithOlder(content, older) {
4725
+ const size = content.length;
4726
+ return { content, page: { size, totalElements: size, totalPages: older ? 2 : 1, number: 0 } };
4727
+ }
4624
4728
  function isChatRow(message) {
4625
4729
  return (message.type === "TEXT" || message.type === "ERROR" || message.type === "TOOL_USE") && message.parentToolId === void 0;
4626
4730
  }
@@ -4713,6 +4817,12 @@ function toAgentTimelineItem(message) {
4713
4817
  ...parentToolIdOf(message.parentToolId)
4714
4818
  };
4715
4819
  }
4820
+ function parentToolIdOfItem(item) {
4821
+ return item.kind === "tool" ? item.tool.parentToolId : item.parentToolId;
4822
+ }
4823
+ function rootItemsOf(messages) {
4824
+ return messages.map(toAgentTimelineItem).filter((item) => parentToolIdOfItem(item) === void 0);
4825
+ }
4716
4826
  function liveAtOf(event) {
4717
4827
  return new Date(typeof event.timestamp === "number" ? event.timestamp : Date.now()).toISOString();
4718
4828
  }
@@ -4726,13 +4836,17 @@ function createAgentTaskSessionManager(options) {
4726
4836
  session(requested) {
4727
4837
  if ("taskId" in requested) {
4728
4838
  const current = sessions.get(requested.taskId);
4729
- if (current && current.status !== "closed") return current;
4839
+ if (current && current.status !== "closed") {
4840
+ if (!requested.reopen || current.status !== "error") return current;
4841
+ current.close();
4842
+ }
4730
4843
  }
4731
4844
  const sessionOptions = "create" in requested && requested.agentId && !requested.runtime && channel.canDial(requested.transport) ? { ...requested, runtime: "T3" } : requested;
4732
4845
  const session = new CoreAgentTaskSession(sessionOptions, {
4733
4846
  tasks: options.tasks,
4734
4847
  eventSource: options.eventSource,
4735
4848
  channel,
4849
+ deliveryDelayMs: options.deliveryDelayMs ?? DELIVERY_DELAY_MS,
4736
4850
  onTaskId: (taskId, value) => sessions.set(taskId, value),
4737
4851
  onClose: (taskId, value) => {
4738
4852
  if (sessions.get(taskId) === value) sessions.delete(taskId);
@@ -4781,6 +4895,7 @@ var CoreAgentTaskSession = class {
4781
4895
  recoveryGeneration = 0;
4782
4896
  recoveredTerminalReason;
4783
4897
  recoveredTerminalUsage;
4898
+ recoveredTerminalCompactions;
4784
4899
  // Polls that found no closing row although a terminal with usage was heard.
4785
4900
  endedPollsWithoutRow = 0;
4786
4901
  // The turn ids the running turn went by, and the highest box sequence seen in it. The Copilot
@@ -4824,6 +4939,9 @@ var CoreAgentTaskSession = class {
4824
4939
  openingCursor;
4825
4940
  historyLimit;
4826
4941
  _hasOlder = false;
4942
+ // The oldest row read so far, kept or not: a page of a Copilot that ignores `thread=root` can
4943
+ // be all subagent rows, and reading before the oldest kept row would read it again (#162).
4944
+ olderCursor;
4827
4945
  // Moves whenever `history` is replaced, so a `loadOlder` still reading drops what it read.
4828
4946
  historyGeneration = 0;
4829
4947
  // Whether the box the channel follows counts in the log of the history's rows. A box whose hello
@@ -4833,6 +4951,8 @@ var CoreAgentTaskSession = class {
4833
4951
  // flag above starts over at each reread, and a page from the old log may come again.
4834
4952
  channelLog;
4835
4953
  olderRead = null;
4954
+ // Messages sent and not at the server yet, by `clientMessageId`, each with its `delivery` clock.
4955
+ deliveries = /* @__PURE__ */ new Map();
4836
4956
  get taskId() {
4837
4957
  return this._taskId;
4838
4958
  }
@@ -4861,7 +4981,7 @@ var CoreAgentTaskSession = class {
4861
4981
  this.requireOpen();
4862
4982
  if (!prompt.trim()) return void 0;
4863
4983
  if (this.isBusy()) return this.steer(prompt, options);
4864
- const clientMessageId = newClientMessageId();
4984
+ const clientMessageId = options.clientMessageId || newClientMessageId();
4865
4985
  this.startDispatch(prompt, options, clientMessageId);
4866
4986
  return clientMessageId;
4867
4987
  }
@@ -4873,13 +4993,19 @@ var CoreAgentTaskSession = class {
4873
4993
  const sendOptions = {
4874
4994
  ...options.agentType ? { agentType: options.agentType } : {},
4875
4995
  ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {},
4876
- ...options.mode ? { mode: options.mode } : {}
4996
+ ...options.mode ? { mode: options.mode } : {},
4997
+ ...options.clientMessageId ? { clientMessageId: options.clientMessageId } : {}
4877
4998
  };
4878
4999
  if (this.isBusy()) {
4879
5000
  this.steer(prompt, sendOptions, waiter);
4880
5001
  return waiter.promise;
4881
5002
  }
4882
- this.startDispatch(prompt, sendOptions, newClientMessageId(), waiter);
5003
+ this.startDispatch(
5004
+ prompt,
5005
+ sendOptions,
5006
+ sendOptions.clientMessageId || newClientMessageId(),
5007
+ waiter
5008
+ );
4883
5009
  return waiter.promise;
4884
5010
  }
4885
5011
  async cancel() {
@@ -4897,7 +5023,7 @@ var CoreAgentTaskSession = class {
4897
5023
  const error = new AgentTaskTurnError(
4898
5024
  "Agent turn cancellation was not acknowledged before the safety timeout."
4899
5025
  );
4900
- this.emit("error", { error: error.message });
5026
+ this.emit("error", { error: error.message, compactions: [] });
4901
5027
  this.failTurn(error);
4902
5028
  }
4903
5029
  }, CANCEL_SAFETY_MS);
@@ -4924,14 +5050,14 @@ var CoreAgentTaskSession = class {
4924
5050
  }
4925
5051
  async loadHistory(options = {}) {
4926
5052
  if (!this._taskId) return [];
5053
+ const generation = this.historyGeneration;
4927
5054
  const page = await this.dependencies.tasks.listMessages(this._taskId, {
4928
5055
  ...options.limit !== void 0 ? { size: options.limit } : {},
4929
- sort: "createdAt,desc",
4930
- kinds: "all",
4931
- include: "plan"
5056
+ ...ROOT_HISTORY
4932
5057
  });
4933
5058
  this.historyLimit = options.limit;
4934
- await this.rereadHistory(page);
5059
+ const whole = this.reachesHistory(page) ? page : await this.backToTurnStart(page, options.limit, generation);
5060
+ if (whole) await this.rereadHistory(whole);
4935
5061
  const history = this.history;
4936
5062
  this.emit("historyLoaded", { history });
4937
5063
  return history;
@@ -4939,34 +5065,25 @@ var CoreAgentTaskSession = class {
4939
5065
  get hasOlder() {
4940
5066
  return this._hasOlder;
4941
5067
  }
4942
- loadOlder() {
5068
+ loadOlder(options = {}) {
4943
5069
  if (this.olderRead?.generation !== this.historyGeneration) {
4944
5070
  const generation = this.historyGeneration;
4945
- const promise = this.readOlder(generation).finally(() => {
5071
+ const size = options.limit ?? this.historyLimit;
5072
+ const promise = this.readOlder(generation, size).finally(() => {
4946
5073
  if (this.olderRead?.promise === promise) this.olderRead = null;
4947
5074
  });
4948
5075
  this.olderRead = { generation, promise };
4949
5076
  }
4950
5077
  return this.olderRead.promise;
4951
5078
  }
4952
- async readOlder(generation) {
4953
- const oldest = oldestRowOf(this._history);
4954
- if (!this._taskId || !this._hasOlder || !oldest) return [];
4955
- let page;
4956
- try {
4957
- page = await this.dependencies.tasks.listMessages(this._taskId, {
4958
- before: oldest.id,
4959
- ...this.historyLimit !== void 0 ? { size: this.historyLimit } : {},
4960
- sort: "createdAt,desc",
4961
- kinds: "all",
4962
- include: "plan"
4963
- });
4964
- } catch (error) {
4965
- if (generation !== this.historyGeneration || this.isClosed()) return [];
4966
- throw error;
4967
- }
4968
- if (generation !== this.historyGeneration || this.isClosed()) return [];
4969
- const rows = [...page.content].reverse().map(toAgentTimelineItem);
5079
+ async readOlder(generation, size) {
5080
+ const before = this.olderCursor ?? oldestRowOf(this._history)?.id;
5081
+ if (!this._taskId || !this._hasOlder || !before) return [];
5082
+ const page = await this.readBefore(before, size, generation);
5083
+ const whole = page && await this.backToTurnStart(page, size, generation);
5084
+ if (!whole) return [];
5085
+ this.olderCursor = whole.content[whole.content.length - 1]?.id ?? before;
5086
+ const rows = rootItemsOf([...whole.content].reverse());
4970
5087
  const rowsLog = [...rows].reverse().find((item) => item.boxLog !== void 0)?.boxLog;
4971
5088
  const liveComparable = this.rowsInChannelLog && (this.channelLog === void 0 || rowsLog === void 0 || rowsLog === this.channelLog);
4972
5089
  const taken = /* @__PURE__ */ new Set();
@@ -4978,11 +5095,73 @@ var CoreAgentTaskSession = class {
4978
5095
  taken.add(held);
4979
5096
  return rowOrHeld(held, row, liveComparable);
4980
5097
  });
4981
- this._hasOlder = hasOlderRows(page);
5098
+ this._hasOlder = hasOlderRows(whole);
4982
5099
  this._history = [...older, ...this._history.filter((item) => !taken.has(item))];
4983
5100
  this.emit("historyLoaded", { history: this.history });
4984
5101
  return older;
4985
5102
  }
5103
+ async loadSubagent(toolId, options = {}) {
5104
+ if (!this._taskId) return { items: [], hasOlder: false };
5105
+ const page = await this.dependencies.tasks.listMessages(this._taskId, {
5106
+ ...options.limit !== void 0 ? { size: options.limit } : {},
5107
+ ...options.before !== void 0 ? { before: options.before } : {},
5108
+ sort: "createdAt,desc",
5109
+ kinds: "all",
5110
+ include: "plan",
5111
+ parentToolId: toolId
5112
+ });
5113
+ const items = [...page.content].reverse().map(toAgentTimelineItem).filter((item) => parentToolIdOfItem(item) === toolId);
5114
+ const oldest = page.content[page.content.length - 1];
5115
+ return {
5116
+ items,
5117
+ hasOlder: hasOlderRows(page),
5118
+ ...oldest === void 0 ? {} : { before: oldest.id }
5119
+ };
5120
+ }
5121
+ // The rows recorded before `before`, or null once `history` was replaced or the session closed:
5122
+ // a read of a history since replaced resolves with nothing, as its success would.
5123
+ async readBefore(before, size, generation) {
5124
+ try {
5125
+ const page = await this.dependencies.tasks.listMessages(this._taskId, {
5126
+ before,
5127
+ ...size !== void 0 ? { size } : {},
5128
+ ...ROOT_HISTORY
5129
+ });
5130
+ return generation !== this.historyGeneration || this.isClosed() ? null : page;
5131
+ } catch (error) {
5132
+ if (generation !== this.historyGeneration || this.isClosed()) return null;
5133
+ throw error;
5134
+ }
5135
+ }
5136
+ // The Copilot pages by piece, so a page can start inside a turn, and without the person's
5137
+ // message that opened it a screen cannot tell the answer from the text between tools (Crew,
5138
+ // 0.3.9). The rows before it are read with the same size until that message, and what the last
5139
+ // read brought from before it is left for the next page. A steer is a person's message too: a
5140
+ // turn steered past a page boundary starts at the steer. Rows carry no turn id to do better.
5141
+ async backToTurnStart(page, size, generation) {
5142
+ let content = page.content;
5143
+ let last = page;
5144
+ let reads = 0;
5145
+ while (hasOlderRows(last) && reads < MAX_TURN_START_READS) {
5146
+ const oldest = content[content.length - 1];
5147
+ if (!oldest || oldest.sender === "USER") break;
5148
+ reads++;
5149
+ const older = await this.readBefore(oldest.id, size, generation);
5150
+ if (!older) return null;
5151
+ const known = new Set(content.map((message) => message.id));
5152
+ if (older.content.some((message) => known.has(message.id))) break;
5153
+ last = older;
5154
+ const start = older.content.findIndex((message) => message.sender === "USER");
5155
+ if (start >= 0) {
5156
+ const left = start + 1 < older.content.length;
5157
+ content = [...content, ...older.content.slice(0, start + 1)];
5158
+ return pageWithOlder(content, left || hasOlderRows(older));
5159
+ }
5160
+ if (older.content.length === 0) break;
5161
+ content = [...content, ...older.content];
5162
+ }
5163
+ return content === page.content ? page : pageWithOlder(content, hasOlderRows(last));
5164
+ }
4986
5165
  // A page that starts at a piece held live, with live pieces before it that no row of the page
4987
5166
  // takes, skipped rows the Copilot wrote between two rereads (more than a page of them): kept as
4988
5167
  // they are, those pieces never get their rows, and `loadOlder` only reads before the oldest row.
@@ -5001,9 +5180,7 @@ var CoreAgentTaskSession = class {
5001
5180
  older = await this.dependencies.tasks.listMessages(this._taskId, {
5002
5181
  before: oldest.id,
5003
5182
  ...this.historyLimit !== void 0 ? { size: this.historyLimit } : {},
5004
- sort: "createdAt,desc",
5005
- kinds: "all",
5006
- include: "plan"
5183
+ ...ROOT_HISTORY
5007
5184
  });
5008
5185
  } catch (error) {
5009
5186
  if (generation !== this.historyGeneration || this.isClosed()) return;
@@ -5015,10 +5192,14 @@ var CoreAgentTaskSession = class {
5015
5192
  }
5016
5193
  this.replaceHistory(current);
5017
5194
  }
5195
+ reachesHistory(page) {
5196
+ const oldest = rootItemsOf(page.content).pop();
5197
+ return oldest !== void 0 && this._history.some((item) => samePiece(item, oldest));
5198
+ }
5018
5199
  // Newest first, as the Copilot answers. Once rows before the page were read, a row the history
5019
5200
  // does not hold at all (one the session never heard) is still inside the gap.
5020
5201
  skipsRows(page, extended) {
5021
- const rows = page.content.map(toAgentTimelineItem);
5202
+ const rows = rootItemsOf(page.content);
5022
5203
  const first = rows[rows.length - 1];
5023
5204
  if (!first) return false;
5024
5205
  const anchor = this._history.findIndex((item) => samePiece(item, first));
@@ -5036,7 +5217,7 @@ var CoreAgentTaskSession = class {
5036
5217
  // `loadOlder` (#145). A page that does not reach the history it already has replaces it.
5037
5218
  replaceHistory(page) {
5038
5219
  const oldest = oldestRowOf(this._history)?.id;
5039
- const rows = [...page.content].reverse().map(toAgentTimelineItem);
5220
+ const rows = rootItemsOf([...page.content].reverse());
5040
5221
  const rowsLog = [...rows].reverse().find((item) => item.boxLog !== void 0)?.boxLog;
5041
5222
  const liveComparable = this.rowsInChannelLog && (this.channelLog === void 0 || rowsLog === void 0 || rowsLog === this.channelLog);
5042
5223
  this.rowsInChannelLog = true;
@@ -5044,7 +5225,10 @@ var CoreAgentTaskSession = class {
5044
5225
  const anchor = first ? this._history.findIndex((item) => samePiece(item, first)) : -1;
5045
5226
  const kept = anchor < 0 ? [] : this._history.slice(0, anchor).filter((item) => !rows.some((row) => samePiece(item, row)));
5046
5227
  const replaced = anchor < 0 ? this._history : this._history.slice(anchor);
5047
- if (anchor < 0) this._hasOlder = hasOlderRows(page);
5228
+ if (anchor < 0) {
5229
+ this._hasOlder = hasOlderRows(page);
5230
+ this.olderCursor = page.content[page.content.length - 1]?.id;
5231
+ }
5048
5232
  const used = /* @__PURE__ */ new Set();
5049
5233
  const merged = rows.map((row) => {
5050
5234
  const held = this._history.find((item) => !used.has(item) && samePiece(item, row));
@@ -5134,6 +5318,8 @@ var CoreAgentTaskSession = class {
5134
5318
  this.connection?.close();
5135
5319
  this.connection = null;
5136
5320
  this.recoveryGeneration += 1;
5321
+ for (const delivery of this.deliveries.values()) clearTimeout(delivery.timer);
5322
+ this.deliveries.clear();
5137
5323
  const closedError = new Error("Agent task session is closed.");
5138
5324
  this.activeWaiter?.reject(closedError);
5139
5325
  this.activeWaiter = void 0;
@@ -5161,6 +5347,7 @@ var CoreAgentTaskSession = class {
5161
5347
  }
5162
5348
  startDispatch(prompt, options, clientMessageId, waiter) {
5163
5349
  this.sentTexts.set(clientMessageId, prompt);
5350
+ this.watchDelivery(clientMessageId);
5164
5351
  this.dispatching = true;
5165
5352
  let handedOver;
5166
5353
  this.handOff = new Promise((resolve) => {
@@ -5174,6 +5361,9 @@ var CoreAgentTaskSession = class {
5174
5361
  this.setStatus("idle");
5175
5362
  }
5176
5363
  return false;
5364
+ }).then((sent) => {
5365
+ this.deliveryEnded(clientMessageId, sent ? "sent" : "failed");
5366
+ return sent;
5177
5367
  }).finally(() => {
5178
5368
  handedOver();
5179
5369
  if (this.dispatch === dispatch) {
@@ -5204,6 +5394,7 @@ var CoreAgentTaskSession = class {
5204
5394
  this.recoveryUsed = false;
5205
5395
  this.recoveredTerminalReason = void 0;
5206
5396
  this.recoveredTerminalUsage = void 0;
5397
+ this.recoveredTerminalCompactions = void 0;
5207
5398
  this.recoveryGeneration += 1;
5208
5399
  this.activeWaiter = waiter;
5209
5400
  this.setStatus("streaming");
@@ -5271,7 +5462,7 @@ var CoreAgentTaskSession = class {
5271
5462
  // session for a message that asks for another model, which would end that turn.
5272
5463
  steer(prompt, options, waiter) {
5273
5464
  const steered = {
5274
- clientMessageId: newClientMessageId(),
5465
+ clientMessageId: options.clientMessageId || newClientMessageId(),
5275
5466
  ...waiter ? { waiter } : {},
5276
5467
  taken: false
5277
5468
  };
@@ -5281,6 +5472,7 @@ var CoreAgentTaskSession = class {
5281
5472
  this.strayedSteers.push(steered);
5282
5473
  }
5283
5474
  this.sentTexts.set(steered.clientMessageId, prompt);
5475
+ this.watchDelivery(steered.clientMessageId);
5284
5476
  const input = messageInput(prompt, options);
5285
5477
  this.pendingSteers += 1;
5286
5478
  const handed = this.handOff.then(async () => {
@@ -5296,6 +5488,7 @@ var CoreAgentTaskSession = class {
5296
5488
  void handed.then(({ admitted }) => admitted).then((admitted) => {
5297
5489
  if (!admitted) {
5298
5490
  this.forgetSteer(steered);
5491
+ this.deliveryEnded(steered.clientMessageId, "failed");
5299
5492
  waiter?.reject(
5300
5493
  steered.refusal ?? new AgentTaskTurnError("The Agent box did not take the message.")
5301
5494
  );
@@ -5305,6 +5498,7 @@ var CoreAgentTaskSession = class {
5305
5498
  this.acceptOnce(steered.clientMessageId);
5306
5499
  }).catch((error) => {
5307
5500
  this.forgetSteer(steered);
5501
+ this.deliveryEnded(steered.clientMessageId, "failed");
5308
5502
  waiter?.reject(error);
5309
5503
  this.emitSendError(error);
5310
5504
  }).finally(() => {
@@ -5381,6 +5575,7 @@ var CoreAgentTaskSession = class {
5381
5575
  this.recoveryUsed = false;
5382
5576
  this.recoveredTerminalReason = void 0;
5383
5577
  this.recoveredTerminalUsage = void 0;
5578
+ this.recoveredTerminalCompactions = void 0;
5384
5579
  this.recoveryGeneration += 1;
5385
5580
  this.turnBaselineIds = new Set(this._history.map((item) => item.id));
5386
5581
  void this.captureTurnBaseline().catch(() => void 0);
@@ -5440,7 +5635,7 @@ var CoreAgentTaskSession = class {
5440
5635
  this.options.transport,
5441
5636
  historyCursor
5442
5637
  ).then((connection) => {
5443
- if (this.isClosed() || this._status === "error") {
5638
+ if (this.isClosed() || this._status === "error" && !this.dispatching) {
5444
5639
  connection.close();
5445
5640
  return;
5446
5641
  }
@@ -5484,9 +5679,7 @@ var CoreAgentTaskSession = class {
5484
5679
  if (!this._taskId) return;
5485
5680
  const page = await this.dependencies.tasks.listMessages(this._taskId, {
5486
5681
  size: 100,
5487
- sort: "createdAt,desc",
5488
- kinds: "all",
5489
- include: "plan"
5682
+ ...ROOT_HISTORY
5490
5683
  });
5491
5684
  this.turnBaselineIds = new Set(page.content.map((message) => message.id));
5492
5685
  }
@@ -5494,9 +5687,7 @@ var CoreAgentTaskSession = class {
5494
5687
  if (!this._taskId) return false;
5495
5688
  const page = await this.dependencies.tasks.listMessages(this._taskId, {
5496
5689
  size: 100,
5497
- sort: "createdAt,desc",
5498
- kinds: "all",
5499
- include: "plan"
5690
+ ...ROOT_HISTORY
5500
5691
  });
5501
5692
  await this.rereadHistory(page);
5502
5693
  this.emit("historyLoaded", { history: this.history });
@@ -5515,19 +5706,28 @@ var CoreAgentTaskSession = class {
5515
5706
  );
5516
5707
  if (!newest) return false;
5517
5708
  this._content = newest.content;
5518
- this.finishTurn(reason, this.recoveredTerminalUsage);
5709
+ this.finishTurn(reason, this.recoveredTerminalUsage, this.recoveredTerminalEnd());
5519
5710
  return true;
5520
5711
  }
5521
5712
  if (recovered.type === "ERROR") {
5522
5713
  const error = new AgentTaskTurnError(recovered.content);
5523
- this.emit("error", { error: error.message });
5714
+ this.emit("error", { error: error.message, compactions: [] });
5524
5715
  this.failTurn(error);
5525
5716
  return true;
5526
5717
  }
5527
5718
  this._content = recovered.content;
5528
- this.finishTurn(reason, recovered.usage ?? this.recoveredTerminalUsage);
5719
+ this.finishTurn(
5720
+ reason,
5721
+ recovered.usage ?? this.recoveredTerminalUsage,
5722
+ this.recoveredTerminalEnd()
5723
+ );
5529
5724
  return true;
5530
5725
  }
5726
+ // The history rows carry no compactions: only a terminal heard live has the turn's list.
5727
+ recoveredTerminalEnd() {
5728
+ const compactions = this.recoveredTerminalCompactions;
5729
+ return compactions ? { compactions } : {};
5730
+ }
5531
5731
  closesThisTurn(message) {
5532
5732
  if (!message.usage) return false;
5533
5733
  const prompt = message.usage.requestMessageId;
@@ -5688,9 +5888,11 @@ var CoreAgentTaskSession = class {
5688
5888
  const finished = typeof lifecycle2?.turnId === "string" ? lifecycle2.turnId : void 0;
5689
5889
  if (finished !== void 0 && this.finishedTurnIds.includes(finished)) break;
5690
5890
  if (finished === void 0 && lifecycle2 && this.turnIds.size > 0) break;
5891
+ const compactions = agentTurnCompactionsOf(payload?.compactions);
5691
5892
  const end = {
5692
5893
  ...sequenceOf(event),
5693
- ...finished === void 0 ? {} : { turnId: finished }
5894
+ ...finished === void 0 ? {} : { turnId: finished },
5895
+ compactions
5694
5896
  };
5695
5897
  if (reason === "interrupted" || lifecycle2?.interruptTerminal === true) {
5696
5898
  this.rememberFinishedTurn(lifecycle2);
@@ -5702,6 +5904,7 @@ var CoreAgentTaskSession = class {
5702
5904
  if (this.recoveryUsed) {
5703
5905
  this.recoveredTerminalReason = reason;
5704
5906
  this.recoveredTerminalUsage = usage;
5907
+ this.recoveredTerminalCompactions = compactions;
5705
5908
  if (!this.recoveryPromise) {
5706
5909
  const generation = this.recoveryGeneration;
5707
5910
  this.recoveryPromise = this.recoverTurn(generation).finally(() => {
@@ -5717,24 +5920,20 @@ var CoreAgentTaskSession = class {
5717
5920
  case "error": {
5718
5921
  const code = typeof payload?.code === "string" ? payload.code : void 0;
5719
5922
  const message = typeof payload?.message === "string" ? payload.message : "Agent returned an error.";
5720
- this.emit("error", { ...code ? { code } : {}, error: message, ...sequenceOf(event) });
5721
- if (!payload?.lifecycle && payload?.requestId !== void 0) break;
5722
- if (typeof payload?.command === "string") break;
5723
- const refused = payload?.lifecycle ? void 0 : payload?.clientMessageId;
5724
- if (typeof refused === "string") {
5725
- if (refused !== this.openingMessageId) {
5726
- const steered = [...this.steers, ...this.strayedSteers].find(
5727
- (pending) => pending.clientMessageId === refused
5728
- );
5729
- if (steered) steered.refusal = new AgentTaskTurnError(message, code);
5730
- break;
5731
- }
5732
- } else if (!payload?.lifecycle && !this.dispatching && this.pendingSteers > 0) break;
5733
- if (this._status === "streaming" || this._status === "cancelled") {
5734
- this.failTurn(new AgentTaskTurnError(message, code));
5735
- }
5923
+ const compactions = agentTurnCompactionsOf(payload?.compactions);
5924
+ const endsTurn = this.boxErrorEndsTurn(payload, message, code);
5925
+ this.emit("error", {
5926
+ ...code ? { code } : {},
5927
+ error: message,
5928
+ ...sequenceOf(event),
5929
+ ...endsTurn ? { compactions } : {}
5930
+ });
5931
+ if (endsTurn) this.failTurn(new AgentTaskTurnError(message, code, compactions));
5736
5932
  break;
5737
5933
  }
5934
+ case "contextCompacted":
5935
+ if (!this.isFinishedTurnFrame(lifecycle)) this.emitCompaction(event, payload);
5936
+ break;
5738
5937
  case "approval":
5739
5938
  case "user_input_request":
5740
5939
  this.liveRequest(event, payload);
@@ -5808,6 +6007,7 @@ var CoreAgentTaskSession = class {
5808
6007
  if (ours) this.acceptOnce(id);
5809
6008
  }
5810
6009
  acceptOnce(id) {
6010
+ this.deliveryEnded(id, "sent");
5811
6011
  if (this.acceptedIds.includes(id)) return;
5812
6012
  this.acceptedIds.push(id);
5813
6013
  if (this.acceptedIds.length > 32) this.acceptedIds.shift();
@@ -5878,6 +6078,22 @@ var CoreAgentTaskSession = class {
5878
6078
  this.turnIds.add(turnId);
5879
6079
  return false;
5880
6080
  }
6081
+ // A refused steer is handed its refusal here, for the send that waits on it.
6082
+ boxErrorEndsTurn(payload, message, code) {
6083
+ if (!payload?.lifecycle && payload?.requestId !== void 0) return false;
6084
+ if (typeof payload?.command === "string") return false;
6085
+ const refused = payload?.lifecycle ? void 0 : payload?.clientMessageId;
6086
+ if (typeof refused === "string") {
6087
+ if (refused !== this.openingMessageId) {
6088
+ const steered = [...this.steers, ...this.strayedSteers].find(
6089
+ (pending) => pending.clientMessageId === refused
6090
+ );
6091
+ if (steered) steered.refusal = new AgentTaskTurnError(message, code);
6092
+ return false;
6093
+ }
6094
+ } else if (!payload?.lifecycle && !this.dispatching && this.pendingSteers > 0) return false;
6095
+ return this._status === "streaming" || this._status === "cancelled";
6096
+ }
5881
6097
  isFinishedTurnFrame(lifecycle) {
5882
6098
  const turnId = lifecycle?.turnId;
5883
6099
  return typeof turnId === "string" && this.finishedTurnIds.includes(turnId);
@@ -5964,7 +6180,7 @@ var CoreAgentTaskSession = class {
5964
6180
  if (oldest?.sequence === void 0 || oldest.boxLog !== newest?.boxLog) return false;
5965
6181
  return sequence < oldest.sequence;
5966
6182
  }
5967
- liveText(event, payload, kind, parentToolId) {
6183
+ liveText(event, payload, kind) {
5968
6184
  const itemId = typeof payload?.itemId === "string" ? payload.itemId : void 0;
5969
6185
  if (itemId === void 0) return;
5970
6186
  const piece = itemDeltaOf(payload).itemDelta ?? (typeof payload?.text === "string" ? payload.text : "");
@@ -5978,8 +6194,7 @@ var CoreAgentTaskSession = class {
5978
6194
  text: piece,
5979
6195
  at: liveAtOf(event),
5980
6196
  itemId,
5981
- ...sequence === void 0 ? {} : { sequence },
5982
- ...parentToolIdOf(parentToolId)
6197
+ ...sequence === void 0 ? {} : { sequence }
5983
6198
  }),
5984
6199
  (item) => {
5985
6200
  const held = item.lastSequence ?? item.sequence;
@@ -6012,7 +6227,7 @@ var CoreAgentTaskSession = class {
6012
6227
  // An approval or a question T3 asks mid-turn enters where it came, with the frame's payload as
6013
6228
  // it came, as the Copilot records it (`APPROVAL` and `USER_INPUT_REQUEST` rows). It still
6014
6229
  // reaches the app as a `raw` event, as before.
6015
- liveRequest(event, payload, parentToolId) {
6230
+ liveRequest(event, payload) {
6016
6231
  if (!payload) return;
6017
6232
  const kind = event.type === "approval" ? "approval" : event.type === "notification" ? "notification" : "userInputRequest";
6018
6233
  const itemId = typeof payload.itemId === "string" ? payload.itemId : void 0;
@@ -6026,8 +6241,7 @@ var CoreAgentTaskSession = class {
6026
6241
  payload,
6027
6242
  at: liveAtOf(event),
6028
6243
  ...sequence === void 0 ? {} : { sequence },
6029
- ...itemId === void 0 ? {} : { itemId },
6030
- ...parentToolIdOf(parentToolId)
6244
+ ...itemId === void 0 ? {} : { itemId }
6031
6245
  };
6032
6246
  return kind === "notification" ? { ...item, kind, ...notificationFieldsOf(payload) } : { ...item, kind };
6033
6247
  },
@@ -6074,7 +6288,9 @@ var CoreAgentTaskSession = class {
6074
6288
  }
6075
6289
  // A child thread's frames are the subagent's conversation: they open no turn and settle no
6076
6290
  // message. Its text and tools still reach `delta`, `content` and `tool` as they did in 0.2.13,
6077
- // which knew no subagents, so an app that only bumps the version sees what it saw before.
6291
+ // which knew no subagents, so an app that only bumps the version sees what it saw before. None
6292
+ // enters `history`, which holds the chat's own thread as `thread=root` reads it back: the
6293
+ // subagent's pieces come from `loadSubagent`, and its approvals still reach `raw`.
6078
6294
  handleSubagentFrame(event, payload) {
6079
6295
  const parentToolId = payload.parentToolId;
6080
6296
  switch (event.type) {
@@ -6085,7 +6301,6 @@ var CoreAgentTaskSession = class {
6085
6301
  const kind = event.type === "thinking" ? "thinking" : "text";
6086
6302
  const identity = { ...itemDeltaOf(payload), ...pieceIdentityOf(event, payload) };
6087
6303
  if (kind === "text") this._content += delta;
6088
- this.liveText(event, payload, kind, parentToolId);
6089
6304
  this.emit("delta", { delta, kind, parentToolId, ...identity });
6090
6305
  this.emit("subagentDelta", { parentToolId, delta, kind, ...identity });
6091
6306
  break;
@@ -6096,19 +6311,26 @@ var CoreAgentTaskSession = class {
6096
6311
  ...toolEventOf(event, payload, event.type === "toolCall" ? "call" : "result"),
6097
6312
  parentToolId
6098
6313
  };
6099
- this.liveTool(tool, event);
6100
6314
  this.emit("tool", tool);
6101
6315
  this.emit("subagentTool", tool);
6102
6316
  break;
6103
6317
  }
6104
- case "approval":
6105
- case "user_input_request":
6106
- this.liveRequest(event, payload, parentToolId);
6318
+ case "contextCompacted":
6319
+ this.emitCompaction(event, payload, parentToolId);
6107
6320
  break;
6108
6321
  default:
6109
6322
  break;
6110
6323
  }
6111
6324
  }
6325
+ emitCompaction(event, payload, parentToolId) {
6326
+ const compaction = agentTurnCompactionOf(payload);
6327
+ if (!compaction) return;
6328
+ this.emit("contextCompacted", {
6329
+ ...compaction,
6330
+ ...pieceIdentityOf(event, payload),
6331
+ ...parentToolIdOf(parentToolId)
6332
+ });
6333
+ }
6112
6334
  applySubagent(event, payload) {
6113
6335
  const subagentId = payload?.subagentId;
6114
6336
  const toolId = payload?.toolId;
@@ -6172,7 +6394,8 @@ var CoreAgentTaskSession = class {
6172
6394
  content: this._content,
6173
6395
  reason,
6174
6396
  ...usage ? { usage } : {},
6175
- ...end
6397
+ ...end,
6398
+ compactions: end.compactions ?? []
6176
6399
  };
6177
6400
  this.emit("turnEnd", result);
6178
6401
  this.activeWaiter?.resolve(result);
@@ -6242,6 +6465,29 @@ var CoreAgentTaskSession = class {
6242
6465
  }
6243
6466
  return waiter;
6244
6467
  }
6468
+ // A message waits in silence for whatever it needs before it leaves (the task, the channel, a
6469
+ // read of the history, the box's answer) when the network is down without failing the request
6470
+ // (Crew, 0.3.9). Failing it after a deadline could not stop the request already out, which may
6471
+ // still deliver it, and a send again would be a second message: the screen is told instead.
6472
+ watchDelivery(id) {
6473
+ const delivery = {
6474
+ timer: void 0,
6475
+ delayed: false
6476
+ };
6477
+ delivery.timer = setTimeout(() => {
6478
+ delivery.timer = void 0;
6479
+ delivery.delayed = true;
6480
+ this.emit("delivery", { clientMessageId: id, state: "delayed" });
6481
+ }, this.dependencies.deliveryDelayMs);
6482
+ this.deliveries.set(id, delivery);
6483
+ }
6484
+ deliveryEnded(id, state) {
6485
+ const delivery = this.deliveries.get(id);
6486
+ if (!delivery) return;
6487
+ this.deliveries.delete(id);
6488
+ clearTimeout(delivery.timer);
6489
+ if (delivery.delayed) this.emit("delivery", { clientMessageId: id, state });
6490
+ }
6245
6491
  emitError(prefix, error) {
6246
6492
  const code = errorCode(error);
6247
6493
  this.emit("error", {
@@ -6292,6 +6538,13 @@ var CoreAgentTaskSession = class {
6292
6538
  }
6293
6539
  };
6294
6540
 
6541
+ // src/agentTurnEvent.ts
6542
+ function isAgentTurnEvent(value) {
6543
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
6544
+ const event = value;
6545
+ return (event.type === "STARTED" || event.type === "ENDED") && typeof event.eventId === "string" && typeof event.taskId === "string" && typeof event.turnId === "string" && typeof event.occurredAt === "string";
6546
+ }
6547
+
6295
6548
  // src/apiKeySession.ts
6296
6549
  var API_KEY_EXCHANGE_PATH = "/api/v1/auth/exchange";
6297
6550
  function appAccessTokenPath(appId) {
@@ -6402,6 +6655,7 @@ export {
6402
6655
  expectObjectArray,
6403
6656
  expectPage,
6404
6657
  expectStringArray,
6658
+ isAgentTurnEvent,
6405
6659
  isWorkspaceSession,
6406
6660
  readTokenAppId,
6407
6661
  readTokenExpiry,