@mitralab.io/sdk-core 0.3.8 → 0.3.9

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
@@ -4272,6 +4272,14 @@ function errorCode(error) {
4272
4272
  const code = candidate.code ?? candidate.details?.code ?? candidate.details?.error_code;
4273
4273
  return typeof code === "string" ? code : void 0;
4274
4274
  }
4275
+ function refusalSentence(error) {
4276
+ if (!error || typeof error !== "object" || errorCode(error) === void 0) return void 0;
4277
+ const candidate = error;
4278
+ const refused = error instanceof AgentTaskTurnError || typeof candidate.status === "number" && candidate.status >= 400;
4279
+ if (!refused) return void 0;
4280
+ const sentence = asObject2(candidate.details)?.message ?? asObject2(candidate.body)?.message ?? errorMessage2(error);
4281
+ return typeof sentence === "string" && sentence.trim() ? sentence : void 0;
4282
+ }
4275
4283
  function delay(milliseconds) {
4276
4284
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
4277
4285
  }
@@ -4351,6 +4359,46 @@ function historyCursorOf(history) {
4351
4359
  }
4352
4360
  return { sequence, ...newest.boxLog === void 0 ? {} : { boxLog: newest.boxLog } };
4353
4361
  }
4362
+ var SUBAGENT_END_STATUSES = /* @__PURE__ */ new Set([
4363
+ "completed",
4364
+ "failed",
4365
+ "cancelled",
4366
+ "interrupted"
4367
+ ]);
4368
+ function samePiece(held, row) {
4369
+ if (held.id === row.id) return true;
4370
+ if (!held.id.startsWith("live:")) return false;
4371
+ if (held.kind === "user" && row.kind === "user" && held.clientMessageId !== void 0) {
4372
+ return held.clientMessageId === row.clientMessageId;
4373
+ }
4374
+ if (row.itemId === void 0) return false;
4375
+ if (held.kind !== row.kind || held.itemId !== row.itemId) return false;
4376
+ return held.kind !== "tool" || row.kind === "tool" && held.tool.phase === row.tool.phase;
4377
+ }
4378
+ function heldIsNewer(held, row) {
4379
+ const heldLast = held.lastSequence ?? held.sequence;
4380
+ const rowLast = row.lastSequence ?? row.sequence;
4381
+ if (heldLast === void 0 || rowLast === void 0) return false;
4382
+ if (held.boxLog !== void 0 && held.boxLog !== row.boxLog) return false;
4383
+ return heldLast > rowLast;
4384
+ }
4385
+ function heldHasRow(held, row) {
4386
+ if (held.kind !== "agent" && held.kind !== "reasoning") return true;
4387
+ return held.sequence !== void 0 && row.sequence !== void 0 && held.sequence <= row.sequence;
4388
+ }
4389
+ function oldestRowOf(history) {
4390
+ return history.find((item) => !item.id.startsWith("live:"));
4391
+ }
4392
+ function rowOrHeld(held, row, liveComparable) {
4393
+ if (!liveComparable || !heldIsNewer(held, row) || !heldHasRow(held, row)) return row;
4394
+ return {
4395
+ ...held,
4396
+ id: row.id,
4397
+ ...row.sequence === void 0 ? {} : { sequence: row.sequence },
4398
+ ...held.lastSequence === void 0 && held.sequence === void 0 ? {} : { lastSequence: held.lastSequence ?? held.sequence },
4399
+ ...row.boxLog === void 0 ? {} : { boxLog: row.boxLog }
4400
+ };
4401
+ }
4354
4402
  function hasOlderRows(page) {
4355
4403
  return page.page.totalPages > page.page.number + 1;
4356
4404
  }
@@ -4562,6 +4610,9 @@ var CoreAgentTaskSession = class {
4562
4610
  // Whether the box the channel follows counts in the log of the history's rows. A box whose hello
4563
4611
  // names another log, or reports a log shorter than the history's, has sequences that start over.
4564
4612
  rowsInChannelLog = true;
4613
+ // The log the hello of the channel named. A reread compares its rows with it every time: the
4614
+ // flag above starts over at each reread, and a page from the old log may come again.
4615
+ channelLog;
4565
4616
  olderRead = null;
4566
4617
  get taskId() {
4567
4618
  return this._taskId;
@@ -4661,7 +4712,7 @@ var CoreAgentTaskSession = class {
4661
4712
  include: "plan"
4662
4713
  });
4663
4714
  this.historyLimit = options.limit;
4664
- this.replaceHistory(page);
4715
+ await this.rereadHistory(page);
4665
4716
  const history = this.history;
4666
4717
  this.emit("historyLoaded", { history });
4667
4718
  return history;
@@ -4680,7 +4731,7 @@ var CoreAgentTaskSession = class {
4680
4731
  return this.olderRead.promise;
4681
4732
  }
4682
4733
  async readOlder(generation) {
4683
- const oldest = this._history.find((item) => !item.id.startsWith("live:"));
4734
+ const oldest = oldestRowOf(this._history);
4684
4735
  if (!this._taskId || !this._hasOlder || !oldest) return [];
4685
4736
  let page;
4686
4737
  try {
@@ -4696,17 +4747,110 @@ var CoreAgentTaskSession = class {
4696
4747
  throw error;
4697
4748
  }
4698
4749
  if (generation !== this.historyGeneration || this.isClosed()) return [];
4699
- const older = [...page.content].reverse().map(toAgentTimelineItem);
4750
+ const rows = [...page.content].reverse().map(toAgentTimelineItem);
4751
+ const rowsLog = [...rows].reverse().find((item) => item.boxLog !== void 0)?.boxLog;
4752
+ const liveComparable = this.rowsInChannelLog && (this.channelLog === void 0 || rowsLog === void 0 || rowsLog === this.channelLog);
4753
+ const taken = /* @__PURE__ */ new Set();
4754
+ const older = rows.map((row) => {
4755
+ const held = this._history.find(
4756
+ (item) => !taken.has(item) && item.id.startsWith("live:") && samePiece(item, row)
4757
+ );
4758
+ if (held === void 0) return row;
4759
+ taken.add(held);
4760
+ return rowOrHeld(held, row, liveComparable);
4761
+ });
4700
4762
  this._hasOlder = hasOlderRows(page);
4701
- this._history = [...older, ...this._history];
4763
+ this._history = [...older, ...this._history.filter((item) => !taken.has(item))];
4702
4764
  this.emit("historyLoaded", { history: this.history });
4703
4765
  return older;
4704
4766
  }
4767
+ // A page that starts at a piece held live, with live pieces before it that no row of the page
4768
+ // takes, skipped rows the Copilot wrote between two rereads (more than a page of them): kept as
4769
+ // they are, those pieces never get their rows, and `loadOlder` only reads before the oldest row.
4770
+ // The rows before the page are read as `loadOlder` reads them, until the page reaches a row the
4771
+ // history holds or the gap's pieces all have their rows. A read of a history since replaced
4772
+ // lands nowhere (#145).
4773
+ async rereadHistory(page) {
4774
+ const generation = this.historyGeneration;
4775
+ let current = page;
4776
+ let extended = false;
4777
+ while (this._taskId && hasOlderRows(current) && this.skipsRows(current, extended)) {
4778
+ const oldest = current.content[current.content.length - 1];
4779
+ if (!oldest) break;
4780
+ let older;
4781
+ try {
4782
+ older = await this.dependencies.tasks.listMessages(this._taskId, {
4783
+ before: oldest.id,
4784
+ ...this.historyLimit !== void 0 ? { size: this.historyLimit } : {},
4785
+ sort: "createdAt,desc",
4786
+ kinds: "all",
4787
+ include: "plan"
4788
+ });
4789
+ } catch (error) {
4790
+ if (generation !== this.historyGeneration || this.isClosed()) return;
4791
+ throw error;
4792
+ }
4793
+ if (generation !== this.historyGeneration || this.isClosed()) return;
4794
+ current = { content: [...current.content, ...older.content], page: older.page };
4795
+ extended = true;
4796
+ }
4797
+ this.replaceHistory(current);
4798
+ }
4799
+ // Newest first, as the Copilot answers. Once rows before the page were read, a row the history
4800
+ // does not hold at all (one the session never heard) is still inside the gap.
4801
+ skipsRows(page, extended) {
4802
+ const rows = page.content.map(toAgentTimelineItem);
4803
+ const first = rows[rows.length - 1];
4804
+ if (!first) return false;
4805
+ const anchor = this._history.findIndex((item) => samePiece(item, first));
4806
+ if (anchor < 0) return extended;
4807
+ if (!this._history[anchor]?.id.startsWith("live:")) return false;
4808
+ for (let index = anchor - 1; index >= 0; index -= 1) {
4809
+ const held = this._history[index];
4810
+ if (!held?.id.startsWith("live:")) return false;
4811
+ if (!rows.some((row) => samePiece(held, row))) return true;
4812
+ }
4813
+ return false;
4814
+ }
4815
+ // The recovery rereads only the newest 100 rows while the turn runs: the older pages already
4816
+ // read stay, or what sits in them (the cards of subagents still running) vanishes until
4817
+ // `loadOlder` (#145). A page that does not reach the history it already has replaces it.
4705
4818
  replaceHistory(page) {
4706
- this.historyGeneration += 1;
4819
+ const oldest = oldestRowOf(this._history)?.id;
4820
+ const rows = [...page.content].reverse().map(toAgentTimelineItem);
4821
+ const rowsLog = [...rows].reverse().find((item) => item.boxLog !== void 0)?.boxLog;
4822
+ const liveComparable = this.rowsInChannelLog && (this.channelLog === void 0 || rowsLog === void 0 || rowsLog === this.channelLog);
4707
4823
  this.rowsInChannelLog = true;
4708
- this._hasOlder = hasOlderRows(page);
4709
- this._history = [...page.content].reverse().map(toAgentTimelineItem);
4824
+ const first = rows[0];
4825
+ const anchor = first ? this._history.findIndex((item) => samePiece(item, first)) : -1;
4826
+ const kept = anchor < 0 ? [] : this._history.slice(0, anchor).filter((item) => !rows.some((row) => samePiece(item, row)));
4827
+ const replaced = anchor < 0 ? this._history : this._history.slice(anchor);
4828
+ if (anchor < 0) this._hasOlder = hasOlderRows(page);
4829
+ const used = /* @__PURE__ */ new Set();
4830
+ const merged = rows.map((row) => {
4831
+ const held = this._history.find((item) => !used.has(item) && samePiece(item, row));
4832
+ if (held === void 0) return row;
4833
+ used.add(held);
4834
+ return rowOrHeld(held, row, liveComparable);
4835
+ });
4836
+ const cursor = liveComparable ? historyCursorOf(rows) : void 0;
4837
+ const unrecorded = cursor === void 0 ? [] : replaced.filter(
4838
+ (item) => !used.has(item) && item.id.startsWith("live:") && item.sequence !== void 0 && (item.kind === "plan" || item.sequence > cursor.sequence)
4839
+ );
4840
+ this._history = [...kept, ...merged, ...unrecorded];
4841
+ if (anchor < 0 || oldestRowOf(this._history)?.id !== oldest) this.historyGeneration += 1;
4842
+ if (cursor === void 0) return;
4843
+ for (const subagent of this.subagentsById.values()) {
4844
+ const row = this._history.find(
4845
+ (item) => item.kind === "tool" && item.tool.toolId === subagent.toolId
4846
+ );
4847
+ const rowStatus = row?.kind === "tool" ? row.subagent?.status : void 0;
4848
+ if (rowStatus !== void 0 && SUBAGENT_END_STATUSES.has(rowStatus)) continue;
4849
+ const applied = this.subagentSequences.get(subagent.subagentId);
4850
+ if (SUBAGENT_END_STATUSES.has(subagent.status) || applied !== void 0 && applied > cursor.sequence) {
4851
+ this.writeSubagentOnSpawn(subagent);
4852
+ }
4853
+ }
4710
4854
  }
4711
4855
  editQueueItem(id, text) {
4712
4856
  this.requireOpen();
@@ -4805,7 +4949,7 @@ var CoreAgentTaskSession = class {
4805
4949
  });
4806
4950
  const dispatch = this.dispatchSend(prompt, options, clientMessageId, handedOver, waiter).catch((error) => {
4807
4951
  waiter?.reject(error);
4808
- this.emitError("Failed to send Agent prompt", error);
4952
+ this.emitSendError(error);
4809
4953
  if (this._status === "streaming") {
4810
4954
  this.settleSteers((steered) => steered.reject(error));
4811
4955
  this.setStatus("idle");
@@ -4873,7 +5017,7 @@ var CoreAgentTaskSession = class {
4873
5017
  taken = await admitted;
4874
5018
  } catch (error) {
4875
5019
  handedOver();
4876
- this.emitError("Failed to send Agent prompt", error);
5020
+ this.emitSendError(error);
4877
5021
  return fail(error);
4878
5022
  }
4879
5023
  if (!taken) {
@@ -4943,7 +5087,7 @@ var CoreAgentTaskSession = class {
4943
5087
  }).catch((error) => {
4944
5088
  this.forgetSteer(steered);
4945
5089
  waiter?.reject(error);
4946
- this.emitError("Failed to send Agent prompt", error);
5090
+ this.emitSendError(error);
4947
5091
  }).finally(() => {
4948
5092
  this.pendingSteers -= 1;
4949
5093
  });
@@ -5135,7 +5279,7 @@ var CoreAgentTaskSession = class {
5135
5279
  kinds: "all",
5136
5280
  include: "plan"
5137
5281
  });
5138
- this.replaceHistory(page);
5282
+ await this.rereadHistory(page);
5139
5283
  this.emit("historyLoaded", { history: this.history });
5140
5284
  const rows = page.content.filter(isChatRow);
5141
5285
  const recovered = rows.find(
@@ -5289,6 +5433,7 @@ var CoreAgentTaskSession = class {
5289
5433
  break;
5290
5434
  case "hello": {
5291
5435
  const lastSequence = payload?.lastSequence;
5436
+ if (typeof payload?.boxLog === "number") this.channelLog = payload.boxLog;
5292
5437
  const history = historyCursorOf(this._history);
5293
5438
  const rowsLog = [...this._history].reverse().find((item) => item.boxLog !== void 0)?.boxLog;
5294
5439
  if (typeof payload?.boxLog === "number" && rowsLog !== void 0 && payload.boxLog !== rowsLog || typeof lastSequence === "number" && history !== void 0 && lastSequence < history.sequence) {
@@ -5765,6 +5910,12 @@ var CoreAgentTaskSession = class {
5765
5910
  ...typeof payload?.childThreadId === "string" ? { childThreadId: payload.childThreadId } : {}
5766
5911
  };
5767
5912
  this.subagentsById.set(subagentId, subagent);
5913
+ this.writeSubagentOnSpawn(subagent);
5914
+ this.emit("subagent", { ...subagent, ...sequenceOf(event) });
5915
+ }
5916
+ // The call that spawned it carries its last state, as the history records it.
5917
+ writeSubagentOnSpawn(subagent) {
5918
+ const { toolId, subagentId, status } = subagent;
5768
5919
  const index = this._history.findIndex(
5769
5920
  (item) => item.kind === "tool" && item.tool.toolId === toolId
5770
5921
  );
@@ -5782,7 +5933,6 @@ var CoreAgentTaskSession = class {
5782
5933
  }
5783
5934
  };
5784
5935
  }
5785
- this.emit("subagent", { ...subagent, ...sequenceOf(event) });
5786
5936
  }
5787
5937
  finishTurn(reason, usage, end = {}) {
5788
5938
  if (this._status !== "streaming" && this._status !== "cancelled") return;
@@ -5880,6 +6030,15 @@ var CoreAgentTaskSession = class {
5880
6030
  error: `${prefix}: ${errorMessage2(error)}`
5881
6031
  });
5882
6032
  }
6033
+ emitSendError(error) {
6034
+ const sentence = refusalSentence(error);
6035
+ if (sentence === void 0) {
6036
+ this.emitError("Failed to send Agent prompt", error);
6037
+ return;
6038
+ }
6039
+ const code = errorCode(error);
6040
+ this.emit("error", { ...code ? { code } : {}, error: sentence });
6041
+ }
5883
6042
  setStatus(status) {
5884
6043
  if (this._status === status) return;
5885
6044
  if (status !== "streaming" && status !== "cancelled") {
package/dist/index.js CHANGED
@@ -4199,6 +4199,14 @@ function errorCode(error) {
4199
4199
  const code = candidate.code ?? candidate.details?.code ?? candidate.details?.error_code;
4200
4200
  return typeof code === "string" ? code : void 0;
4201
4201
  }
4202
+ function refusalSentence(error) {
4203
+ if (!error || typeof error !== "object" || errorCode(error) === void 0) return void 0;
4204
+ const candidate = error;
4205
+ const refused = error instanceof AgentTaskTurnError || typeof candidate.status === "number" && candidate.status >= 400;
4206
+ if (!refused) return void 0;
4207
+ const sentence = asObject2(candidate.details)?.message ?? asObject2(candidate.body)?.message ?? errorMessage2(error);
4208
+ return typeof sentence === "string" && sentence.trim() ? sentence : void 0;
4209
+ }
4202
4210
  function delay(milliseconds) {
4203
4211
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
4204
4212
  }
@@ -4278,6 +4286,46 @@ function historyCursorOf(history) {
4278
4286
  }
4279
4287
  return { sequence, ...newest.boxLog === void 0 ? {} : { boxLog: newest.boxLog } };
4280
4288
  }
4289
+ var SUBAGENT_END_STATUSES = /* @__PURE__ */ new Set([
4290
+ "completed",
4291
+ "failed",
4292
+ "cancelled",
4293
+ "interrupted"
4294
+ ]);
4295
+ function samePiece(held, row) {
4296
+ if (held.id === row.id) return true;
4297
+ if (!held.id.startsWith("live:")) return false;
4298
+ if (held.kind === "user" && row.kind === "user" && held.clientMessageId !== void 0) {
4299
+ return held.clientMessageId === row.clientMessageId;
4300
+ }
4301
+ if (row.itemId === void 0) return false;
4302
+ if (held.kind !== row.kind || held.itemId !== row.itemId) return false;
4303
+ return held.kind !== "tool" || row.kind === "tool" && held.tool.phase === row.tool.phase;
4304
+ }
4305
+ function heldIsNewer(held, row) {
4306
+ const heldLast = held.lastSequence ?? held.sequence;
4307
+ const rowLast = row.lastSequence ?? row.sequence;
4308
+ if (heldLast === void 0 || rowLast === void 0) return false;
4309
+ if (held.boxLog !== void 0 && held.boxLog !== row.boxLog) return false;
4310
+ return heldLast > rowLast;
4311
+ }
4312
+ function heldHasRow(held, row) {
4313
+ if (held.kind !== "agent" && held.kind !== "reasoning") return true;
4314
+ return held.sequence !== void 0 && row.sequence !== void 0 && held.sequence <= row.sequence;
4315
+ }
4316
+ function oldestRowOf(history) {
4317
+ return history.find((item) => !item.id.startsWith("live:"));
4318
+ }
4319
+ function rowOrHeld(held, row, liveComparable) {
4320
+ if (!liveComparable || !heldIsNewer(held, row) || !heldHasRow(held, row)) return row;
4321
+ return {
4322
+ ...held,
4323
+ id: row.id,
4324
+ ...row.sequence === void 0 ? {} : { sequence: row.sequence },
4325
+ ...held.lastSequence === void 0 && held.sequence === void 0 ? {} : { lastSequence: held.lastSequence ?? held.sequence },
4326
+ ...row.boxLog === void 0 ? {} : { boxLog: row.boxLog }
4327
+ };
4328
+ }
4281
4329
  function hasOlderRows(page) {
4282
4330
  return page.page.totalPages > page.page.number + 1;
4283
4331
  }
@@ -4489,6 +4537,9 @@ var CoreAgentTaskSession = class {
4489
4537
  // Whether the box the channel follows counts in the log of the history's rows. A box whose hello
4490
4538
  // names another log, or reports a log shorter than the history's, has sequences that start over.
4491
4539
  rowsInChannelLog = true;
4540
+ // The log the hello of the channel named. A reread compares its rows with it every time: the
4541
+ // flag above starts over at each reread, and a page from the old log may come again.
4542
+ channelLog;
4492
4543
  olderRead = null;
4493
4544
  get taskId() {
4494
4545
  return this._taskId;
@@ -4588,7 +4639,7 @@ var CoreAgentTaskSession = class {
4588
4639
  include: "plan"
4589
4640
  });
4590
4641
  this.historyLimit = options.limit;
4591
- this.replaceHistory(page);
4642
+ await this.rereadHistory(page);
4592
4643
  const history = this.history;
4593
4644
  this.emit("historyLoaded", { history });
4594
4645
  return history;
@@ -4607,7 +4658,7 @@ var CoreAgentTaskSession = class {
4607
4658
  return this.olderRead.promise;
4608
4659
  }
4609
4660
  async readOlder(generation) {
4610
- const oldest = this._history.find((item) => !item.id.startsWith("live:"));
4661
+ const oldest = oldestRowOf(this._history);
4611
4662
  if (!this._taskId || !this._hasOlder || !oldest) return [];
4612
4663
  let page;
4613
4664
  try {
@@ -4623,17 +4674,110 @@ var CoreAgentTaskSession = class {
4623
4674
  throw error;
4624
4675
  }
4625
4676
  if (generation !== this.historyGeneration || this.isClosed()) return [];
4626
- const older = [...page.content].reverse().map(toAgentTimelineItem);
4677
+ const rows = [...page.content].reverse().map(toAgentTimelineItem);
4678
+ const rowsLog = [...rows].reverse().find((item) => item.boxLog !== void 0)?.boxLog;
4679
+ const liveComparable = this.rowsInChannelLog && (this.channelLog === void 0 || rowsLog === void 0 || rowsLog === this.channelLog);
4680
+ const taken = /* @__PURE__ */ new Set();
4681
+ const older = rows.map((row) => {
4682
+ const held = this._history.find(
4683
+ (item) => !taken.has(item) && item.id.startsWith("live:") && samePiece(item, row)
4684
+ );
4685
+ if (held === void 0) return row;
4686
+ taken.add(held);
4687
+ return rowOrHeld(held, row, liveComparable);
4688
+ });
4627
4689
  this._hasOlder = hasOlderRows(page);
4628
- this._history = [...older, ...this._history];
4690
+ this._history = [...older, ...this._history.filter((item) => !taken.has(item))];
4629
4691
  this.emit("historyLoaded", { history: this.history });
4630
4692
  return older;
4631
4693
  }
4694
+ // A page that starts at a piece held live, with live pieces before it that no row of the page
4695
+ // takes, skipped rows the Copilot wrote between two rereads (more than a page of them): kept as
4696
+ // they are, those pieces never get their rows, and `loadOlder` only reads before the oldest row.
4697
+ // The rows before the page are read as `loadOlder` reads them, until the page reaches a row the
4698
+ // history holds or the gap's pieces all have their rows. A read of a history since replaced
4699
+ // lands nowhere (#145).
4700
+ async rereadHistory(page) {
4701
+ const generation = this.historyGeneration;
4702
+ let current = page;
4703
+ let extended = false;
4704
+ while (this._taskId && hasOlderRows(current) && this.skipsRows(current, extended)) {
4705
+ const oldest = current.content[current.content.length - 1];
4706
+ if (!oldest) break;
4707
+ let older;
4708
+ try {
4709
+ older = await this.dependencies.tasks.listMessages(this._taskId, {
4710
+ before: oldest.id,
4711
+ ...this.historyLimit !== void 0 ? { size: this.historyLimit } : {},
4712
+ sort: "createdAt,desc",
4713
+ kinds: "all",
4714
+ include: "plan"
4715
+ });
4716
+ } catch (error) {
4717
+ if (generation !== this.historyGeneration || this.isClosed()) return;
4718
+ throw error;
4719
+ }
4720
+ if (generation !== this.historyGeneration || this.isClosed()) return;
4721
+ current = { content: [...current.content, ...older.content], page: older.page };
4722
+ extended = true;
4723
+ }
4724
+ this.replaceHistory(current);
4725
+ }
4726
+ // Newest first, as the Copilot answers. Once rows before the page were read, a row the history
4727
+ // does not hold at all (one the session never heard) is still inside the gap.
4728
+ skipsRows(page, extended) {
4729
+ const rows = page.content.map(toAgentTimelineItem);
4730
+ const first = rows[rows.length - 1];
4731
+ if (!first) return false;
4732
+ const anchor = this._history.findIndex((item) => samePiece(item, first));
4733
+ if (anchor < 0) return extended;
4734
+ if (!this._history[anchor]?.id.startsWith("live:")) return false;
4735
+ for (let index = anchor - 1; index >= 0; index -= 1) {
4736
+ const held = this._history[index];
4737
+ if (!held?.id.startsWith("live:")) return false;
4738
+ if (!rows.some((row) => samePiece(held, row))) return true;
4739
+ }
4740
+ return false;
4741
+ }
4742
+ // The recovery rereads only the newest 100 rows while the turn runs: the older pages already
4743
+ // read stay, or what sits in them (the cards of subagents still running) vanishes until
4744
+ // `loadOlder` (#145). A page that does not reach the history it already has replaces it.
4632
4745
  replaceHistory(page) {
4633
- this.historyGeneration += 1;
4746
+ const oldest = oldestRowOf(this._history)?.id;
4747
+ const rows = [...page.content].reverse().map(toAgentTimelineItem);
4748
+ const rowsLog = [...rows].reverse().find((item) => item.boxLog !== void 0)?.boxLog;
4749
+ const liveComparable = this.rowsInChannelLog && (this.channelLog === void 0 || rowsLog === void 0 || rowsLog === this.channelLog);
4634
4750
  this.rowsInChannelLog = true;
4635
- this._hasOlder = hasOlderRows(page);
4636
- this._history = [...page.content].reverse().map(toAgentTimelineItem);
4751
+ const first = rows[0];
4752
+ const anchor = first ? this._history.findIndex((item) => samePiece(item, first)) : -1;
4753
+ const kept = anchor < 0 ? [] : this._history.slice(0, anchor).filter((item) => !rows.some((row) => samePiece(item, row)));
4754
+ const replaced = anchor < 0 ? this._history : this._history.slice(anchor);
4755
+ if (anchor < 0) this._hasOlder = hasOlderRows(page);
4756
+ const used = /* @__PURE__ */ new Set();
4757
+ const merged = rows.map((row) => {
4758
+ const held = this._history.find((item) => !used.has(item) && samePiece(item, row));
4759
+ if (held === void 0) return row;
4760
+ used.add(held);
4761
+ return rowOrHeld(held, row, liveComparable);
4762
+ });
4763
+ const cursor = liveComparable ? historyCursorOf(rows) : void 0;
4764
+ const unrecorded = cursor === void 0 ? [] : replaced.filter(
4765
+ (item) => !used.has(item) && item.id.startsWith("live:") && item.sequence !== void 0 && (item.kind === "plan" || item.sequence > cursor.sequence)
4766
+ );
4767
+ this._history = [...kept, ...merged, ...unrecorded];
4768
+ if (anchor < 0 || oldestRowOf(this._history)?.id !== oldest) this.historyGeneration += 1;
4769
+ if (cursor === void 0) return;
4770
+ for (const subagent of this.subagentsById.values()) {
4771
+ const row = this._history.find(
4772
+ (item) => item.kind === "tool" && item.tool.toolId === subagent.toolId
4773
+ );
4774
+ const rowStatus = row?.kind === "tool" ? row.subagent?.status : void 0;
4775
+ if (rowStatus !== void 0 && SUBAGENT_END_STATUSES.has(rowStatus)) continue;
4776
+ const applied = this.subagentSequences.get(subagent.subagentId);
4777
+ if (SUBAGENT_END_STATUSES.has(subagent.status) || applied !== void 0 && applied > cursor.sequence) {
4778
+ this.writeSubagentOnSpawn(subagent);
4779
+ }
4780
+ }
4637
4781
  }
4638
4782
  editQueueItem(id, text) {
4639
4783
  this.requireOpen();
@@ -4732,7 +4876,7 @@ var CoreAgentTaskSession = class {
4732
4876
  });
4733
4877
  const dispatch = this.dispatchSend(prompt, options, clientMessageId, handedOver, waiter).catch((error) => {
4734
4878
  waiter?.reject(error);
4735
- this.emitError("Failed to send Agent prompt", error);
4879
+ this.emitSendError(error);
4736
4880
  if (this._status === "streaming") {
4737
4881
  this.settleSteers((steered) => steered.reject(error));
4738
4882
  this.setStatus("idle");
@@ -4800,7 +4944,7 @@ var CoreAgentTaskSession = class {
4800
4944
  taken = await admitted;
4801
4945
  } catch (error) {
4802
4946
  handedOver();
4803
- this.emitError("Failed to send Agent prompt", error);
4947
+ this.emitSendError(error);
4804
4948
  return fail(error);
4805
4949
  }
4806
4950
  if (!taken) {
@@ -4870,7 +5014,7 @@ var CoreAgentTaskSession = class {
4870
5014
  }).catch((error) => {
4871
5015
  this.forgetSteer(steered);
4872
5016
  waiter?.reject(error);
4873
- this.emitError("Failed to send Agent prompt", error);
5017
+ this.emitSendError(error);
4874
5018
  }).finally(() => {
4875
5019
  this.pendingSteers -= 1;
4876
5020
  });
@@ -5062,7 +5206,7 @@ var CoreAgentTaskSession = class {
5062
5206
  kinds: "all",
5063
5207
  include: "plan"
5064
5208
  });
5065
- this.replaceHistory(page);
5209
+ await this.rereadHistory(page);
5066
5210
  this.emit("historyLoaded", { history: this.history });
5067
5211
  const rows = page.content.filter(isChatRow);
5068
5212
  const recovered = rows.find(
@@ -5216,6 +5360,7 @@ var CoreAgentTaskSession = class {
5216
5360
  break;
5217
5361
  case "hello": {
5218
5362
  const lastSequence = payload?.lastSequence;
5363
+ if (typeof payload?.boxLog === "number") this.channelLog = payload.boxLog;
5219
5364
  const history = historyCursorOf(this._history);
5220
5365
  const rowsLog = [...this._history].reverse().find((item) => item.boxLog !== void 0)?.boxLog;
5221
5366
  if (typeof payload?.boxLog === "number" && rowsLog !== void 0 && payload.boxLog !== rowsLog || typeof lastSequence === "number" && history !== void 0 && lastSequence < history.sequence) {
@@ -5692,6 +5837,12 @@ var CoreAgentTaskSession = class {
5692
5837
  ...typeof payload?.childThreadId === "string" ? { childThreadId: payload.childThreadId } : {}
5693
5838
  };
5694
5839
  this.subagentsById.set(subagentId, subagent);
5840
+ this.writeSubagentOnSpawn(subagent);
5841
+ this.emit("subagent", { ...subagent, ...sequenceOf(event) });
5842
+ }
5843
+ // The call that spawned it carries its last state, as the history records it.
5844
+ writeSubagentOnSpawn(subagent) {
5845
+ const { toolId, subagentId, status } = subagent;
5695
5846
  const index = this._history.findIndex(
5696
5847
  (item) => item.kind === "tool" && item.tool.toolId === toolId
5697
5848
  );
@@ -5709,7 +5860,6 @@ var CoreAgentTaskSession = class {
5709
5860
  }
5710
5861
  };
5711
5862
  }
5712
- this.emit("subagent", { ...subagent, ...sequenceOf(event) });
5713
5863
  }
5714
5864
  finishTurn(reason, usage, end = {}) {
5715
5865
  if (this._status !== "streaming" && this._status !== "cancelled") return;
@@ -5807,6 +5957,15 @@ var CoreAgentTaskSession = class {
5807
5957
  error: `${prefix}: ${errorMessage2(error)}`
5808
5958
  });
5809
5959
  }
5960
+ emitSendError(error) {
5961
+ const sentence = refusalSentence(error);
5962
+ if (sentence === void 0) {
5963
+ this.emitError("Failed to send Agent prompt", error);
5964
+ return;
5965
+ }
5966
+ const code = errorCode(error);
5967
+ this.emit("error", { ...code ? { code } : {}, error: sentence });
5968
+ }
5810
5969
  setStatus(status) {
5811
5970
  if (this._status === status) return;
5812
5971
  if (status !== "streaming" && status !== "cancelled") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mitralab.io/sdk-core",
3
- "version": "0.3.8",
3
+ "version": "0.3.9",
4
4
  "description": "Environment-neutral contracts and modules shared by Mitra JavaScript SDKs",
5
5
  "type": "module",
6
6
  "sideEffects": false,